feat(tool): add WriteFileAtomic helper
This commit is contained in:
1 parent
7fa3e75ad1
commit
c4750347e6
2 files changed
+73
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user