add AtomicWriteFile for replacing a file in one step

AtomicWriteFile writes to a temporary file in the same directory, flushes it,
sets the mode and renames it over the target, so a reader never sees a
half-written file and a failure leaves the old one untouched. Comes with a doc
comment and table-driven tests. (closes #17)

Model: opus-5
This commit is contained in:
2026-09-05 03:30:52 +00:00
parent 9302c14a6c
commit 9708301eba
2 changed files with 166 additions and 0 deletions

110
atomicwrite_test.go Normal file
View File

@@ -0,0 +1,110 @@
package util
import (
"os"
"path/filepath"
"testing"
)
func TestAtomicWriteFile(t *testing.T) {
tests := []struct {
name string
existing string
data []byte
perm os.FileMode
}{
{"a new file", "", []byte("hello"), 0644},
{"replacing a shorter file", "old", []byte("a much longer set of contents"), 0644},
{"replacing a longer file", "a much longer set of contents", []byte("new"), 0644},
{"an empty payload", "something", []byte{}, 0644},
{"a nil payload", "something", nil, 0644},
{"a private mode", "", []byte("secret"), 0600},
{"an executable mode", "", []byte("#!/bin/sh\n"), 0755},
{"binary contents", "", []byte{0x00, 0xff, 0x10, 0x00}, 0644},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
directory := t.TempDir()
path := filepath.Join(directory, "target")
if test.existing != "" {
if err := os.WriteFile(path, []byte(test.existing), 0666); err != nil {
t.Fatalf("could not write the file to be replaced: %v", err)
}
}
if err := AtomicWriteFile(path, test.data, test.perm); err != nil {
t.Fatalf("did not expect an error, got %v", err)
}
written, err := os.ReadFile(path)
if err != nil {
t.Fatalf("could not read the file back: %v", err)
}
if string(written) != string(test.data) {
t.Errorf("expected contents %q got %q", string(test.data), string(written))
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("could not look at the file: %v", err)
}
if info.Mode().Perm() != test.perm {
t.Errorf("expected mode %v got %v", test.perm, info.Mode().Perm())
}
entries, err := os.ReadDir(directory)
if err != nil {
t.Fatalf("could not list the directory: %v", err)
}
if len(entries) != 1 {
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Name())
}
t.Errorf("expected only the target file to be left, got %v", names)
}
})
}
}
func TestAtomicWriteFileReportsAMissingDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), "not-there", "target")
if err := AtomicWriteFile(path, []byte("hello"), 0644); err == nil {
t.Errorf("expected an error for a directory that does not exist")
}
}
func TestAtomicWriteFileLeavesTheOldFileAloneOnFailure(t *testing.T) {
directory := t.TempDir()
path := filepath.Join(directory, "target")
if err := os.WriteFile(path, []byte("original"), 0644); err != nil {
t.Fatalf("could not write the file to be replaced: %v", err)
}
// A directory that cannot be written to means the temporary file cannot
// be created, so the write has to fail before anything is replaced.
if err := os.Chmod(directory, 0500); err != nil {
t.Fatalf("could not change the directory mode: %v", err)
}
defer os.Chmod(directory, 0700)
if os.Geteuid() == 0 {
t.Skip("running as root, which ignores the directory mode")
}
if err := AtomicWriteFile(path, []byte("replacement"), 0644); err == nil {
t.Fatalf("expected an error for a directory that cannot be written to")
}
existing, err := os.ReadFile(path)
if err != nil {
t.Fatalf("could not read the file back: %v", err)
}
if string(existing) != "original" {
t.Errorf("expected the original contents to survive, got %q", string(existing))
}
}