47 lines
906 B
Go
47 lines
906 B
Go
package update
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
)
|
|
|
|
const readableFilePermissions = 0o644
|
|
|
|
func writeFileAtomically(path string, content []byte, permissions os.FileMode) error {
|
|
temporary := path + ".tmp"
|
|
if err := os.WriteFile(temporary, content, permissions); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Rename(temporary, path); err != nil {
|
|
_ = os.Remove(temporary)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func writeJSONAtomically(path string, value any, permissions os.FileMode) error {
|
|
content, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return writeFileAtomically(path, content, permissions)
|
|
}
|
|
|
|
func removeFile(path string) (bool, error) {
|
|
err := os.Remove(path)
|
|
if err == nil {
|
|
return true, nil
|
|
}
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
|
|
func removeIfPresent(path string) error {
|
|
_, err := removeFile(path)
|
|
return err
|
|
}
|