Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write configuration only if encoding succeeds #1501

Merged
merged 1 commit into from
Aug 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions authority/config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"bytes"
"encoding/json"
"fmt"
"net"
Expand Down Expand Up @@ -258,15 +259,16 @@ func (c *Config) Init() {

// Save saves the configuration to the given filename.
func (c *Config) Save(filename string) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return errors.Wrapf(err, "error opening %s", filename)
}
defer f.Close()

enc := json.NewEncoder(f)
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetIndent("", "\t")
return errors.Wrapf(enc.Encode(c), "error writing %s", filename)
if err := enc.Encode(c); err != nil {
return fmt.Errorf("error encoding configuration: %w", err)
}
if err := os.WriteFile(filename, b.Bytes(), 0600); err != nil {
return fmt.Errorf("error writing %q: %w", filename, err)
}
return nil
}

// Commit saves the current configuration to the same
Expand Down