Skip to content

Commit

Permalink
bindings: Perform write process atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeKar committed Sep 3, 2024
1 parent 2e8a2c6 commit 0850acb
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions internal/action/bindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,16 @@ var Binder = map[string]func(e Event, action string){
"terminal": TermMapEvent,
}

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 createBindingsIfNotExist(fname string) {
if _, e := os.Stat(fname); errors.Is(e, fs.ErrNotExist) {
os.WriteFile(fname, []byte("{}"), util.FileMode)
writeFile(fname, []byte("{}"))
}
}

Expand Down Expand Up @@ -305,7 +312,8 @@ func TryBindKey(k, v string, overwrite bool) (bool, error) {
BindKey(k, v, Binder["buffer"])

txt, _ := json.MarshalIndent(parsed, "", " ")
return true, os.WriteFile(filename, append(txt, '\n'), util.FileMode)
txt = append(txt, '\n')
return true, writeFile(filename, txt)
}
return false, e
}
Expand Down Expand Up @@ -355,7 +363,8 @@ func UnbindKey(k string) error {
}

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

0 comments on commit 0850acb

Please sign in to comment.