From e557351bb8aa131fad15402b820aa8165f9ed93a Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Thu, 23 Jul 2020 00:53:52 +0900 Subject: [PATCH] Fix atomicwrite for Windows os.Rename does not overwrite on Windows --- config/config.go | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/config/config.go b/config/config.go index d1d0c711c..5650de36a 100644 --- a/config/config.go +++ b/config/config.go @@ -140,10 +140,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 { @@ -250,13 +251,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 } @@ -271,7 +266,7 @@ func WriteConfigValueToConfigFile(key, value string) error { } configValues[key] = value - err = atomicwrite(f.Name(), &configValues) + err = atomicwrite(configFilePath, &configValues) if err != nil { return err } @@ -288,13 +283,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 { @@ -303,6 +299,8 @@ 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 {