-
Notifications
You must be signed in to change notification settings - Fork 46
/
config.go
295 lines (267 loc) · 8.12 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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Package config is a set of types for interacting with the gh configuration files.
// Note: This package is intended for use only in gh, any other use cases are subject
// to breakage and non-backwards compatible updates.
package config
import (
"errors"
"io"
"os"
"path/filepath"
"runtime"
"github.com/cli/go-gh/internal/yamlmap"
)
const (
appData = "AppData"
ghConfigDir = "GH_CONFIG_DIR"
localAppData = "LocalAppData"
xdgConfigHome = "XDG_CONFIG_HOME"
xdgDataHome = "XDG_DATA_HOME"
xdgStateHome = "XDG_STATE_HOME"
)
// Config is a in memory representation of the gh configuration files.
// It can be thought of as map where entries consist of a key that
// correspond to either a string value or a map value, allowing for
// multi-level maps.
type Config struct {
entries *yamlmap.Map
}
// Get a string value from a Config.
// The keys argument is a sequence of key values so that nested
// entries can be retrieved. A undefined string will be returned
// if trying to retrieve a key that corresponds to a map value.
// Returns "", KeyNotFoundError if any of the keys can not be found.
func Get(c *Config, keys []string) (string, error) {
m := c.entries
for _, key := range keys {
var err error
m, err = m.FindEntry(key)
if err != nil {
return "", KeyNotFoundError{key}
}
}
return m.Value, nil
}
// Keys enumerates a Configs keys.
// The keys argument is a sequence of key values so that nested
// map values can be have their keys enumerated.
// Returns nil, KeyNotFoundError if any of the keys can not be found.
func Keys(c *Config, keys []string) ([]string, error) {
m := c.entries
for _, key := range keys {
var err error
m, err = m.FindEntry(key)
if err != nil {
return nil, KeyNotFoundError{key}
}
}
return m.Keys(), nil
}
// Remove an entry from a Config.
// The keys argument is a sequence of key values so that nested
// entries can be removed. Removing an entry that has nested
// entries removes those also.
// Returns "", KeyNotFoundError if any of the keys can not be found.
func Remove(c *Config, keys []string) error {
m := c.entries
for i := 0; i < len(keys)-1; i++ {
var err error
key := keys[i]
m, err = m.FindEntry(key)
if err != nil {
return KeyNotFoundError{key}
}
}
err := m.RemoveEntry(keys[len(keys)-1])
if err != nil {
return KeyNotFoundError{keys[len(keys)-1]}
}
return nil
}
// Set an entry in a Config.
// The keys argument is a sequence of key values so that nested
// entries can be set. If any of the keys do not exist they will
// be created.
func Set(c *Config, keys []string, value string) {
m := c.entries
for i := 0; i < len(keys)-1; i++ {
key := keys[i]
entry, err := m.FindEntry(key)
if err != nil {
entry = yamlmap.MapValue()
m.AddEntry(key, entry)
}
m = entry
}
m.SetEntry(keys[len(keys)-1], yamlmap.StringValue(value))
}
// Read gh configuration files from the local file system and
// return a Config.
func Read() (*Config, error) {
// TODO: Make global config singleton using sync.Once
// so as not to read from file every time.
return load(generalConfigFile(), hostsConfigFile())
}
// ReadFromString takes a yaml string and returns a Config.
// Note: This is only used for testing, and should not be
// relied upon in production.
func ReadFromString(str string) *Config {
m, _ := mapFromString(str)
if m == nil {
m = yamlmap.MapValue()
}
return &Config{m}
}
// Write gh configuration files to the local file system.
// It will only write gh configuration files that have been modified
// since last being read.
func Write(config *Config) error {
hosts, err := config.entries.FindEntry("hosts")
if err == nil && hosts.IsModified() {
err := writeFile(hostsConfigFile(), []byte(hosts.String()))
if err != nil {
return err
}
hosts.SetUnmodified()
}
if config.entries.IsModified() {
// Hosts gets written to a different file above so remove it
// before writing and add it back in after writing.
hostsMap, hostsErr := config.entries.FindEntry("hosts")
if hostsErr == nil {
_ = config.entries.RemoveEntry("hosts")
}
err := writeFile(generalConfigFile(), []byte(config.entries.String()))
if err != nil {
return err
}
config.entries.SetUnmodified()
if hostsErr == nil {
config.entries.AddEntry("hosts", hostsMap)
}
}
return nil
}
func load(generalFilePath, hostsFilePath string) (*Config, error) {
generalMap, err := mapFromFile(generalFilePath)
if err != nil && !os.IsNotExist(err) {
if errors.Is(err, yamlmap.ErrInvalidYaml) ||
errors.Is(err, yamlmap.ErrInvalidFormat) {
return nil, InvalidConfigFileError{Path: generalFilePath, Err: err}
}
return nil, err
}
if generalMap == nil || generalMap.Empty() {
generalMap, _ = mapFromString(defaultGeneralEntries)
}
hostsMap, err := mapFromFile(hostsFilePath)
if err != nil && !os.IsNotExist(err) {
if errors.Is(err, yamlmap.ErrInvalidYaml) ||
errors.Is(err, yamlmap.ErrInvalidFormat) {
return nil, InvalidConfigFileError{Path: hostsFilePath, Err: err}
}
return nil, err
}
if hostsMap != nil && !hostsMap.Empty() {
generalMap.AddEntry("hosts", hostsMap)
}
return &Config{generalMap}, nil
}
func generalConfigFile() string {
return filepath.Join(configDir(), "config.yml")
}
func hostsConfigFile() string {
return filepath.Join(configDir(), "hosts.yml")
}
func mapFromFile(filename string) (*yamlmap.Map, error) {
data, err := readFile(filename)
if err != nil {
return nil, err
}
return yamlmap.Unmarshal(data)
}
func mapFromString(str string) (*yamlmap.Map, error) {
return yamlmap.Unmarshal([]byte(str))
}
// Config path precedence: GH_CONFIG_DIR, XDG_CONFIG_HOME, AppData (windows only), HOME.
func configDir() string {
var path string
if a := os.Getenv(ghConfigDir); a != "" {
path = a
} else if b := os.Getenv(xdgConfigHome); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(appData); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
return path
}
// State path precedence: XDG_STATE_HOME, LocalAppData (windows only), HOME.
func stateDir() string {
var path string
if a := os.Getenv(xdgStateHome); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(localAppData); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
return path
}
// Data path precedence: XDG_DATA_HOME, LocalAppData (windows only), HOME.
func dataDir() string {
var path string
if a := os.Getenv(xdgDataHome); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(localAppData); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
func readFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
func writeFile(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return err
}
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
return err
}
var defaultGeneralEntries = `
# What protocol to use when performing git operations. Supported values: ssh, https
git_protocol: https
# What editor gh should run when creating issues, pull requests, etc. If blank, will refer to environment.
editor:
# When to interactively prompt. This is a global config that cannot be overridden by hostname. Supported values: enabled, disabled
prompt: enabled
# A pager program to send command output to, e.g. "less". Set the value to "cat" to disable the pager.
pager:
# Aliases allow you to create nicknames for gh commands
aliases:
co: pr checkout
# The path to a unix socket through which send HTTP connections. If blank, HTTP traffic will be handled by net/http.DefaultTransport.
http_unix_socket:
# What web browser gh should use when opening URLs. If blank, will refer to environment.
browser:
`