diff --git a/internal/app/plugin_bridge_files.go b/internal/app/plugin_bridge_files.go index 9437c02..dda63c3 100644 --- a/internal/app/plugin_bridge_files.go +++ b/internal/app/plugin_bridge_files.go @@ -13,6 +13,7 @@ import ( "time" "unicode/utf8" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/plugin" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -226,12 +227,7 @@ func (a *App) panelFileCall(mgr *plugin.Manager, pluginID, method string, params if len(data) > maxPanelFileBytes { return nil, fmt.Errorf("data exceeds %d bytes", maxPanelFileBytes) } - tmp := path + "." + id + ".reims-plugin-tmp" - if err := os.WriteFile(tmp, data, 0o600); err != nil { - return nil, err - } - if err := os.Rename(tmp, path); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.Write(path, data, 0o600); err != nil { return nil, err } return map[string]any{"ok": true, "name": filepath.Base(path), "size": len(data)}, nil diff --git a/internal/app/secret_materialize_flow.go b/internal/app/secret_materialize_flow.go index 2a35131..6edc5e8 100644 --- a/internal/app/secret_materialize_flow.go +++ b/internal/app/secret_materialize_flow.go @@ -14,6 +14,7 @@ import ( "sync" "unicode/utf16" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/plugin" ) @@ -170,37 +171,10 @@ func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, plug } func writeSecretFile(dest string, content []byte) error { - dir := filepath.Dir(dest) - if err := os.MkdirAll(dir, 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { return err } - tmp, err := os.CreateTemp(dir, ".secret-*") - if err != nil { - return err - } - tmpName := tmp.Name() - ok := false - defer func() { - if !ok { - _ = os.Remove(tmpName) - } - }() - if err := tmp.Chmod(0o600); err != nil { - _ = tmp.Close() - return err - } - if _, err := tmp.Write(content); err != nil { - _ = tmp.Close() - return err - } - if err := tmp.Close(); err != nil { - return err - } - if err := os.Rename(tmpName, dest); err != nil { - return err - } - ok = true - return nil + return atomicfile.Write(dest, content, 0o600) } func (a *App) materializedSecretsPath() string { @@ -234,18 +208,10 @@ func saveMaterializedSecrets(path string, doc materializedSecretsFile) error { } return nil } - raw, err := json.MarshalIndent(doc, "", " ") - if err != nil { - return err - } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } - tmp := path + ".tmp" - if err := os.WriteFile(tmp, raw, 0o600); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(path, doc, 0o600) } func samePath(a, b string) bool { return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) } diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 20bc9d9..6ee9665 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -18,6 +18,7 @@ import ( "sync" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" @@ -289,10 +290,7 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, return VMThumbnail{}, false } if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil { - part := path + ".part" - if os.WriteFile(part, jpg, 0o644) == nil { - _ = os.Rename(part, path) - } + _ = atomicfile.Write(path, jpg, 0o644) } return VMThumbnail{ DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg), diff --git a/internal/archtest/file_replace_test.go b/internal/archtest/file_replace_test.go new file mode 100644 index 0000000..e6d1056 --- /dev/null +++ b/internal/archtest/file_replace_test.go @@ -0,0 +1,58 @@ +package archtest + +import ( + "go/ast" + "testing" +) + +// renameOwners move something atomicfile cannot write: a directory, an image or +// download too large for memory, a rotated log, the running executable, or +// several files that must change together. +var renameOwners = map[string]bool{ + "internal/app/guesttools_flow.go": true, // file copied into the shared folder + "internal/app/ui_health.go": true, // log rotation + "internal/atomicfile/atomicfile.go": true, + "internal/fetch/fetch.go": true, // download + "internal/macos/installer/accelerated.go": true, // download + "internal/macos/installer/hfs_image.go": true, // disk image + "internal/macos/installer/oc_cache.go": true, // download + "internal/macos/installer/recovery.go": true, // download + "internal/macos/installguide/progress.go": true, // macOS may not import atomicfile, see macosHostImports + "internal/macos/reims/network_record.go": true, // same + "internal/macos/opencore/image.go": true, // disk image with rollback + "internal/macos/reims/disk_import.go": true, // disk image with rollback + "internal/macos/reims/suspend_transaction.go": true, // state and metadata commit together + "internal/plugin/broker.go": true, // log rotation + "internal/plugin/pack.go": true, // archive + "internal/plugin/package.go": true, // plugin directory + "internal/runtime/runtime.go": true, // runtime directory + "internal/selfupdate/selfupdate.go": true, // running executable +} + +func TestSmallFilesAreReplacedThroughAtomicfile(t *testing.T) { + seen := map[string]bool{} + for _, s := range sources(t) { + if s.isTest() { + continue + } + ast.Inspect(s.file, func(n ast.Node) bool { + sel, ok := n.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Rename" { + return true + } + if pkg, ok := sel.X.(*ast.Ident); !ok || pkg.Name != "os" { + return true + } + seen[s.rel] = true + if !renameOwners[s.rel] { + t.Errorf("%s calls os.Rename: write small files with atomicfile.Write or atomicfile.WriteJSON", s.rel) + } + return true + }) + } + for rel := range renameOwners { + if !seen[rel] { + t.Errorf("%s no longer calls os.Rename: remove it from renameOwners", rel) + } + } +} diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go new file mode 100644 index 0000000..9020b92 --- /dev/null +++ b/internal/atomicfile/atomicfile.go @@ -0,0 +1,43 @@ +// Package atomicfile replaces small files so that a reader, a concurrent +// writer or a crash never leaves a partly written file behind. +package atomicfile + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" +) + +// Write replaces path with data. The directory must exist. On failure the +// previous file stays as it was and no temporary file is left. +func Write(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 err == nil { + err = f.Chmod(perm) + } + if err == nil { + err = f.Sync() + } + err = errors.Join(err, f.Close()) + if err == nil { + err = os.Rename(f.Name(), path) + } + if err != nil { + return errors.Join(err, os.Remove(f.Name())) + } + return nil +} + +// WriteJSON replaces path with v as indented JSON. +func WriteJSON(path string, v any, perm os.FileMode) error { + data, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + return Write(path, append(data, '\n'), perm) +} diff --git a/internal/atomicfile/atomicfile_test.go b/internal/atomicfile/atomicfile_test.go new file mode 100644 index 0000000..12dbdaf --- /dev/null +++ b/internal/atomicfile/atomicfile_test.go @@ -0,0 +1,92 @@ +package atomicfile + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +func entries(t *testing.T, dir string) []string { + t.Helper() + list, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var names []string + for _, e := range list { + names = append(names, e.Name()) + } + return names +} + +func TestWriteReplacesAndLeavesNoTemporaryFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state.json") + for _, want := range []string{"first, longer content", "second"} { + if err := Write(path, []byte(want), 0o600); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(path); err != nil || string(got) != want { + t.Fatalf("content = %q, %v; want %q", got, err, want) + } + } + if got := entries(t, dir); len(got) != 1 { + t.Fatalf("directory holds %v", got) + } +} + +func TestWriteFailureKeepsTargetAndCleansUp(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "taken") + if err := os.MkdirAll(filepath.Join(target, "child"), 0o755); err != nil { + t.Fatal(err) + } + if err := Write(target, []byte("x"), 0o600); err == nil { + t.Fatal("replacing a directory succeeded") + } + if got := entries(t, dir); len(got) != 1 { + t.Fatalf("directory holds %v", got) + } + if err := Write(filepath.Join(dir, "missing", "f"), nil, 0o600); err == nil { + t.Fatal("writing into a missing directory succeeded") + } +} + +func TestConcurrentWritersNeverMixContent(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state") + var wg sync.WaitGroup + for i := range 8 { + wg.Go(func() { + // Windows may refuse a rename that races with another one; the file + // must still hold one writer's whole content. + if err := Write(path, []byte(strings.Repeat(fmt.Sprint(i), 4096)), 0o600); err != nil { + t.Logf("writer %d: %v", i, err) + } + }) + } + wg.Wait() + got, err := os.ReadFile(path) + if err != nil || len(got) != 4096 || strings.Trim(string(got), string(got[0])) != "" { + t.Fatalf("mixed content of %d bytes, %v", len(got), err) + } + if left := entries(t, dir); len(left) != 1 { + t.Fatalf("directory holds %v", left) + } +} + +func TestWriteJSONIndentsAndEndsWithNewline(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.json") + if err := WriteJSON(path, map[string]int{"a": 1}, 0o644); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "{\n \"a\": 1\n}\n" { + t.Fatalf("content = %q", got) + } + if err := WriteJSON(path, func() {}, 0o644); err == nil { + t.Fatal("encoded a function") + } +} diff --git a/internal/cli/start.go b/internal/cli/start.go index 8297ada..50c2334 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -10,6 +10,7 @@ import ( "path/filepath" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/i18n" @@ -199,9 +200,5 @@ func WriteStartResult(path string, startErr error) error { if err != nil { return err } - part := path + ".part" - if err := os.WriteFile(part, b, 0o644); err != nil { - return err - } - return os.Rename(part, path) + return atomicfile.Write(path, b, 0o644) } diff --git a/internal/config/config.go b/internal/config/config.go index 5625c4c..bc1c05f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -8,6 +8,7 @@ import ( "runtime" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -256,26 +257,16 @@ func Save(path string, cfg *Config) error { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - // Temp file + rename: a crash mid-write leaves the old file, not a - // truncated one. - tmp := path + ".tmp" - if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(path, cfg, 0o644) } func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") } func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") } func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") } func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") } -func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") } -func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") } -func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") } +func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") } +func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") } +func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") } func (c *Config) EnsureDirs() error { for _, d := range []string{ diff --git a/internal/datamigrate/datamigrate.go b/internal/datamigrate/datamigrate.go index 2e70f52..956633e 100644 --- a/internal/datamigrate/datamigrate.go +++ b/internal/datamigrate/datamigrate.go @@ -11,6 +11,8 @@ import ( "os" "path/filepath" "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) // StampFile sits at the root of the data folder. @@ -141,14 +143,5 @@ func stampExists(dataRoot string) bool { } func writeStamp(dataRoot string, s Stamp) error { - raw, err := json.MarshalIndent(s, "", " ") - if err != nil { - return err - } - path := filepath.Join(dataRoot, StampFile) - tmp := path + ".tmp" - if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil { - return err - } - return os.Rename(tmp, path) + return atomicfile.WriteJSON(filepath.Join(dataRoot, StampFile), s, 0o644) } diff --git a/internal/downloader/parallel.go b/internal/downloader/parallel.go index fe01ec3..f62b7f2 100644 --- a/internal/downloader/parallel.go +++ b/internal/downloader/parallel.go @@ -19,6 +19,7 @@ import ( "sync/atomic" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/netproxy" ) @@ -167,10 +168,7 @@ func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done if err != nil { return } - tmp := statePath(destPath) + ".tmp" - if os.WriteFile(tmp, raw, 0o644) == nil { - _ = os.Rename(tmp, statePath(destPath)) - } + _ = atomicfile.Write(statePath(destPath), raw, 0o644) } // Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index a56974c..5a00e18 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -25,6 +25,7 @@ import ( "unicode" "unicode/utf8" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "golang.org/x/net/webdav" @@ -218,20 +219,7 @@ func SaveVMConfig(vmDir string, cfg VMConfig) error { if _, err := os.Stat(vmDir); err != nil { return err } - b, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - f, err := os.CreateTemp(vmDir, ConfigFileName+"-*") - if err != nil { - return err - } - defer os.Remove(f.Name()) - _, writeErr := f.Write(b) - if err := errors.Join(writeErr, f.Close()); err != nil { - return err - } - return os.Rename(f.Name(), filepath.Join(vmDir, ConfigFileName)) + return atomicfile.WriteJSON(filepath.Join(vmDir, ConfigFileName), cfg, 0o600) } type pendingTextInput struct { diff --git a/internal/host/hypervisor.go b/internal/host/hypervisor.go index 61b0c73..2fe2f1d 100644 --- a/internal/host/hypervisor.go +++ b/internal/host/hypervisor.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "sync" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -126,29 +128,6 @@ func pendingBootFilePath(dataRoot string) string { return filepath.Join(dataRoot, "tmp", pendingBootFileName) } -func writePendingFileAtomic(path string, data []byte) error { - dir := filepath.Dir(path) - f, err := os.CreateTemp(dir, ".hypervisor-pending-*") - if err != nil { - return err - } - tmpName := f.Name() - if _, err := f.Write(data); err != nil { - _ = f.Close() - _ = os.Remove(tmpName) - return err - } - if err := f.Close(); err != nil { - _ = os.Remove(tmpName) - return err - } - if err := os.Rename(tmpName, path); err != nil { - _ = os.Remove(tmpName) - return err - } - return nil -} - // RecordPendingHypervisorBoot records (or clears) the pending hypervisor boot // mode for the current OS boot session. If /tmp already exists, it is // also persisted atomically there so reopening Reims-Go before restarting @@ -186,7 +165,7 @@ func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, en tmpDir := filepath.Dir(p) if st, err := os.Stat(tmpDir); err == nil && st.IsDir() { if raw, merr := json.Marshal(rec); merr == nil { - if writePendingFileAtomic(p, append(raw, '\n')) == nil { + if atomicfile.Write(p, append(raw, '\n'), 0o600) == nil { if pendingBootPath != "" && pendingBootPath != p { _ = os.Remove(pendingBootPath) } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index e54dfa5..afa1ace 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -9,6 +9,8 @@ import ( "sort" "strconv" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ArgLedgerFileName = ".reims-go-arg-ledger.json" @@ -195,35 +197,7 @@ func SaveArgLedger(vmDir string, ledger *ArgLedger) error { return err } ledger.Version = 1 - raw, err := json.MarshalIndent(ledger, "", " ") - if err != nil { - return err - } - target := filepath.Join(vmDir, ArgLedgerFileName) - f, err := os.CreateTemp(vmDir, ArgLedgerFileName+".*.tmp") - if err != nil { - return err - } - tmp := f.Name() - if _, err := f.Write(append(raw, '\n')); err != nil { - _ = f.Close() - _ = os.Remove(tmp) - return err - } - if err := f.Sync(); err != nil { - _ = f.Close() - _ = os.Remove(tmp) - return err - } - if err := f.Close(); err != nil { - _ = os.Remove(tmp) - return err - } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) - return err - } - return nil + return atomicfile.WriteJSON(filepath.Join(vmDir, ArgLedgerFileName), ledger, 0o600) } // ReconcileResult holds the merged extra-args, env vars, warnings, and post-start actions. diff --git a/internal/plugin/market.go b/internal/plugin/market.go index cc95dc1..436bf96 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -17,6 +17,7 @@ import ( "sync" "time" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/netproxy" ) @@ -699,33 +700,10 @@ func (c *MarketClient) writeDiskCache(idx MarketIndex) error { c.diskCacheMu.Lock() defer c.diskCacheMu.Unlock() cachePath := c.layout.IndexCachePath() - dir := filepath.Dir(cachePath) - if err := os.MkdirAll(dir, 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil { return err } - raw, err := json.MarshalIndent(idx, "", " ") - if err != nil { - return err - } - tmpFile, err := os.CreateTemp(dir, "index-cache-*.tmp") - if err != nil { - return err - } - tmpPath := tmpFile.Name() - if _, err := tmpFile.Write(raw); err != nil { - _ = tmpFile.Close() - _ = os.Remove(tmpPath) - return err - } - if err := tmpFile.Close(); err != nil { - _ = os.Remove(tmpPath) - return err - } - if err := os.Rename(tmpPath, cachePath); err != nil { - _ = os.Remove(tmpPath) - return err - } - return nil + return atomicfile.WriteJSON(cachePath, idx, 0o600) } func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry { diff --git a/internal/plugin/state.go b/internal/plugin/state.go index f3de906..91b3b59 100644 --- a/internal/plugin/state.go +++ b/internal/plugin/state.go @@ -9,6 +9,8 @@ import ( "strings" "sync" "time" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -116,29 +118,17 @@ func (s *StateStore) Save(st *StateFile) error { if err := os.MkdirAll(s.dir, 0o755); err != nil { return err } - raw, err := json.MarshalIndent(st, "", " ") - if err != nil { - return err - } - raw = append(raw, '\n') target := s.Path() - tmp := target + ".tmp" - if err := os.WriteFile(tmp, raw, 0o644); err != nil { - return err - } - // Preserve previous valid file as .bak before atomic swap. A failed backup + // Preserve the previous valid file as .bak before the swap. A failed backup // aborts the migration/save instead of silently destroying the only fallback. if prev, err := os.ReadFile(target); err == nil { if err := os.WriteFile(target+".bak", prev, 0o644); err != nil { - _ = os.Remove(tmp) return fmt.Errorf("backup plugin state: %w", err) } } else if !errors.Is(err, os.ErrNotExist) { - _ = os.Remove(tmp) return fmt.Errorf("read plugin state before backup: %w", err) } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.WriteJSON(target, st, 0o644); err != nil { return err } s.data = st diff --git a/internal/plugin/view_storage.go b/internal/plugin/view_storage.go index 83ff4d0..b17bf7c 100644 --- a/internal/plugin/view_storage.go +++ b/internal/plugin/view_storage.go @@ -10,6 +10,8 @@ import ( "strings" "unicode" "unicode/utf8" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const ( @@ -79,16 +81,7 @@ func (m *Manager) saveViewStorage(pluginID string, st *viewStorageFile) error { if err := os.MkdirAll(dir, 0o700); err != nil { return err } - target := m.viewStoragePath(pluginID) - tmp := target + ".tmp" - if err := os.WriteFile(tmp, raw, 0o600); err != nil { - return err - } - if err := os.Rename(tmp, target); err != nil { - _ = os.Remove(tmp) - return err - } - return nil + return atomicfile.Write(m.viewStoragePath(pluginID), raw, 0o600) } // ViewStorageGet returns one value from a plugin's persistent private view store. diff --git a/internal/vmstart/affinity.go b/internal/vmstart/affinity.go index d2c52b0..720d24f 100644 --- a/internal/vmstart/affinity.go +++ b/internal/vmstart/affinity.go @@ -9,6 +9,7 @@ import ( "path/filepath" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -128,17 +129,7 @@ func SaveVMAffinity(vmDir string, cfg VMAffinityConfig, maxCPUs int) (VMAffinity } else { cfg.CPUs = nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMAffinityConfig{}, err - } - dst := filepath.Join(vmDir, affinityConfigFile) - tmp := dst + ".tmp" - if err := os.WriteFile(tmp, data, 0o600); err != nil { - return VMAffinityConfig{}, err - } - if err := os.Rename(tmp, dst); err != nil { - _ = os.Remove(tmp) + if err := atomicfile.WriteJSON(filepath.Join(vmDir, affinityConfigFile), cfg, 0o600); err != nil { return VMAffinityConfig{}, err } return cfg, nil diff --git a/internal/vmstart/display.go b/internal/vmstart/display.go index 8a1f48a..f309fbf 100644 --- a/internal/vmstart/display.go +++ b/internal/vmstart/display.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" + "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/host" ) @@ -50,20 +51,7 @@ func SaveVMDisplay(vmDir string, cfg VMDisplayConfig) (VMDisplayConfig, error) { return cfg, nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMDisplayConfig{}, err - } - tmp, err := os.CreateTemp(vmDir, vmDisplayConfigFile+".*") - if err != nil { - return VMDisplayConfig{}, err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return VMDisplayConfig{}, err - } - if err := os.Rename(tmp.Name(), dst); err != nil { + if err := atomicfile.WriteJSON(dst, cfg, 0o600); err != nil { return VMDisplayConfig{}, err } return cfg, nil diff --git a/internal/vmstart/keymap.go b/internal/vmstart/keymap.go index a74fd2a..af3952d 100644 --- a/internal/vmstart/keymap.go +++ b/internal/vmstart/keymap.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) type KeymapPreset string @@ -155,20 +157,7 @@ func SaveVMKeymap(vmDir string, cfg VMKeymapConfig) (VMKeymapConfig, error) { } else { cfg.Bindings = nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return VMKeymapConfig{}, err - } - tmp, err := os.CreateTemp(vmDir, keymapConfigFile+".*") - if err != nil { - return VMKeymapConfig{}, err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return VMKeymapConfig{}, err - } - if err := os.Rename(tmp.Name(), dst); err != nil { + if err := atomicfile.WriteJSON(dst, cfg, 0o600); err != nil { return VMKeymapConfig{}, err } return cfg, nil diff --git a/internal/vmstart/nestedvirt.go b/internal/vmstart/nestedvirt.go index f00c381..1775ca0 100644 --- a/internal/vmstart/nestedvirt.go +++ b/internal/vmstart/nestedvirt.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/atomicfile" ) const vmNestedVirtConfigFile = ".reims-go-nested-virt.json" @@ -52,18 +54,5 @@ func SaveVMNestedVirt(vmDir string, cfg VMNestedVirtConfig) error { return nil } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - tmp, err := os.CreateTemp(vmDir, vmNestedVirtConfigFile+".*") - if err != nil { - return err - } - defer os.Remove(tmp.Name()) - _, writeErr := tmp.Write(data) - if err := errors.Join(writeErr, tmp.Close()); err != nil { - return err - } - return os.Rename(tmp.Name(), dst) + return atomicfile.WriteJSON(dst, cfg, 0o600) }