Initialize the configuration file during writing if not exist

This commit is contained in:
Ryan SIU 2019-07-26 14:01:37 +08:00
parent 3349bd9cc2
commit a3d17c7a20
2 changed files with 38 additions and 2 deletions

View file

@ -1316,7 +1316,15 @@ func WriteConfig() error { return v.WriteConfig() }
func (v *Viper) WriteConfig() error {
filename, err := v.getConfigFile()
if err != nil {
return err
ext := SupportedExts[0]
if v.configType != "" {
ext = v.configType
}
path := ""
if len(v.configPaths) > 0 {
path = v.configPaths[0]
}
filename = filepath.Join(path, v.configName+"."+ext)
}
return v.writeConfig(filename, true)
}
@ -1326,7 +1334,15 @@ func SafeWriteConfig() error { return v.SafeWriteConfig() }
func (v *Viper) SafeWriteConfig() error {
filename, err := v.getConfigFile()
if err != nil {
return err
ext := SupportedExts[0]
if v.configType != "" {
ext = v.configType
}
path := ""
if len(v.configPaths) > 0 {
path = v.configPaths[0]
}
filename = filepath.Join(path, v.configName+"."+ext)
}
return v.writeConfig(filename, false)
}

View file

@ -1243,6 +1243,26 @@ func TestWriteConfigYAML(t *testing.T) {
assert.Equal(t, yamlWriteExpected, read)
}
func TestWriteNotExistTarget(t *testing.T) {
v := New()
fs := afero.NewMemMapFs()
v.SetFs(fs)
v.SetConfigName("c")
v.SetConfigType("yaml")
err := v.ReadConfig(bytes.NewBuffer(yamlExample))
if err != nil {
t.Fatal(err)
}
if err := v.WriteConfig(); err != nil {
t.Fatal(err)
}
read, err := afero.ReadFile(fs, "c.yaml")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, yamlWriteExpected, read)
}
var yamlMergeExampleTgt = []byte(`
hello:
pop: 37890