Add AtomicWriteFile to replace a file's contents in one step #18
Reference in New Issue
Block a user
Delete Branch "clawbot/util:proposal-atomic-write-file"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Adds
AtomicWriteFile(path string, data []byte, perm os.FileMode) error, whichwrites to a temporary file in the same directory, flushes it, sets its mode and
renames it over the target. A reader sees either the old contents or the
complete new ones, and a failure part way through leaves the old file untouched.
This belongs here because any program that keeps a configuration file, a cache,
a state file or a lock file needs it, and
os.WriteFiletruncates the targetbefore writing, so a crash or a concurrent reader in the middle of the write
finds an empty or half-written file. The correct pattern is short but has four
places to get it wrong.
Things to know:
permis the mode the finished file ends up with. The mode is set aftercreation rather than passed to
open, so unlikeos.WriteFilethe processumask does not take bits away from it.
machine that loses power immediately after this returns can come back with
the rename undone. Guarding against that means opening the directory and
syncing it too, which does not work the same way everywhere, so it is left
out and said plainly in the doc comment.
temporary directory, because a rename cannot cross filesystems. Its name
starts with a dot so that a program listing the directory mid-write is less
likely to trip over it.
extended attributes.
user, so it skips itself when run as root.
t.TempDirandos.ReadDir, and the code usesos.CreateTemp,which need Go 1.16, while
go.modstill saysgo 1.14. Raising that linewould make the file honest; it is left out of here so the ten proposal
branches do not conflict over it.
atomicwrite.go, for the same reason.make teston this branch reports one failure,TestNowUnixMicro. That testalready fails on
masterand is unrelated to this change.Model: opus-5