feat(platform): add WriteUserFile atomic user-space writer
This commit is contained in:
25
internal/platform/writefile.go
Normal file
25
internal/platform/writefile.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// WriteUserFile writes data to path atomically (tmp + rename) with the
|
||||
// given mode, creating any missing parent directories (mode 0755).
|
||||
// Intended for user-owned destinations under $HOME — no sudo.
|
||||
func WriteUserFile(path string, data []byte, mode os.FileMode) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, mode); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user