From 803055a5a5b5ee38a4b8bf77dd53e26582bff44e Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Fri, 10 Jan 2020 16:36:18 +0900 Subject: [PATCH] Fix atomicwrite for Windows os.Rename does not overwrite on Windows --- config/config.go | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/config/config.go b/config/config.go index 049716f8..8558bd05 100644 --- a/config/config.go +++ b/config/config.go @@ -2,10 +2,10 @@ package config import ( "fmt" + "io/ioutil" "os" "path/filepath" "strings" - "io/ioutil" "github.com/fnproject/fn_go/provider" "github.com/spf13/viper" @@ -72,6 +72,7 @@ func ensureConfiguration() error { if err != nil { return fmt.Errorf("error creating config.yaml file %v", err) } + defer file.Close() err = WriteYamlFile(file.Name(), defaultRootConfigContents) if err != nil { @@ -87,10 +88,11 @@ func ensureConfiguration() error { defaultContextPath := filepath.Join(contextsPath, defaultContextFileName) if _, err := os.Stat(defaultContextPath); os.IsNotExist(err) { - _, err = os.Create(defaultContextPath) + f, err := os.Create(defaultContextPath) if err != nil { return fmt.Errorf("error creating default.yaml context file %v", err) } + defer f.Close() err = WriteYamlFile(defaultContextPath, DefaultContextConfigContents) if err != nil { @@ -149,13 +151,7 @@ func WriteConfigValueToConfigFile(key, value string) error { home := GetHomeDir() configFilePath := filepath.Join(home, rootConfigPathName, contextConfigFileName) - f, err := os.OpenFile(configFilePath, os.O_RDWR, ReadWritePerms) - if err != nil { - return err - } - defer f.Close() - - file, err := DecodeYAMLFile(f.Name()) + file, err := DecodeYAMLFile(configFilePath) if err != nil { return err } @@ -170,7 +166,7 @@ func WriteConfigValueToConfigFile(key, value string) error { } configValues[key] = value - err = atomicwrite(f.Name(), &configValues) + err = atomicwrite(configFilePath, &configValues) if err != nil { return err } @@ -187,13 +183,14 @@ func atomicwrite(file string, c *ContextMap) (err error) { return fmt.Errorf("cannot create temp file: %v", err) } - defer f.Close() defer os.Remove(f.Name()) err = WriteYamlFile(f.Name(), c) if err != nil { + f.Close() return err } + f.Close() info, err := os.Stat(file) if err != nil { @@ -202,10 +199,12 @@ func atomicwrite(file string, c *ContextMap) (err error) { _ = os.Chmod(f.Name(), info.Mode()) } + os.Remove(file) + // replace file with the tempfile err = os.Rename(f.Name(), file) - if err !=nil { - return fmt.Errorf("error replacing file with tempfile") + if err != nil { + return fmt.Errorf("error replacing file with tempfile: %v", err) } return nil -} \ No newline at end of file +}