-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistory.go
More file actions
100 lines (88 loc) · 1.68 KB
/
history.go
File metadata and controls
100 lines (88 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"time"
)
type Need int
const (
Hunger Need = iota
Comfort
Bladder
Energy
Fun
Social
Hygiene
Environment
NeedCount
)
var needNames = [NeedCount]string{
"Hunger",
"Comfort",
"Bladder",
"Energy",
"Fun",
"Social",
"Hygiene",
"Environment",
}
func NeedName(n Need) string {
if n < 0 || n >= NeedCount {
return "Unknown"
}
return needNames[n]
}
func NeedNames() [NeedCount]string {
return needNames
}
type Entry struct {
Timestamp time.Time `json:"timestamp"`
Values [NeedCount]int `json:"values"`
}
type History struct {
Entries []Entry `json:"entries"`
}
func DefaultPath() (string, error) {
dataDir := os.Getenv("XDG_DATA_HOME")
if dataDir == "" {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
dataDir = filepath.Join(home, ".local", "share")
}
dir := filepath.Join(dataDir, "sbars")
if err := os.MkdirAll(dir, 0755); err != nil {
return "", err
}
return filepath.Join(dir, "history.json"), nil
}
func Load(path string) (History, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return History{}, nil
}
return History{}, err
}
var h History
if err := json.Unmarshal(data, &h); err != nil {
return History{}, err
}
return h, nil
}
func Save(path string, h History) error {
data, err := json.MarshalIndent(h, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}
func AppendEntry(h History, e Entry) History {
newEntries := make([]Entry, len(h.Entries), len(h.Entries)+1)
copy(newEntries, h.Entries)
newEntries = append(newEntries, e)
return History{Entries: newEntries}
}