-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserConfig.go
130 lines (104 loc) · 2.39 KB
/
userConfig.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package clicommon
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"runtime"
)
type UserConfigDir struct {
name string
}
func NewUserConfigDir(name string) *UserConfigDir {
return &UserConfigDir{
name: name,
}
}
// GetConfigDir gets the os-dependent user configuration directory
func (userConfigDir *UserConfigDir) GetConfigDir() (string, error) {
var dir string
switch runtime.GOOS {
case "linux", "darwin":
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
dir = fmt.Sprintf("%s/.config/%s/", home, userConfigDir.name)
case "windows":
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
dir = fmt.Sprintf("%s\\AppData\\Roaming\\%s\\", home, userConfigDir.name)
}
info, err := os.Stat(dir)
if err != nil {
err = os.MkdirAll(dir, 0770)
if err != nil {
return "", err
}
} else if !info.IsDir() {
return "", errors.New("config path is not a directory")
}
return dir, nil
}
// LoadConfig loads a user config file of the given name
func (userConfigDir *UserConfigDir) LoadConfig(config string, data interface{}) error {
dir, err := userConfigDir.GetConfigDir()
if err != nil {
return err
}
filename := dir + config + ".json"
text, err := ioutil.ReadFile(filename)
if err != nil {
text = []byte("{}")
}
err = json.Unmarshal(text, data)
if err != nil {
return err
}
return nil
}
// SaveConfig saves a user config file of the given name
func (userConfigDir *UserConfigDir) SaveConfig(config string, data interface{}) error {
dir, err := userConfigDir.GetConfigDir()
if err != nil {
return err
}
filename := dir + config + ".json"
text, err := json.Marshal(data)
if err != nil {
return err
}
err = ioutil.WriteFile(filename, text, 0660)
if err != nil {
return err
}
return nil
}
// LoadExternalConfig reads an external config file, outside of the default user
// config directory
func LoadExternalConfig(filename string, data interface{}) error {
text, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = json.Unmarshal(text, data)
if err != nil {
return err
}
return nil
}
// SaveExternalConfig saves a file outside of the default user config directory
func SaveExternalConfig(filename string, data interface{}) error {
text, err := json.Marshal(data)
if err != nil {
return err
}
err = ioutil.WriteFile(filename, text, 0666)
if err != nil {
return err
}
return nil
}