mirror of
https://github.com/spf13/viper
synced 2024-12-23 20:17:03 +00:00
Merge remote-tracking branch 'g3rk6/master' into feature/write-config
This commit is contained in:
commit
a16df4f05e
1 changed files with 49 additions and 0 deletions
49
viper.go
49
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.
|
||||
|
|
Loading…
Reference in a new issue