-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
73 lines (65 loc) · 1.33 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
package godid
import (
"os"
"path"
"github.com/go-yaml/yaml"
homedir "github.com/mitchellh/go-homedir"
)
const (
workDir = "~/.godid/"
configPath = workDir + "config.yml"
)
type config struct {
StorePath string `yaml:"store_path"`
}
func (c *config) GetStorePath() (string, error) {
return homedir.Expand(c.StorePath)
}
var (
defaultConfig = config{
StorePath: workDir + "store.db",
}
)
func getConfig() (*config, error) {
path, err := homedir.Expand(configPath)
if err != nil {
return nil, err
}
_, err = os.Stat(path)
if os.IsNotExist(err) {
return initDefaultConfig()
}
cfgBytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg config
err = yaml.Unmarshal(cfgBytes, &cfg)
if err != nil {
return nil, err
}
return &cfg, nil
}
func initDefaultConfig() (*config, error) {
if os.Getenv("GODID_TEST") == "" {
cfgPath, err := homedir.Expand(configPath)
if err != nil {
return nil, err
}
pathDir := path.Dir(cfgPath)
_, err = os.Stat(pathDir)
if os.IsNotExist(err) {
if err := os.MkdirAll(pathDir, os.ModePerm); err != nil { // nolint: vetshadow
return nil, err
}
}
cfgBytes, err := yaml.Marshal(defaultConfig)
if err != nil {
return nil, err
}
if err := os.WriteFile(cfgPath, cfgBytes, 0600); err != nil {
return nil, err
}
}
return &defaultConfig, nil
}