Use defaultConfigFile if configFile is not exist

This commit is contained in:
koooge 2018-05-23 18:01:59 +00:00
parent 15738813a0
commit c21acdd422
1 changed files with 20 additions and 2 deletions

View File

@ -1211,7 +1211,10 @@ 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 filename, err = v.getDefaultConfigFile()
if err != nil {
return err
}
} }
return v.writeConfig(filename, true) return v.writeConfig(filename, true)
} }
@ -1221,11 +1224,26 @@ 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 filename, err = v.getDefaultConfigFile()
if err != nil {
return err
}
} }
return v.writeConfig(filename, false) return v.writeConfig(filename, false)
} }
func (v *Viper) getDefaultConfigFile() (string, error) {
if v.configName == "" {
return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
}
if len(v.configPaths) == 0 {
return v.configName + "." + SupportedExts[0], nil
} else {
return filepath.Join(v.configPaths[0], v.configName+"."+SupportedExts[0]), nil
}
}
// WriteConfigAs writes current configuration to a given filename. // WriteConfigAs writes current configuration to a given filename.
func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) } func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) }
func (v *Viper) WriteConfigAs(filename string) error { func (v *Viper) WriteConfigAs(filename string) error {