Mining/pkg/mining/atomic_write_file.go
Virgil 7c214f0c8b
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
AX: make mining helpers more descriptive
2026-04-04 05:21:43 +00:00

49 lines
1 KiB
Go

package mining
import (
"os"
"path/filepath"
)
// AtomicWriteFile("/home/alice/.config/lethean-desktop/miners.json", data, 0600)
func AtomicWriteFile(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmpFile, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return ErrInternal("create temp file").WithCause(err)
}
tmpPath := tmpFile.Name()
success := false
defer func() {
if !success {
os.Remove(tmpPath)
}
}()
if _, err := tmpFile.Write(data); err != nil {
tmpFile.Close()
return ErrInternal("write temp file").WithCause(err)
}
if err := tmpFile.Sync(); err != nil {
tmpFile.Close()
return ErrInternal("sync temp file").WithCause(err)
}
if err := tmpFile.Close(); err != nil {
return ErrInternal("close temp file").WithCause(err)
}
if err := os.Chmod(tmpPath, perm); err != nil {
return ErrInternal("set file permissions").WithCause(err)
}
if err := os.Rename(tmpPath, path); err != nil {
return ErrInternal("rename temp file").WithCause(err)
}
success = true
return nil
}