41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
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
|
|
}
|