This commit is contained in:
Alessandro (Ale) Segala 2024-05-12 18:06:07 -07:00 committed by GitHub
commit 952532e2ca
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1774,17 +1774,27 @@ func (v *Viper) writeConfig(filename string, force bool) error {
if v.config == nil {
v.config = make(map[string]any)
}
flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
if !force {
flags |= os.O_EXCL
}
f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
exists, err := afero.Exists(v.fs, filename)
if err != nil {
return err
}
if exists && !force {
return fmt.Errorf("file already exists: %s", filename)
}
f, err := afero.TempFile(v.fs, filepath.Dir(filename), filepath.Base(filename)+"-")
if err != nil {
return err
}
defer f.Close()
if err := v.marshalWriter(f, configType); err != nil {
f.Close()
return err
}
f.Close()
err = v.fs.Rename(f.Name(), filename)
if err != nil {
return err
}