From 497fce2145d019714ddc5567002b4d115ca657e2 Mon Sep 17 00:00:00 2001 From: Rodrigo Chiossi Date: Tue, 30 Jan 2018 10:15:47 +0000 Subject: [PATCH] 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 --- viper.go | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/viper.go b/viper.go index ad8a037..ed6fb17 100644 --- a/viper.go +++ b/viper.go @@ -1246,15 +1246,9 @@ func (v *Viper) writeConfig(filename string, force bool) error { if v.config == nil { v.config = make(map[string]interface{}) } - var flags int - if force == true { - flags = os.O_CREATE | os.O_TRUNC | os.O_WRONLY - } 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) - } + flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY + if !force { + flags |= os.O_EXCL } f, err := v.fs.OpenFile(filename, flags, os.FileMode(0644)) if err != nil {