feat(tool): add WriteFileAtomic helper

This commit is contained in:
sausheong committed 2026-06-13 00:49:50 +08:00
1 parent 7fa3e75ad1
commit c4750347e6
2 files changed
+73

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"fmt"
"os"
"path/filepath"
)
// WriteFileAtomic writes data to path atomically: it writes to a temp file in
// the same directory, fsyncs, sets perm, then renames over path. A crash
// mid-write leaves either the old file or the complete new file, never a
// truncated one. The rename is atomic on POSIX within a single filesystem.
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp: %w", err)
}
if err := os.Chmod(tmpName, perm); err != nil {
return fmt.Errorf("chmod temp: %w", err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename temp: %w", err)
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package tool
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteFileAtomic(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "out.txt")
require.NoError(t, WriteFileAtomic(path, []byte("hello"), 0o600))
data, err := os.ReadFile(path)
require.NoError(t, err)
require.Equal(t, "hello", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
require.NoError(t, WriteFileAtomic(path, []byte("world"), 0o644))
data, _ = os.ReadFile(path)
require.Equal(t, "world", string(data))
entries, err := os.ReadDir(dir)
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, "out.txt", entries[0].Name())
}