From 48e0b61d8cc0a63aecff14f774ff3faf696df021 Mon Sep 17 00:00:00 2001 From: g3rk6 Date: Tue, 8 Sep 2015 03:25:36 -0400 Subject: [PATCH] Added method to write into TOML file. --- viper.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/viper.go b/viper.go index 389a58e..270abcc 100644 --- a/viper.go +++ b/viper.go @@ -20,6 +20,7 @@ package viper import ( + "bufio" "bytes" "fmt" "io" @@ -31,6 +32,7 @@ import ( "strings" "time" + "github.com/BurntSushi/toml" "github.com/kr/pretty" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" @@ -874,6 +876,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 +} + // Set the default value for this key. // Default only used when no value is provided by the user via flag, config or ENV. func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }