mirror of
https://github.com/spf13/viper
synced 2025-05-10 22:27:18 +00:00
Initialize the configuration file during writing if not exist
This commit is contained in:
parent
3349bd9cc2
commit
a3d17c7a20
2 changed files with 38 additions and 2 deletions
20
viper.go
20
viper.go
|
@ -1316,7 +1316,15 @@ func WriteConfig() error { return v.WriteConfig() }
|
||||||
func (v *Viper) WriteConfig() error {
|
func (v *Viper) WriteConfig() error {
|
||||||
filename, err := v.getConfigFile()
|
filename, err := v.getConfigFile()
|
||||||
if err != nil {
|
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)
|
return v.writeConfig(filename, true)
|
||||||
}
|
}
|
||||||
|
@ -1326,7 +1334,15 @@ func SafeWriteConfig() error { return v.SafeWriteConfig() }
|
||||||
func (v *Viper) SafeWriteConfig() error {
|
func (v *Viper) SafeWriteConfig() error {
|
||||||
filename, err := v.getConfigFile()
|
filename, err := v.getConfigFile()
|
||||||
if err != nil {
|
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)
|
return v.writeConfig(filename, false)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1243,6 +1243,26 @@ func TestWriteConfigYAML(t *testing.T) {
|
||||||
assert.Equal(t, yamlWriteExpected, read)
|
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(`
|
var yamlMergeExampleTgt = []byte(`
|
||||||
hello:
|
hello:
|
||||||
pop: 37890
|
pop: 37890
|
||||||
|
|
Loading…
Add table
Reference in a new issue