Merge pull request #1359 from tsuna/master

cli/config/configfile: Atomically rewrite the config file when saving.
This commit is contained in:
Sebastiaan van Stijn 2018-09-11 12:27:47 +02:00 committed by GitHub
commit 00e6843118
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 4 deletions

View File

@ -175,15 +175,21 @@ func (configFile *ConfigFile) Save() error {
return errors.Errorf("Can't save config with empty filename")
}
if err := os.MkdirAll(filepath.Dir(configFile.Filename), 0700); err != nil {
dir := filepath.Dir(configFile.Filename)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
f, err := os.OpenFile(configFile.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
temp, err := ioutil.TempFile(dir, filepath.Base(configFile.Filename))
if err != nil {
return err
}
defer f.Close()
return configFile.SaveToWriter(f)
err = configFile.SaveToWriter(temp)
temp.Close()
if err != nil {
os.Remove(temp.Name())
return err
}
return os.Rename(temp.Name(), configFile.Filename)
}
// ParseProxyConfig computes proxy configuration by retrieving the config for the provided host and

View File

@ -2,6 +2,8 @@ package configfile
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/docker/cli/cli/config/credentials"
@ -413,3 +415,13 @@ func TestCheckKubernetesConfigurationRaiseAnErrorOnInvalidValue(t *testing.T) {
}
}
}
func TestSave(t *testing.T) {
configFile := New("test-save")
defer os.Remove("test-save")
err := configFile.Save()
assert.NilError(t, err)
cfg, err := ioutil.ReadFile("test-save")
assert.NilError(t, err)
assert.Check(t, is.Equal(string(cfg), "{\n \"auths\": {}\n}"))
}