From a3d17c7a2036afca430a814c641dc8c24b418f88 Mon Sep 17 00:00:00 2001 From: Ryan SIU Date: Fri, 26 Jul 2019 14:01:37 +0800 Subject: [PATCH] Initialize the configuration file during writing if not exist --- viper.go | 20 ++++++++++++++++++-- viper_test.go | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/viper.go b/viper.go index 0699c4c..9eb9f84 100644 --- a/viper.go +++ b/viper.go @@ -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) } diff --git a/viper_test.go b/viper_test.go index c40c971..e940491 100644 --- a/viper_test.go +++ b/viper_test.go @@ -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