forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
264 lines (215 loc) · 4.95 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
package github
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"github.com/github/hub/ui"
"github.com/github/hub/utils"
"github.com/howeyc/gopass"
"github.com/mitchellh/go-homedir"
)
var defaultConfigsFile string
func init() {
homeDir, err := homedir.Dir()
utils.Check(err)
defaultConfigsFile = filepath.Join(homeDir, ".config", "hub")
}
type yamlHost struct {
User string `yaml:"user"`
OAuthToken string `yaml:"oauth_token"`
Protocol string `yaml:"protocol"`
}
type yamlConfig map[string][]yamlHost
type Host struct {
Host string `toml:"host"`
User string `toml:"user"`
AccessToken string `toml:"access_token"`
Protocol string `toml:"protocol"`
}
type Config struct {
Hosts []*Host `toml:"hosts"`
}
func (c *Config) PromptForHost(host string) (h *Host, err error) {
token := c.DetectToken()
tokenFromEnv := token != ""
h = c.Find(host)
if h != nil {
if h.User == "" {
// User is missing from the config: this is a broken config probably
// because it was created with an old (broken) version of hub. Let's fix
// it now. See issue #1007 for details.
user := c.PromptForUser(host)
if user == "" {
utils.Check(fmt.Errorf("missing user"))
}
h.User = user
err := newConfigService().Save(configsFile(), c)
utils.Check(err)
}
if tokenFromEnv {
h.AccessToken = token
} else {
return
}
} else {
h = &Host{
Host: host,
AccessToken: token,
Protocol: "https",
}
c.Hosts = append(c.Hosts, h)
}
client := NewClientWithHost(h)
if !tokenFromEnv {
err = c.authorizeClient(client, host)
if err != nil {
return
}
}
currentUser, err := client.CurrentUser()
if err != nil {
return
}
h.User = currentUser.Login
if !tokenFromEnv {
err = newConfigService().Save(configsFile(), c)
}
return
}
func (c *Config) authorizeClient(client *Client, host string) (err error) {
user := c.PromptForUser(host)
pass := c.PromptForPassword(host, user)
var code, token string
for {
token, err = client.FindOrCreateToken(user, pass, code)
if err == nil {
break
}
if ae, ok := err.(*AuthError); ok && ae.IsRequired2FACodeError() {
if code != "" {
ui.Errorln("warning: invalid two-factor code")
}
code = c.PromptForOTP()
} else {
break
}
}
if err == nil {
client.Host.AccessToken = token
}
return
}
func (c *Config) DetectToken() string {
return os.Getenv("GITHUB_TOKEN")
}
func (c *Config) PromptForUser(host string) (user string) {
user = os.Getenv("GITHUB_USER")
if user != "" {
return
}
ui.Printf("%s username: ", host)
user = c.scanLine()
return
}
func (c *Config) PromptForPassword(host, user string) (pass string) {
pass = os.Getenv("GITHUB_PASSWORD")
if pass != "" {
return
}
ui.Printf("%s password for %s (never stored): ", host, user)
if ui.IsTerminal(os.Stdout) {
passBytes, _ := gopass.GetPasswd()
pass = string(passBytes)
} else {
pass = c.scanLine()
}
return
}
func (c *Config) PromptForOTP() string {
fmt.Print("two-factor authentication code: ")
return c.scanLine()
}
func (c *Config) scanLine() string {
var line string
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
line = scanner.Text()
}
utils.Check(scanner.Err())
return line
}
func (c *Config) Find(host string) *Host {
for _, h := range c.Hosts {
if h.Host == host {
return h
}
}
return nil
}
func (c *Config) selectHost() *Host {
options := len(c.Hosts)
if options == 1 {
return c.Hosts[0]
}
prompt := "Select host:\n"
for idx, host := range c.Hosts {
prompt += fmt.Sprintf(" %d. %s\n", idx+1, host.Host)
}
prompt += fmt.Sprint("> ")
ui.Printf(prompt)
index := c.scanLine()
i, err := strconv.Atoi(index)
if err != nil || i < 1 || i > options {
utils.Check(fmt.Errorf("Error: must enter a number [1-%d]", options))
}
return c.Hosts[i-1]
}
func configsFile() string {
configsFile := os.Getenv("HUB_CONFIG")
if configsFile == "" {
configsFile = defaultConfigsFile
}
return configsFile
}
var currentConfig *Config
var configLoadedFrom = ""
func CurrentConfig() *Config {
filename := configsFile()
if configLoadedFrom != filename {
currentConfig = &Config{}
newConfigService().Load(filename, currentConfig)
configLoadedFrom = filename
}
return currentConfig
}
func (c *Config) DefaultHost() (host *Host, err error) {
if GitHubHostEnv != "" {
host, err = c.PromptForHost(GitHubHostEnv)
} else if len(c.Hosts) > 0 {
host = c.selectHost()
// HACK: forces host to inherit GITHUB_TOKEN if applicable
host, err = c.PromptForHost(host.Host)
} else {
host, err = c.PromptForHost(DefaultGitHubHost())
}
return
}
// Public for testing purpose
func CreateTestConfigs(user, token string) *Config {
f, _ := ioutil.TempFile("", "test-config")
defaultConfigsFile = f.Name()
host := &Host{
User: "jingweno",
AccessToken: "123",
Host: GitHubHost,
}
c := &Config{Hosts: []*Host{host}}
err := newConfigService().Save(f.Name(), c)
if err != nil {
panic(err)
}
return c
}