mirror of
https://github.com/spf13/viper
synced 2024-12-23 03:57:01 +00:00
Fix SafeWriteConfig
If the config file does not exist and the force flag is not set, OpenFile would not use O_CREATE flag, causing viper to fail with error "File not exist" and to not create the config file. This patch changes the behavior of writeConfig() so that if force is set to false, OpenFile will use O_EXCL flag, thus failing if the file already exists or creating a new file otherwise. Signed-off-by: Rodrigo Chiossi <rodrigo.chiossi@intel.com>
This commit is contained in:
parent
e02bc9eca5
commit
cdccc8152c
1 changed files with 3 additions and 9 deletions
12
viper.go
12
viper.go
|
@ -1364,15 +1364,9 @@ func (v *Viper) writeConfig(filename string, force bool) error {
|
||||||
if v.config == nil {
|
if v.config == nil {
|
||||||
v.config = make(map[string]interface{})
|
v.config = make(map[string]interface{})
|
||||||
}
|
}
|
||||||
var flags int
|
flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
|
||||||
if force == true {
|
if !force {
|
||||||
flags = os.O_CREATE | os.O_TRUNC | os.O_WRONLY
|
flags |= os.O_EXCL
|
||||||
} else {
|
|
||||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
|
||||||
flags = os.O_WRONLY
|
|
||||||
} else {
|
|
||||||
return fmt.Errorf("File: %s exists. Use WriteConfig to overwrite.", filename)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
|
f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
Loading…
Reference in a new issue