-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconfig.go
60 lines (48 loc) · 1.25 KB
/
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
52
53
54
55
56
57
58
59
60
// Package config provides super simple JSON configuration for command-line programs.
package config
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
// Load configuration from path, into the struct pointer provided. No error is returned
// if the file does not exist.
func Load(path string, v interface{}) error {
b, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(b, v)
}
// Save saves configuration to path. If the directory does not exist, it is created.
func Save(path string, v interface{}) error {
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return err
}
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(path, b, 0600)
}
// LoadHome loads configuration from path relative to the user home directory.
func LoadHome(path string, v interface{}) error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
return Load(filepath.Join(home, path), v)
}
// SaveHome saves configuration to path relative to the user home directory.
func SaveHome(path string, v interface{}) error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
return Save(filepath.Join(home, path), v)
}