forked from muja/goconfig
-
Notifications
You must be signed in to change notification settings - Fork 1
/
load.go
139 lines (116 loc) · 2.44 KB
/
load.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
131
132
133
134
135
136
137
138
139
package goconfig
import (
"io/ioutil"
"os"
)
// loadConfigFile loads specific git config file
func loadConfigFile(name string) (GitConfig, error) {
if cfg, ok := CacheGet(name); ok {
return cfg, nil
}
// cache will be updated using this time
fi, _ := os.Stat(name)
buf, err := ioutil.ReadFile(name)
if err != nil {
return nil, err
}
cfg, _, err := Parse(buf, name)
if err != nil {
return cfg, err
}
// update cache
CacheSet(name, cfg, fi.Size(), fi.ModTime())
return cfg, nil
}
// Load only loads one file or config of current repository
func Load(name string) (GitConfig, error) {
var (
err error
fi os.FileInfo
search bool
)
if name == "" {
search = true
name, err = os.Getwd()
if err != nil {
return nil, err
}
} else {
fi, err = os.Stat(name)
if err != nil {
return nil, ErrNotExist
}
if fi.IsDir() {
search = true
}
}
if search {
name, err = FindGitConfig(name)
if err != nil {
if err == ErrNotInGitDir {
return nil, nil
}
return nil, err
}
}
return loadConfigFile(name)
}
// LoadAll will load additional global and system config files
func LoadAll(name string) (GitConfig, error) {
cfg := NewGitConfig()
sysConfig, err := SystemConfig()
if err != nil {
return nil, err
}
globalConfig, err := GlobalConfig()
if err != nil {
return nil, err
}
repoConfig, err := Load(name)
if err != nil {
return nil, err
}
if sysConfig != nil {
cfg.Merge(sysConfig, ScopeSystem)
}
if globalConfig != nil {
cfg.Merge(globalConfig, ScopeGlobal)
}
if repoConfig != nil {
cfg.Merge(repoConfig, ScopeSelf)
}
return cfg, nil
}
// SystemConfig returns system git config, reload if necessary
func SystemConfig() (GitConfig, error) {
file := SystemConfigFile()
if file == "" {
return nil, nil
}
if _, err := os.Stat(file); err != nil {
return nil, nil
}
return Load(file)
}
// GlobalConfig returns global user config, reload if necessary
func GlobalConfig() (GitConfig, error) {
file, err := GlobalConfigFile()
if err != nil {
return nil, err
}
if _, err := os.Stat(file); err != nil {
return nil, nil
}
return Load(file)
}
// DefaultConfig returns global and system wide config
func DefaultConfig() GitConfig {
cfg := NewGitConfig()
if sysCfg, err := SystemConfig(); err == nil && sysCfg != nil {
cfg.Merge(sysCfg, ScopeSystem)
}
if globalCfg, err := GlobalConfig(); err == nil && globalCfg != nil {
cfg.Merge(globalCfg, ScopeGlobal)
}
return cfg
}