refactor: write small files through one atomic writer

Fifteen call sites each had their own temp-file-and-rename code. Some
used a fixed temporary name, so two writers could mix their content, and
most did not flush before the rename. They now share atomicfile.Write.

An architecture test keeps new os.Rename calls out of other packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
千川白浪andClaude Opus 5.5 committed 2026-12-03 20:59:56 -07:00
1 parent c639682a88
commit 90fbce8b47
20 files changed
+241 -250

No files matched your search

+2 -6
View File
@@ -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
+4 -38
View File
@@ -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)) }
+2 -4
View File
@@ -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),
+58
View File
@@ -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)
}
}
}
+43
View File
@@ -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)
}
+92
View File
@@ -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")
}
}
+2 -5
View File
@@ -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)
}
+5 -14
View File
@@ -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{
+3 -10
View File
@@ -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)
}
+2 -4
View File
@@ -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
+2 -14
View File
@@ -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 {
+3 -24
View File
@@ -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 <dataRoot>/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)
}
+3 -29
View File
@@ -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.
+3 -25
View File
@@ -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 {
+4 -14
View File
@@ -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
+3 -10
View File
@@ -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.
+2 -11
View File
@@ -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
+2 -14
View File
@@ -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
+3 -14
View File
@@ -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
+3 -14
View File
@@ -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)
}