Skip to content
Merged
Prev Previous commit
Next Next commit
refactor: unify atomic file writes into internal/atomicfile
  • Loading branch information
kyya committed Nov 28, 2026
commit 2ea2200827c11a6d70f04fe7395ea5fcd82625e1
12 changes: 2 additions & 10 deletions brand_fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/egoist/mygo/ui"
"gorex/internal/atomicfile"
"gorex/internal/homedir"
)

Expand Down Expand Up @@ -130,16 +131,7 @@ func fetchBrandSVG(id, baseURL string) {

if dir := brandCacheDir(); dir != "" {
if os.MkdirAll(dir, 0o755) == nil {
if tmp, err := os.CreateTemp(dir, id+".*.tmp"); err == nil {
tmpName := tmp.Name()
_, werr := tmp.Write(data)
cerr := tmp.Close()
if werr == nil && cerr == nil {
_ = os.Rename(tmpName, filepath.Join(dir, id+".svg"))
} else {
_ = os.Remove(tmpName)
}
}
_ = atomicfile.Write(filepath.Join(dir, id+".svg"), data, 0o644)
}
}

Expand Down
5 changes: 3 additions & 2 deletions debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/terminal"

"gorex/internal/atomicfile"
"gorex/locales"
)

Expand Down Expand Up @@ -181,7 +182,7 @@ func (st *store) debug(dir, line string) {
var b []byte
debugMain(func() { b, _ = json.MarshalIndent(st.state(), "", " ") })
path := filepath.Join(dir, arg)
writeFileAtomic(path, b, 0o644)
atomicfile.Write(path, b, 0o644)
return
}
if a == nil {
Expand Down Expand Up @@ -309,7 +310,7 @@ func (a *App) debug(dir, line string) {
}
b, _ := json.MarshalIndent(a.panesDump(), "", " ")
path := filepath.Join(dir, name)
writeFileAtomic(path, b, 0o644)
atomicfile.Write(path, b, 0o644)
return
}
win := a.win
Expand Down
3 changes: 2 additions & 1 deletion hostlayout.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"slices"
"sort"

"gorex/internal/atomicfile"
"gorex/internal/layout"
"gorex/internal/rex"
)
Expand Down Expand Up @@ -400,7 +401,7 @@ func readHostCache() map[string]savedStore {

func writeHostCache(all map[string]savedStore) {
b, _ := json.Marshal(all)
if err := writeFileAtomic(hostCachePath(), b, 0o600); err != nil {
if err := atomicfile.Write(hostCachePath(), b, 0o600); err != nil {
log.Printf("gorex: keeping the hosts' layouts: %v", err)
}
}
Expand Down
81 changes: 81 additions & 0 deletions internal/atomicfile/atomicfile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Package atomicfile writes files atomically through a temporary file in the
// destination directory followed by a rename, with a retry loop on Windows for
// transient sharing violations while a reader has the target open.
package atomicfile

import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"time"
)

// Write writes data to path through a temporary file beside it and renames it
// into place. A crash or failure leaves either the previous file or the new
// content, never a partial write. The parent directory must already exist.
func Write(path string, data []byte, perm os.FileMode) error {
return write(path, data, perm, false)
}

// WriteSync behaves like Write and calls Sync on the temporary file before
// closing and renaming it.
func WriteSync(path string, data []byte, perm os.FileMode) error {
return write(path, data, perm, true)
}

// WriteJSON marshals v as indented JSON with a trailing newline, creates parent
// directories if needed (0o700 for user-only perm, else 0o755), and writes path
// atomically.
func WriteJSON(path string, v any, perm os.FileMode) error {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
b = append(b, '\n')
dirPerm := os.FileMode(0o755)
if perm&0o077 == 0 {
dirPerm = 0o700
}
if err := os.MkdirAll(filepath.Dir(path), dirPerm); err != nil {
return err
}
return write(path, b, perm, false)
}

func write(path string, data []byte, perm os.FileMode, syncFile bool) error {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
name := f.Name()
_, err = f.Write(data)
if err == nil && syncFile {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Chmod(name, perm)
}
if err == nil {
err = rename(name, path)
}
if err != nil {
_ = os.Remove(name)
}
return err
}

func rename(src, dst string) error {
err := os.Rename(src, dst)
// On Windows the rename fails while a reader (such as the app's poll of
// lan-status.json) has dst open: retry briefly rather than lose the write.
for i := 0; err != nil && runtime.GOOS == "windows" && i < 50; i++ {
time.Sleep(10 * time.Millisecond)
err = os.Rename(src, dst)
}
return err
}
76 changes: 76 additions & 0 deletions internal/atomicfile/atomicfile_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package atomicfile

import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
)

func TestWrite(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "f.json")
if err := os.WriteFile(path, []byte("old"), 0o600); err != nil {
t.Fatal(err)
}
if err := Write(path, []byte("new"), 0o644); err != nil {
t.Fatal(err)
}
if b, err := os.ReadFile(path); err != nil || string(b) != "new" {
t.Fatalf("file has %q (err=%v), want new", b, err)
}
if es, err := os.ReadDir(dir); err != nil || len(es) != 1 {
t.Fatalf("dir has %d files (err=%v), want 1", len(es), err)
}
if runtime.GOOS == "windows" {
return
}
if err := os.Chmod(dir, 0o500); err != nil {
t.Fatal(err)
}
defer func() { _ = os.Chmod(dir, 0o700) }()
if Write(path, []byte("newer"), 0o644) == nil {
t.Skip("directory is writable all the same (root)")
}
if b, err := os.ReadFile(path); err != nil || string(b) != "new" {
t.Fatalf("failed write left %q (err=%v), want new", b, err)
}
}

