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>
44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
// 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)
|
|
}
|