/
config.go
90 lines (76 loc) · 1.66 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
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
package config
import (
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
conf "xinhari.com/xinhari/config"
"xinhari.com/xinhari/config/source/file"
"xinhari.com/xinhari/util/log"
)
// FileName for global micro config
const FileName = ".micro"
// config is a singleton which is required to ensure
// each function call doesn't load the .micro file
// from disk
var config = newConfig()
// Get a value from the .micro file
func Get(path ...string) (string, error) {
tk := config.Get(path...).String("")
return strings.TrimSpace(tk), nil
}
// Set a value in the .micro file
func Set(value string, path ...string) error {
// get the filepath
fp, err := filePath()
if err != nil {
return err
}
// set the value
config.Set(value, path...)
// write to the file
return ioutil.WriteFile(fp, config.Bytes(), 0644)
}
func filePath() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
return filepath.Join(usr.HomeDir, FileName), nil
}
// newConfig returns a loaded config
func newConfig() conf.Config {
// get the filepath
fp, err := filePath()
if err != nil {
log.Error(err)
return conf.DefaultConfig
}
// write the file if it does not exist
if _, err := os.Stat(fp); os.IsNotExist(err) {
ioutil.WriteFile(fp, []byte{}, 0644)
} else if err != nil {
log.Error(err)
return conf.DefaultConfig
}
// create a new config
c, err := conf.NewConfig(
conf.WithSource(
file.NewSource(
file.WithPath(fp),
),
),
)
if err != nil {
log.Error(err)
return conf.DefaultConfig
}
// load the config
if err := c.Load(); err != nil {
log.Error(err)
return conf.DefaultConfig
}
// return the conf
return c
}