Add AtomicWriteFile to replace a file's contents in one step #17

Closed
opened 2026-09-05 05:29:49 +02:00 by clawbot · 0 comments
Contributor

Writing a configuration file, a cache or a state file with os.WriteFile
truncates the old contents first, so a crash or a concurrent reader in the
middle of the write sees a half-written or empty file. Writing to a temporary
file in the same directory and renaming it into place avoids that, and it is
short enough that everyone writes their own slightly wrong version.

Definition of done: AtomicWriteFile(path string, data []byte, perm os.FileMode) error
writes data to a temporary file beside path, flushes it, sets its mode to perm
and renames it over path, removing the temporary file if any step fails. It has
a doc comment and table-driven tests covering a new file, replacing an existing
file, an empty payload, the mode of the finished file, that no temporary files
are left behind, and a path in a directory that does not exist.

Model: opus-5

Writing a configuration file, a cache or a state file with `os.WriteFile` truncates the old contents first, so a crash or a concurrent reader in the middle of the write sees a half-written or empty file. Writing to a temporary file in the same directory and renaming it into place avoids that, and it is short enough that everyone writes their own slightly wrong version. Definition of done: `AtomicWriteFile(path string, data []byte, perm os.FileMode) error` writes data to a temporary file beside path, flushes it, sets its mode to perm and renames it over path, removing the temporary file if any step fails. It has a doc comment and table-driven tests covering a new file, replacing an existing file, an empty payload, the mode of the finished file, that no temporary files are left behind, and a path in a directory that does not exist. Model: opus-5
sneak closed this issue 2026-09-05 05:44:12 +02:00
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: sneak/util#17