Skip to content

Commit

Permalink
settings: Perform write process atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeKar committed Aug 29, 2024
1 parent f140c1f commit 42e896f
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions internal/config/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -150,6 +151,13 @@ var (
VolatileSettings map[string]bool
)

func writeFile(name string, txt []byte) error {
if _, err := os.Stat(name); errors.Is(err, fs.ErrNotExist) {
return os.WriteFile(name, txt, util.FileMode)
}
return util.SafeWriteInternal(name, txt, false)
}

func init() {
ModifiedSettings = make(map[string]bool)
VolatileSettings = make(map[string]bool)
Expand Down Expand Up @@ -341,7 +349,8 @@ func WriteSettings(filename string) error {
}

txt, _ := json.MarshalIndent(parsedSettings, "", " ")
err = os.WriteFile(filename, append(txt, '\n'), util.FileMode)
txt = append(txt, '\n')
err = writeFile(filename, txt)
}
return err
}
Expand All @@ -362,8 +371,9 @@ func OverwriteSettings(filename string) error {
}
}

txt, _ := json.MarshalIndent(settings, "", " ")
err = os.WriteFile(filename, append(txt, '\n'), util.FileMode)
txt, _ := json.MarshalIndent(parsedSettings, "", " ")
txt = append(txt, '\n')
err = writeFile(filename, txt)
}
return err
}
Expand Down

0 comments on commit 42e896f

Please sign in to comment.