diff --git a/viper.go b/viper.go index 4ed2d40..04f55ea 100644 --- a/viper.go +++ b/viper.go @@ -20,7 +20,9 @@ package viper import ( + "bufio" "bytes" + "encoding/json" "fmt" "io" "log" @@ -30,12 +32,15 @@ import ( "strings" "time" + "github.com/BurntSushi/toml" "github.com/fsnotify/fsnotify" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" jww "github.com/spf13/jwalterweatherman" "github.com/spf13/pflag" + "gopkg.in/fsnotify.v1" + "gopkg.in/yaml.v2" ) var v *Viper @@ -1039,6 +1044,50 @@ 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()) + if err != nil { + return err + } + defer f.Close() + + switch v.getConfigType() { + case "json": + + b, err := json.MarshalIndent(v.AllSettings(), "", " ") + if err != nil { + jww.FATAL.Println("Panic while encoding into JSON format.") + } + f.WriteString(string(b)) + + case "toml": + + w := bufio.NewWriter(f) + if err := toml.NewEncoder(w).Encode(v.AllSettings()); err != nil { + jww.FATAL.Println("Panic while encoding into TOML format.") + } + w.Flush() + + case "yaml", "yml": + + b, err := yaml.Marshal(v.AllSettings()) + if err != nil { + jww.FATAL.Println("Panic while encoding into YAML format.") + } + f.WriteString(string(b)) + } + + 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.