diff --git a/viper.go b/viper.go index 31b41a6..83077b3 100644 --- a/viper.go +++ b/viper.go @@ -20,6 +20,7 @@ package viper import ( + "bufio" "bytes" "encoding/csv" "fmt" @@ -31,6 +32,7 @@ import ( "strings" "time" + "github.com/BurntSushi/toml" "github.com/fsnotify/fsnotify" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" @@ -53,7 +55,7 @@ func init() { type remoteConfigFactory interface { Get(rp RemoteProvider) (io.Reader, error) Watch(rp RemoteProvider) (io.Reader, error) - WatchChannel(rp RemoteProvider)(<-chan *RemoteResponse, chan bool) + WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool) } // RemoteConfig is optional, see the remote package @@ -1067,6 +1069,32 @@ func (v *Viper) InConfig(key string) bool { return exists } +// Save configuration to file +func SaveConfig() error { return v.SaveConfig() } +func (v *Viper) SaveConfig() error { + + jww.INFO.Println("Attempting to write config into the file") + if !stringInSlice(v.getConfigType(), SupportedExts) { + return UnsupportedConfigError(v.getConfigType()) + } + + f, err := os.Create(v.getConfigFile()) + defer f.Close() + + if err != nil { + return err + } + + w := bufio.NewWriter(f) + + if err := toml.NewEncoder(w).Encode(v.AllSettings()); err != nil { + jww.FATAL.Println("Panic while writing into the file") + } + w.Flush() + + return nil +} + // SetDefault sets the default value for this key. // SetDefault is case-insensitive for a key. // Default only used when no value is provided by the user via flag, config or ENV.