package store import ( "encoding/json" "fmt" "os" "path/filepath" ) // jsonMarshal encodes a small record the store keeps for itself. The anchor is // the only one. func jsonMarshal(v any) ([]byte, error) { raw, err := json.MarshalIndent(v, "", " ") if err != nil { return nil, fmt.Errorf("store: encode record: %w", err) } return raw, nil } // jsonUnmarshal decodes a small record. func jsonUnmarshal(raw []byte, v any) error { if err := json.Unmarshal(raw, v); err != nil { return fmt.Errorf("store: decode record: %w", err) } return nil } // writeFileAtomic replaces a file with a temporary write and a rename, so a // crash leaves either the old file or the new one and never half of either. func writeFileAtomic(path string, raw []byte) error { tmp := path + ".tmp" if err := os.WriteFile(tmp, raw, 0o644); err != nil { return fmt.Errorf("store: write %s: %w", tmp, err) } if err := os.Rename(tmp, path); err != nil { return fmt.Errorf("store: replace %s: %w", path, err) } return nil } // writeFileAtomicIn is writeFileAtomic for a named file under dir. func writeFileAtomicIn(dir, name string, raw []byte) error { return writeFileAtomic(filepath.Join(dir, name), raw) }