Avoid partial file writes by writing to a tmp file and then renaming

This commit is contained in:
David Dworken 2022-10-14 16:42:47 -07:00
parent 51c4792e84
commit bb36a30ded

View File

@ -195,10 +195,14 @@ func SetConfig(config ClientConfig) error {
if err != nil { if err != nil {
return err return err
} }
err = os.WriteFile(path.Join(homedir, shared.HISHTORY_PATH, shared.CONFIG_PATH), serializedConfig, 0o600) err = os.WriteFile(path.Join(homedir, shared.HISHTORY_PATH, shared.CONFIG_PATH+".tmp"), serializedConfig, 0o600)
if err != nil { if err != nil {
return fmt.Errorf("failed to write config: %v", err) return fmt.Errorf("failed to write config: %v", err)
} }
err = os.Rename(path.Join(homedir, shared.HISHTORY_PATH, shared.CONFIG_PATH+".tmp"), path.Join(homedir, shared.HISHTORY_PATH, shared.CONFIG_PATH))
if err != nil {
return fmt.Errorf("failed to replace config file with the rewritten version: %v", err)
}
return nil return nil
} }