Skip to content

Commit e557351

Browse files
committed
Fix atomicwrite for Windows
os.Rename does not overwrite on Windows
1 parent ba48d8c commit e557351

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

config/config.go

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,11 @@ func ensureConfiguration() error {
140140

141141
defaultContextPath := filepath.Join(contextsPath, defaultContextFileName)
142142
if _, err := os.Stat(defaultContextPath); os.IsNotExist(err) {
143-
_, err = os.Create(defaultContextPath)
143+
f, err := os.Create(defaultContextPath)
144144
if err != nil {
145145
return fmt.Errorf("error creating default.yaml context file %v", err)
146146
}
147+
defer f.Close()
147148

148149
err = WriteYamlFile(defaultContextPath, DefaultContextConfigContents())
149150
if err != nil {
@@ -250,13 +251,7 @@ func WriteConfigValueToConfigFile(key, value string) error {
250251
home := GetHomeDir()
251252

252253
configFilePath := filepath.Join(home, rootConfigPathName, contextConfigFileName)
253-
f, err := os.OpenFile(configFilePath, os.O_RDWR, ReadWritePerms)
254-
if err != nil {
255-
return err
256-
}
257-
defer f.Close()
258-
259-
file, err := DecodeYAMLFile(f.Name())
254+
file, err := DecodeYAMLFile(configFilePath)
260255
if err != nil {
261256
return err
262257
}
@@ -271,7 +266,7 @@ func WriteConfigValueToConfigFile(key, value string) error {
271266
}
272267
configValues[key] = value
273268

274-
err = atomicwrite(f.Name(), &configValues)
269+
err = atomicwrite(configFilePath, &configValues)
275270
if err != nil {
276271
return err
277272
}
@@ -288,13 +283,14 @@ func atomicwrite(file string, c *ContextMap) (err error) {
288283
return fmt.Errorf("cannot create temp file: %v", err)
289284
}
290285

291-
defer f.Close()
292286
defer os.Remove(f.Name())
293287

294288
err = WriteYamlFile(f.Name(), c)
295289
if err != nil {
290+
f.Close()
296291
return err
297292
}
293+
f.Close()
298294

299295
info, err := os.Stat(file)
300296
if err != nil {
@@ -303,6 +299,8 @@ func atomicwrite(file string, c *ContextMap) (err error) {
303299
_ = os.Chmod(f.Name(), info.Mode())
304300
}
305301

302+
os.Remove(file)
303+
306304
// replace file with the tempfile
307305
err = os.Rename(f.Name(), file)
308306
if err != nil {

0 commit comments

Comments
 (0)