forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_file.go
More file actions
64 lines (57 loc) · 1.31 KB
/
config_file.go
File metadata and controls
64 lines (57 loc) · 1.31 KB
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
package context
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"gopkg.in/yaml.v3"
)
type configEntry struct {
User string
Token string `yaml:"oauth_token"`
}
func parseOrSetupConfigFile(fn string) (*configEntry, error) {
entry, err := parseConfigFile(fn)
if err != nil && errors.Is(err, os.ErrNotExist) {
return setupConfigFile(fn)
}
return entry, err
}
func parseConfigFile(fn string) (*configEntry, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
return parseConfig(f)
}
// ParseDefaultConfig reads the configuration file
func ParseDefaultConfig() (*configEntry, error) {
return parseConfigFile(configFile())
}
func parseConfig(r io.Reader) (*configEntry, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
var config yaml.Node
err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
if len(config.Content) < 1 {
return nil, fmt.Errorf("malformed config")
}
for i := 0; i < len(config.Content[0].Content)-1; i = i + 2 {
if config.Content[0].Content[i].Value == defaultHostname {
var entries []configEntry
err = config.Content[0].Content[i+1].Decode(&entries)
if err != nil {
return nil, err
}
return &entries[0], nil
}
}
return nil, fmt.Errorf("could not find config entry for %q", defaultHostname)
}