57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package safeio
|
|
|
|
import (
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
// AtomicWriteFile writes data to path atomically by writing to a temp file in
|
|
// the same directory and renaming it into place. On any error before rename,
|
|
// the temp file is removed. The parent directory is created if needed.
|
|
func AtomicWriteFile(path string, data []byte, perm fs.FileMode) error {
|
|
dir := filepath.Dir(path)
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return fmt.Errorf("create parent directory: %w", err)
|
|
}
|
|
|
|
tmp, err := os.CreateTemp(dir, ".atomic-*")
|
|
if err != nil {
|
|
return fmt.Errorf("create temp file: %w", err)
|
|
}
|
|
tmpPath := tmp.Name()
|
|
cleanup := true
|
|
defer func() {
|
|
if cleanup {
|
|
os.Remove(tmpPath)
|
|
}
|
|
}()
|
|
|
|
if _, err := tmp.Write(data); err != nil {
|
|
tmp.Close()
|
|
return fmt.Errorf("write temp file: %w", err)
|
|
}
|
|
if err := tmp.Sync(); err != nil {
|
|
tmp.Close()
|
|
return fmt.Errorf("sync temp file: %w", err)
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
return fmt.Errorf("close temp file: %w", err)
|
|
}
|
|
if err := os.Chmod(tmpPath, perm); err != nil {
|
|
return fmt.Errorf("chmod temp file: %w", err)
|
|
}
|
|
if err := os.Rename(tmpPath, path); err != nil {
|
|
return fmt.Errorf("rename temp file: %w", err)
|
|
}
|
|
cleanup = false
|
|
|
|
// Best-effort sync of the parent directory.
|
|
if f, err := os.Open(dir); err == nil {
|
|
_ = f.Sync()
|
|
f.Close()
|
|
}
|
|
return nil
|
|
}
|