-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
132 lines (117 loc) · 2.41 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
package godzil
import (
"bytes"
"os"
"path/filepath"
"strings"
"github.com/Songmu/gitconfig"
"github.com/Songmu/prompter"
"github.com/goccy/go-yaml"
"github.com/natefinch/atomic"
)
func getGitConfig(k string) (string, error) {
u, err := gitconfig.Get(k)
if err != nil {
if gitconfig.IsNotFound(err) {
return "", nil
}
return "", err
}
return u, nil
}
type config struct {
User string `yaml:"user,omitempty"`
Host string `yaml:"host,omitempty"`
Root string `yaml:"root,omitempty"`
filepath string
}
func (c *config) host() string {
if c.Host != "" {
return c.Host
}
return "github.com"
}
func (c *config) user() (string, error) {
if c.User != "" {
return c.User, nil
}
c.User, _ = gitconfig.GitHubUser(c.host())
if c.User != "" {
return c.User, nil
}
var githubID string
for githubID == "" {
githubID = prompter.Prompt("Enter your GitHub ID", "")
}
c.User = githubID
if err := c.save(); err != nil {
return "", err
}
return c.User, nil
}
func (c *config) root() (string, error) {
if c.Root != "" {
return expandTilde(c.Root)
}
r, err := getGitConfig("ghq.root")
if err != nil {
return "", err
}
return expandTilde(r)
}
func (c *config) profilesBase() string {
return filepath.Join(filepath.Dir(c.filepath), "profiles")
}
func (c *config) save() error {
if err := os.MkdirAll(filepath.Dir(c.filepath), 0755); err != nil {
return err
}
b, _ := yaml.Marshal(c)
return atomic.WriteFile(c.filepath, bytes.NewReader(b))
}
func loadConfig() (*config, error) {
root, err := configRoot()
if err != nil {
return nil, err
}
configPath := filepath.Join(root, "config.yaml")
c := config{filepath: configPath}
f, err := os.Open(c.filepath)
if err != nil {
if os.IsNotExist(err) {
return &c, nil
}
return nil, err
}
defer f.Close()
if err := yaml.NewDecoder(f).Decode(&c); err != nil {
return nil, err
}
return &c, err
}
const xdgConfigHomeEnv = "XDG_CONFIG_HOME"
func configRoot() (string, error) {
root := os.Getenv(xdgConfigHomeEnv)
if root == "" {
root = "~/.config"
}
var err error
root, err = expandTilde(root)
if err != nil {
return "", err
}
return filepath.Join(root, "godzil"), nil
}
func expandTilde(p string) (string, error) {
if p == "" {
return p, nil
}
if p[0] == '~' && (len(p) == 1 || p[1] == '/') {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return strings.Replace(p, "~", homeDir, 1), nil
}
return p, nil
}