Skip to content

Commit

Permalink
Fix atomicwrite for Windows
Browse files Browse the repository at this point in the history
os.Rename does not overwrite on Windows
  • Loading branch information
mattn committed Jan 10, 2020
1 parent e639ee7 commit 803055a
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand All @@ -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 {
Expand All @@ -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
}
}

0 comments on commit 803055a

Please sign in to comment.