-
-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathconfig.go
More file actions
271 lines (230 loc) · 5.55 KB
/
config.go
File metadata and controls
271 lines (230 loc) · 5.55 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
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
package config
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
)
const (
// File is the default name of the JSON file where the config written.
// The user can pass an alternate filename when using the CLI.
File = ".exercism.json"
// LegacyFile is the name of the original config file.
// It is a misnomer, since the config was in json, not go.
LegacyFile = ".exercism.go"
// hostAPI is the endpoint to submit solutions to, and to get personalized data
hostAPI = "http://exercism.io"
// hostXAPI is the endpoint to fetch problems from
hostXAPI = "http://x.exercism.io"
// DirExercises is the default name of the directory for active users.
// Make this non-exported when handlers.Login is deleted.
DirExercises = "exercism"
)
var (
errHomeNotFound = errors.New("unable to locate home directory")
)
// Config represents the settings for particular user.
// This defines both the auth for talking to the API, as well as
// where to put problems that get downloaded.
type Config struct {
APIKey string `json:"apiKey"`
Dir string `json:"dir"`
API string `json:"api"`
XAPI string `json:"xapi"`
File string `json:"-"` // full path to config file
home string // cache user's home directory
}
// Home returns the user's canonical home directory.
// See: http://stackoverflow.com/questions/7922270/obtain-users-home-directory
// we can't cross compile using cgo and use user.Current()
func Home() (string, error) {
var dir string
if runtime.GOOS == "windows" {
dir = os.Getenv("USERPROFILE")
if dir == "" {
dir = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
} else {
dir = os.Getenv("HOME")
}
if dir == "" {
return dir, errHomeNotFound
}
return dir, nil
}
// New returns a configuration struct with content from the exercism.json file
func New(path string) (*Config, error) {
c := &Config{}
err := c.load(path)
return c, err
}
// Update sets new values where given.
func (c *Config) Update(key, host, dir, xapi string) {
key = strings.TrimSpace(key)
if key != "" {
c.APIKey = key
}
host = strings.TrimSpace(host)
if host != "" {
c.API = host
}
dir = strings.TrimSpace(dir)
if dir != "" {
c.SetDir(dir)
}
xapi = strings.TrimSpace(xapi)
if xapi != "" {
c.XAPI = xapi
}
}
// Write saves the config as JSON.
func (c *Config) Write() error {
// truncates existing file if it exists
f, err := os.Create(c.File)
if err != nil {
return err
}
defer f.Close()
b, err := json.MarshalIndent(c, "", "\t")
if err != nil {
return err
}
if _, err := f.Write(b); err != nil {
return err
}
return nil
}
func (c *Config) load(argPath string) error {
path, err := c.resolvePath(argPath)
if err != nil {
return err
}
c.File = path
if err := c.read(); err != nil {
return err
}
// in case people manually update the config file
// with weird formatting
c.APIKey = strings.TrimSpace(c.APIKey)
c.Dir = strings.TrimSpace(c.Dir)
c.API = strings.TrimSpace(c.API)
c.XAPI = strings.TrimSpace(c.XAPI)
return c.setDefaults()
}
func (c *Config) read() error {
if _, err := os.Stat(c.File); err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
f, err := os.Open(c.File)
if err != nil {
return err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(&c); err != nil {
var extra string
if serr, ok := err.(*json.SyntaxError); ok {
if _, serr := f.Seek(0, os.SEEK_SET); serr != nil {
log.Fatalf("seek error: %v", serr)
}
line, str := findInvalidJSON(f, serr.Offset)
extra = fmt.Sprintf(":\ninvalid JSON syntax at line %d:\n%s",
line, str)
}
return fmt.Errorf("error parsing JSON in the config file %s%s\n%s", f.Name(), extra, err)
}
return nil
}
func findInvalidJSON(f io.Reader, pos int64) (int, string) {
var (
col int
line int
errLine []byte
)
buf := new(bytes.Buffer)
fb := bufio.NewReader(f)
for c := int64(0); c < pos; {
b, err := fb.ReadBytes('\n')
if err != nil {
log.Fatalf("read error: %v", err)
}
c += int64(len(b))
col = len(b) - int(c-pos)
line++
errLine = b
}
if len(errLine) != 0 {
buf.WriteString(fmt.Sprintf("%5d: %s <~", line, errLine[:col]))
}
return line, buf.String()
}
// IsAuthenticated returns true if the config contains an API key.
// This does not check whether or not that key is valid.
func (c *Config) IsAuthenticated() bool {
return c.APIKey != ""
}
// homeDir caches the lookup of the user's home directory.
func (c *Config) homeDir() (string, error) {
if c.home != "" {
return c.home, nil // only set during testing
}
return Home()
}
func (c *Config) resolvePath(argPath string) (string, error) {
path := argPath
if path == "" {
path = filepath.Join("~", File)
}
h, err := c.homeDir()
if err != nil {
return "", err
}
path = expandHome(path, h)
fi, _ := os.Stat(path)
if fi != nil && fi.IsDir() {
path = filepath.Join(path, File)
}
return path, nil
}
func (c *Config) setDefaults() error {
if c.API == "" {
c.API = hostAPI
}
if c.XAPI == "" {
c.XAPI = hostXAPI
}
if err := c.SetDir(c.Dir); err != nil {
return err
}
return nil
}
// SetDir sets the configuration directory to the given path
// or defaults to the home exercism directory
func (c *Config) SetDir(path string) error {
home, err := c.homeDir()
if err != nil {
return err
}
if path == "" {
c.Dir = filepath.Join(home, DirExercises)
} else {
c.Dir = path
}
c.Dir = expandHome(c.Dir, home)
return nil
}
func expandHome(path, home string) string {
if path[:2] == "~"+string(os.PathSeparator) {
return strings.Replace(path, "~", home, 1)
}
return path
}