-
Notifications
You must be signed in to change notification settings - Fork 26
/
config.go
51 lines (45 loc) · 987 Bytes
/
config.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
package main
import (
"encoding/json"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
)
type JSONData struct {
Highlight bool `json:"highlight"`
Linewrap int `json:"linewrap"`
Editor string `json:"editor"`
Cheatdirs []string `json:"cheatdirs"`
}
var defaults = `{
"highlight": true,
"linewrap": 79,
"cheatdirs": [
"~/.cheatsheets"
],
"editor": "vim"
}`
func (q *JSONData) ReadConfig() error {
usr, _ := user.Current()
rcfile := filepath.Join(usr.HomeDir, ".cheatrc")
settings := []byte(defaults)
if _, err := os.Stat(rcfile); os.IsNotExist(err) {
ioutil.WriteFile(rcfile, []byte(defaults), 0777)
} else {
settings, _ = ioutil.ReadFile(rcfile)
}
//Umarshalling JSON into struct
var data = &q
err := json.Unmarshal(settings, data)
if err != nil {
return err
}
for i, dir := range q.Cheatdirs {
if strings.HasPrefix(dir, "~/") {
q.Cheatdirs[i] = filepath.Join(usr.HomeDir, dir[2:])
}
}
return nil
}