func TestWriteSync(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sync.txt")
if err := WriteSync(path, []byte("synced"), 0o600); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(path)
if err != nil || string(b) != "synced" {
t.Fatalf("got %q, %v; want synced", b, err)
}
}

func TestWriteJSON(t *testing.T) {
dir := filepath.Join(t.TempDir(), "nested")
path := filepath.Join(dir, "cfg.json")
in := map[string]int{"a": 1}
if err := WriteJSON(path, in, 0o600); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var out map[string]int
if err := json.Unmarshal(b, &out); err != nil || out["a"] != 1 {
t.Fatalf("got %q -> %v, %v", b, out, err)
}
// Unmarshalable value returns an error without creating a file.
bad := filepath.Join(dir, "bad.json")
if err := WriteJSON(bad, make(chan int), 0o600); err == nil {
t.Fatal("expected marshal error, got nil")
}
if _, err := os.Stat(bad); !os.IsNotExist(err) {
t.Fatalf("bad.json should not exist, stat err = %v", err)
}
}
32 changes: 3 additions & 29 deletions internal/cli/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"path/filepath"
"runtime"
"strings"

"gorex/internal/atomicfile"
)

// hookCommand is what an agent's session-start hook runs. The trailing
Expand Down Expand Up @@ -93,35 +95,7 @@ func writeObject(path string, root map[string]any) error {
if err := enc.Encode(root); err != nil {
return err
}
b := buf.Bytes()
tmp, err := os.CreateTemp(filepath.Dir(path), ".settings-*")
if err != nil {
return err
}
name := tmp.Name()
if _, err := tmp.Write(b); err != nil {
tmp.Close()
os.Remove(name)
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
os.Remove(name)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(name)
return err
}
if err := os.Chmod(name, 0o600); err != nil {
os.Remove(name)
return err
}
if err := os.Rename(name, path); err != nil {
os.Remove(name)
return err
}
return nil
return atomicfile.WriteSync(path, buf.Bytes(), 0o600)
}

// hooksObject returns the hooks map and the SessionStart array, refusing
Expand Down
4 changes: 2 additions & 2 deletions internal/cli/pack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ func TestPackInstallTheme(t *testing.T) {
{"config", "user.email", "test@example.com"},
{"config", "user.name", "Test"},
{"add", "."},
{"commit", "-m", "init"},
{"commit", "--no-verify", "-m", "init"},
} {
c := exec.Command("git", args...)
c.Dir = repo
Expand Down Expand Up @@ -310,7 +310,7 @@ func TestPackUpdate(t *testing.T) {
os.WriteFile(filepath.Join(iconDir, "pack.json"), []byte(`{"schema":1,"id":"tools","name":"Tools","version":"`+version+`","programs":{"mycli":{"icon":"icons/app.svg","bg":"#112233"}}}`), 0o644)
os.WriteFile(filepath.Join(themeDir, "theme.json"), []byte(manifest), 0o644)
git("add", ".")
git("commit", "-q", "-m", version)
git("commit", "--no-verify", "-q", "-m", version)
return git("rev-parse", "HEAD")
}
git("init", "-q", "-b", "main")
Expand Down
26 changes: 3 additions & 23 deletions internal/cli/skill.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"runtime"
"strings"
"text/tabwriter"

"gorex/internal/atomicfile"
)

// The skill is a stub: it points at the guide the installed binary prints,
Expand Down Expand Up @@ -586,29 +588,7 @@ func installSkill(dir, content string, force, dry bool) (string, error) {
return "failed", err
}
path := filepath.Join(dir, "SKILL.md")
tmp, err := os.CreateTemp(dir, ".SKILL.md-*")
if err != nil {
return "failed", err
}
name := tmp.Name()
cleanup := func() {
tmp.Close()
os.Remove(name)
}
if _, err := tmp.WriteString(content); err != nil {
cleanup()
return "failed", err
}
if err := tmp.Close(); err != nil {
os.Remove(name)
return "failed", err
}
if err := os.Chmod(name, 0o644); err != nil {
os.Remove(name)
return "failed", err
}
if err := os.Rename(name, path); err != nil {
os.Remove(name)
if err := atomicfile.Write(path, []byte(content), 0o644); err != nil {
return "failed", err
}
if state == "missing" {
Expand Down
27 changes: 3 additions & 24 deletions internal/hosts/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"path/filepath"
"slices"
"strings"

"gorex/internal/atomicfile"
)

// Host is a remote host as hosts.json keeps it.
Expand Down Expand Up @@ -97,28 +99,5 @@ func Save(dir string, list []Host) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
return writeAtomic(path, b, 0o600)
}

// writeAtomic writes data to path through a file beside it, renamed over
// it: a crash leaves the old file or the new one, not half of either.
func writeAtomic(path string, data []byte, perm os.FileMode) error {
f, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
_, err = f.Write(data)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Chmod(f.Name(), perm)
}
if err == nil {
err = os.Rename(f.Name(), path)
}
if err != nil {
os.Remove(f.Name())
}
return err
return atomicfile.Write(path, b, 0o600)
}
Loading