package core import ( "os" "path/filepath" ) // AtomicWriteFile writes data to a file atomically by first writing to a // temporary file in the same directory, syncing, then renaming over the target. // This prevents data loss / corruption on crash. func AtomicWriteFile(path string, data []byte, perm os.FileMode) error { dir := filepath.Dir(path) tmp, err := os.CreateTemp(dir, ".tmp-*") if err != nil { return err } tmpPath := tmp.Name() if _, err := tmp.Write(data); err != nil { tmp.Close() os.Remove(tmpPath) return err } if err := tmp.Sync(); err != nil { tmp.Close() os.Remove(tmpPath) return err } if err := tmp.Close(); err != nil { os.Remove(tmpPath) return err } if err := os.Chmod(tmpPath, perm); err != nil { os.Remove(tmpPath) return err } return os.Rename(tmpPath, path) }