this repo has no description
1package state
2
3import (
4 "encoding/json"
5 "os"
6 "time"
7)
8
9// State holds metadata for the cache, including
10// the last update timestamp and a map of file hashes.
11type State struct {
12 LastUpdated int64
13 Data map[string]string
14}
15
16var defaultPath = ".nox-state.json"
17
18// SetPath updates the default file path used for saving and loading state
19func SetPath(path string) {
20 defaultPath = path
21}
22
23// Touch updates the LastUpdated timestamp to the current time.
24func (s *State) Touch() {
25 s.LastUpdated = time.Now().Unix()
26}
27
28// Load reads the state from the state file
29func Load() (*State, error) {
30 return loadFromFile(defaultPath)
31}
32
33// Save writes the given State to the state file.
34// Overwrites any existing state file.
35func Save(state *State) error {
36 return saveToFile(defaultPath, state)
37}
38
39// loadFromFile reads the state JSON from the specified file path.
40func loadFromFile(path string) (*State, error) {
41 data, err := os.ReadFile(path)
42 if err != nil {
43 return &State{Data: make(map[string]string)}, nil
44 }
45 var state State
46 if err := json.Unmarshal(data, &state); err != nil {
47 return nil, err
48 }
49
50 return &state, nil
51}
52
53// saveToFile writes the State as JSON to the specified file path.
54func saveToFile(path string, state *State) error {
55 data, err := json.Marshal(state)
56 if err != nil {
57 return err
58 }
59
60 return os.WriteFile(path, data, 0644)
61}