-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
88 lines (73 loc) · 1.48 KB
/
store.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
package main
import (
"encoding/json"
"io/ioutil"
"os"
"os/user"
"path"
)
const flanFile = ".flan"
type commands map[string][][]string
func store(cmd, example, anno string, cmds commands) {
flannotations, prs := cmds[cmd]
if prs {
flannotations = append(flannotations, []string{example, anno})
} else {
flannotations = make([][]string, 1)
flannotations[0] = []string{example, anno}
}
cmds[cmd] = flannotations
}
func readFlanFile() (commands, error) {
flanPath, err := flanPath()
if err != nil {
return nil, err
}
cmds, err := readFlanFileFromPath(flanPath)
if err != nil {
return nil, err
}
return cmds, nil
}
func readFlanFileFromPath(path string) (commands, error) {
dat, err := ioutil.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return make(commands), nil
}
return nil, err
}
var cmds commands
if err := json.Unmarshal(dat, &cmds); err != nil {
return nil, err
}
return cmds, nil
}
func writeFlanFile(cmds commands) error {
flanPath, err := flanPath()
if err != nil {
return err
}
if err := writeFlanFileToPath(cmds, flanPath); err != nil {
return err
}
return nil
}
func writeFlanFileToPath(cmds commands, path string) error {
b, err := json.Marshal(cmds)
if err != nil {
return err
}
if err = ioutil.WriteFile(path, b, 0644); err != nil {
return err
}
return nil
}
func flanPath() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
p := path.Join(usr.HomeDir, flanFile)
return p, nil
}