-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhistory.go
102 lines (92 loc) · 1.9 KB
/
history.go
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
101
102
package main
import (
"encoding/json"
"os"
"path"
)
type GrueHistory struct {
path string
Feeds map[string]*RSSFeed
}
func (hist *GrueHistory) String() string {
b, err := json.Marshal(hist)
if err != nil {
panic("Cant Marshal GrueHistory")
}
return string(b)
}
func (hist *GrueHistory) Write() error {
file, err := os.Create(hist.path)
if err != nil {
return err
}
defer file.Close()
enc := json.NewEncoder(file)
enc.SetIndent("", " ")
return enc.Encode(hist)
}
func makeDefHistory() (*GrueHistory, error) {
var feeds = make(map[string]*RSSFeed)
var hist = &GrueHistory{Feeds: feeds}
return hist, nil
}
func writeDefHistory(path string) (*GrueHistory, error) {
hist, err := makeDefHistory()
if err != nil {
return nil, err
}
hist.path = path
return hist, hist.Write()
}
func getHistoryPath() string {
dataPath := os.Getenv("XDG_DATA_HOME")
if dataPath == "" {
home := os.Getenv("HOME")
if home == "" {
panic("Can't find path to data directory")
}
return path.Join(os.Getenv("HOME"), ".local/share", "grue.json")
}
return path.Join(dataPath, "grue.json")
}
func ReadHistory() (*GrueHistory, error) {
var hist *GrueHistory = new(GrueHistory)
var path = getHistoryPath()
file, err := os.Open(path)
if os.IsNotExist(err) {
return writeDefHistory(path)
} else if err != nil {
return nil, err
}
defer file.Close()
dec := json.NewDecoder(file)
err = dec.Decode(hist)
if err != nil {
return nil, err
}
hist.path = path
return hist, nil
}
func DeleteHistory(name string) error {
hist, err := ReadHistory()
if err != nil {
return err
}
if _, ok := hist.Feeds[name]; !ok {
return nil
}
delete(hist.Feeds, name)
return hist.Write()
}
func RenameHistory(old, new string) error {
hist, err := ReadHistory()
if err != nil {
return err
}
if _, ok := hist.Feeds[old]; !ok {
return nil
}
hist.Feeds[new] = hist.Feeds[old]
delete(hist.Feeds, old)
return hist.Write()
}