-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.go
325 lines (276 loc) · 7.86 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package config
import (
"errors"
"io/ioutil"
"os"
"os/user"
"path"
"path/filepath"
"github.com/go-ini/ini"
"github.com/manifoldco/go-manifold"
"github.com/stripe/stripe-go"
"gopkg.in/yaml.v2"
)
// Version represents the version of the cli. This variable is updated at build
// time.
var Version = "dev"
// StripePublishableKey facilitates secure transmission of payment values
var StripePublishableKey = "pk_live_A6qSWh1v4SrNnrWSftgDcKFQ"
// GitHubClientID facilitates logins with GitHub
var GitHubClientID = "40ff4213256c4b253c7f"
var GitHubCallback = "https://dashboard.manifold.co/login/oauth/github"
func init() {
stripe.LogLevel = 0
stripe.Key = StripePublishableKey
}
const (
requiredPermissions = 0600
defaultHostname = "manifold.co"
defaultScheme = "https"
defaultAnalytics = true
rcFilename = ".manifoldrc"
// YamlFilename is where dirprefs are stored
YamlFilename = ".manifold.yml"
)
// ErrMissingHomeDir represents an error when a home directory could not be found
var ErrMissingHomeDir = errors.New("Could not find Home Directory")
// ErrPluginNotFound is returned if a particular plugin doesn't exist in the yaml when requested
var ErrPluginNotFound = errors.New("Plugin not found")
// ErrWrongConfigPermissions represents an error when the config permissions
// are incorrect.
var ErrWrongConfigPermissions = errors.New(
"~/.manifoldrc must be only readable and writable to the current user (0600)")
// ErrExpectedFile represents an error where the manifoldrc file was a
// directory instead of a file.
var ErrExpectedFile = errors.New("Expected ~/.manifoldrc to be a file; found a directory")
// Load checks if ~/.manifoldrc exists, if it does, it reads it from disk.
//
// If it doesn't an empty config with the default values is returned.
//
// If the file cannot be read, or it has the incorrect permissions an error is
// returned.
func Load() (*Config, error) {
return loadConfigurationCheckLegacy()
}
// LoadIgnoreLegacy checks if ~/.manifoldrc exists, if it does, it reads it from disk. This func ignores the legacy check.
//
// If it doesn't an empty config with the default values is returned.
//
// If the file cannot be read, or it has the incorrect permissions an error is
// returned.
func LoadIgnoreLegacy() (*Config, error) {
return loadConfiguration()
}
func loadConfiguration() (*Config, error) {
rcpath, err := RCPath()
if err != nil {
return nil, err
}
cfg := &Config{
Hostname: defaultHostname,
AuthToken: "",
TransportScheme: defaultScheme,
Analytics: defaultAnalytics,
GitHubCallback: GitHubCallback,
}
f, err := os.OpenFile(rcpath, os.O_RDONLY, requiredPermissions)
switch {
case err == nil: // ok
case os.IsNotExist(err):
return cfg, nil
default:
return nil, err
}
f.Close()
err = ini.MapTo(cfg, rcpath)
if err != nil {
return nil, err
}
return cfg, nil
}
func loadConfigurationCheckLegacy() (*Config, error) {
cfg, err := loadConfiguration()
if err != nil {
return nil, err
}
err = cfg.IdentifyLegacyValues()
if err != nil {
return nil, err
}
return cfg, nil
}
// RCPath returns the absolute path to the ~/.manifoldrc file
func RCPath() (string, error) {
home, err := UserHome()
if err != nil {
return "", err
}
return path.Join(home, rcFilename), nil
}
// Config represents the configuration which is stored inside a ~/.manifoldrc
// file in ini format.
type Config struct {
Hostname string `ini:"hostname"`
AuthToken string `ini:"auth_token"`
TransportScheme string `ini:"scheme"`
Analytics bool `ini:"analytics"`
LegacyTeam string `ini:"team,omitempty"`
TeamTitle string `ini:"team_title,omitempty"`
TeamName string `ini:"team_name,omitempty"`
TeamID string `ini:"team_id,omitempty"`
GitHubCallback string `ini:"github_callback,omitempty"`
}
// IdentifyLegacyValues identifies if a user's config file is out of date
// aiding migration, or suggesting a fix
func (c *Config) IdentifyLegacyValues() error {
if c.LegacyTeam != "" {
// Team was moved into three parts: TeamTitle, TeamName and TeamID
_, err := manifold.DecodeIDFromString(c.LegacyTeam)
if err != nil {
return errors.New("Invalid configuration. Please run `manifold switch` to fix, then you may execute your command")
}
c.TeamID = c.LegacyTeam
c.LegacyTeam = ""
err = c.Write()
if err != nil {
return err
}
}
return nil
}
// Write writes the contents of the Config struct to ~/.manifoldrc and sets the
// appropriate permissions.
func (c *Config) Write() error {
rcpath, err := RCPath()
if err != nil {
return err
}
f, err := os.OpenFile(rcpath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, requiredPermissions)
if err != nil {
return err
}
// Finish writing file before we close, due to race condition inside go-ini
defer func() {
f.Sync()
f.Close()
}()
cfg := ini.Empty()
err = ini.ReflectFrom(cfg, c)
if err != nil {
return err
}
_, err = cfg.WriteTo(f)
return err
}
// ManifoldYaml represents the standard project config object
type ManifoldYaml struct {
Project string `yaml:"project,omitempty" flag:"project,omitempty"`
Team string `yaml:"team,omitempty" flag:"team,omitempty"`
Plugins map[string]interface{} `yaml:"plugins,omitempty"`
Path string `yaml:"-" json:"-"`
}
// GetPlugin retrieves plugins config for the given plugin name
func (m ManifoldYaml) GetPlugin(name string, conf interface{}) error {
if m.Plugins == nil {
return ErrPluginNotFound
}
if _, ok := m.Plugins[name]; ok {
// TODO: Can this just be reflected into the interface?
str, err := yaml.Marshal(m.Plugins[name])
if err != nil {
return errors.New("Invalid configuration")
}
err = yaml.Unmarshal(str, conf)
if err != nil {
return errors.New("Failed to read configuration")
}
return nil
}
return ErrPluginNotFound
}
// SavePlugin writes the ManifoldYaml values for a specific plugin name
func (m *ManifoldYaml) SavePlugin(name string, conf interface{}) error {
if m.Plugins == nil {
m.Plugins = make(map[string]interface{})
}
m.Plugins[name] = conf
return m.Save()
}
// Save writes the ManifoldYaml values to the file in the struct's Path
// field
func (m *ManifoldYaml) Save() error {
yml, err := yaml.Marshal(m)
if err != nil {
return err
}
path := m.Path
if path == "" {
// Set the yaml in the current directory if path is not known
wd, err := os.Getwd()
if err != nil {
return err
}
path = filepath.Join(wd, YamlFilename)
}
err = ioutil.WriteFile(path, yml, requiredPermissions)
if err != nil {
return err
}
return nil
}
// Remove removes the backing file for this ManifoldYaml
func (m *ManifoldYaml) Remove() error {
return os.Remove(m.Path)
}
// LoadYaml loads ManifoldYaml. It starts in the current working directory,
// looking for a readable '.manifold.yml' file, and walks up the directory
// hierarchy until it finds one, or reaches the root of the fs.
//
// It returns an empty ManifoldYaml is no '.manifold.yml' files are found.
// It returns an error if a malformed file is found, or if any errors occur
// during file system access.
func LoadYaml(recurse bool) (*ManifoldYaml, error) {
path, err := os.Getwd()
if err != nil {
return nil, err
}
prefs := &ManifoldYaml{}
var f *os.File
for {
f, err = os.Open(filepath.Join(path, YamlFilename))
if err != nil {
newPath := filepath.Dir(path)
if path == newPath || !recurse {
return prefs, nil
}
path = newPath
continue
}
break
}
defer f.Close()
contents, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(contents, prefs)
if err != nil {
return nil, err
}
prefs.Path = f.Name()
return prefs, nil
}
func UserHome() (string, error) {
home := os.Getenv("HOME")
if home != "" {
return home, nil
}
u, err := user.Current()
if err != nil {
return "", err
}
if u.HomeDir == "" {
return "", ErrMissingHomeDir
}
return u.HomeDir, nil
}