-
Notifications
You must be signed in to change notification settings - Fork 32
/
middleware.go
316 lines (261 loc) · 6.91 KB
/
middleware.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
package cmd
import (
"context"
"fmt"
"os"
"reflect"
"strings"
"time"
"github.com/urfave/cli"
"gopkg.in/oleiade/reflections.v1"
"github.com/arigatomachine/cli/api"
"github.com/arigatomachine/cli/apitypes"
"github.com/arigatomachine/cli/config"
"github.com/arigatomachine/cli/dirprefs"
"github.com/arigatomachine/cli/prefs"
)
// chain allows easy sequential calling of BeforeFuncs and AfterFuncs.
// chain will exit on the first error seen.
func chain(funcs ...func(*cli.Context) error) func(*cli.Context) error {
return func(ctx *cli.Context) error {
for _, f := range funcs {
err := f(ctx)
if err != nil {
return err
}
}
return nil
}
}
// ensureDaemon ensures that the daemon is running, and is the correct version,
// before a command is exeucted.
// the daemon will be started/restarted once, to try and launch the latest
// version.
func ensureDaemon(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
proc, err := findDaemon(cfg)
if err != nil {
return err
}
spawned := false
if proc == nil {
err := spawnDaemon()
if err != nil {
return err
}
spawned = true
}
client := api.NewClient(cfg)
var v *apitypes.Version
increment := 5 * time.Millisecond
for d := increment; d < 1*time.Second; d += increment {
v, err = client.Version.Get(context.Background())
if err == nil {
break
}
time.Sleep(d)
}
if err != nil {
return cli.NewExitError("Error communicating with the daemon: "+err.Error(), -1)
}
if v.Version == cfg.Version {
return nil
}
if spawned {
return cli.NewExitError("The daemon version is incorrect. Check for stale processes", -1)
}
fmt.Println("The daemon version is out of date and is being restarted.")
fmt.Println("You will need to login again.")
_, err = stopDaemon(proc)
if err != nil {
return err
}
return ensureDaemon(ctx)
}
// ensureSession ensures that the user is logged in with the daemon and has a
// valid session. If not, it will attempt to log the user in via environment
// variables. If they do not exist, of the login fails, it will abort the
// command.
func ensureSession(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
_, err = client.Session.Get(context.Background())
hasSession := true
if err != nil {
if cerr, ok := err.(*apitypes.Error); ok {
if cerr.Type == apitypes.UnauthorizedError {
hasSession = false
}
}
if hasSession {
return cli.NewExitError("Error communicating with the daemon: "+err.Error(), -1)
}
}
if hasSession {
return nil
}
email, hasEmail := os.LookupEnv("TORUS_EMAIL")
password, hasPassword := os.LookupEnv("TORUS_PASSWORD")
if hasEmail && hasPassword {
fmt.Println("Attempting to login with email: " + email)
err := client.Session.Login(context.Background(), email, password)
if err != nil {
fmt.Println("Could not log in: " + err.Error())
} else {
return nil
}
}
msg := "You must be logged in to run '" + ctx.Command.FullName() + "'.\n" +
"Login using 'login' or create an account using 'signup'."
return cli.NewExitError(msg, -1)
}
// loadDirPrefs loads argument values from the .torus.json file
func loadDirPrefs(ctx *cli.Context) error {
p, err := prefs.NewPreferences(true)
if err != nil {
return err
}
d, err := dirprefs.Load(true)
if err != nil {
return err
}
return reflectArgs(ctx, p, d, "json")
}
// loadPrefDefaults loads default argument values from the .torusrc
// preferences file defaults section, inserting them into any unset flag values
func loadPrefDefaults(ctx *cli.Context) error {
p, err := prefs.NewPreferences(true)
if err != nil {
return err
}
return reflectArgs(ctx, p, p.Defaults, "ini")
}
func reflectArgs(ctx *cli.Context, p *prefs.Preferences, i interface{},
tagName string) error {
// The user has disabled reading arguments from prefs and .torus.json
if !p.Core.Context {
return nil
}
// tagged field names match the argument names
tags, err := reflections.Tags(i, tagName)
if err != nil {
return err
}
flags := make(map[string]bool)
for _, flagName := range ctx.FlagNames() {
// This value is already set via arguments or env vars. skip it.
if isSet(ctx, flagName) {
continue
}
flags[flagName] = true
}
for fieldName, tag := range tags {
name := strings.SplitN(tag, ",", 2)[0] // remove omitempty if its there
if _, ok := flags[name]; ok {
field, err := reflections.GetField(i, fieldName)
if err != nil {
return err
}
if f, ok := field.(string); ok && f != "" {
ctx.Set(name, field.(string))
}
}
}
return nil
}
// setUserEnv populates the env argument, if present and unset,
// with dev-USERNAME
func setUserEnv(ctx *cli.Context) error {
argName := "environment"
// Check for env flag, just in case this middleware is misused
hasEnvFlag := false
for _, name := range ctx.FlagNames() {
if name == argName {
hasEnvFlag = true
break
}
}
if !hasEnvFlag {
return nil
}
if isSet(ctx, argName) {
return nil
}
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
u, err := client.Users.Self(context.Background())
if err != nil {
return err
}
ctx.Set(argName, "dev-"+u.Body.Username)
return nil
}
// setSliceDefaults populates any string slice flags with the default value
// if nothing else is set. This is different from the default urfave default
// Value, which will always be included in the string slice options.
func setSliceDefaults(ctx *cli.Context) error {
for _, f := range ctx.Command.Flags {
if psf, ok := f.(placeHolderStringSliceFlag); ok {
name := strings.SplitN(psf.GetName(), ",", 2)[0]
if psf.Default != "" && len(ctx.StringSlice(name)) == 0 {
ctx.Set(name, psf.Default)
}
}
}
return nil
}
func isSet(ctx *cli.Context, name string) bool {
value := ctx.Generic(name)
if value != nil {
v := reflect.Indirect(reflect.ValueOf(value))
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
return v.Len() != 0
}
return true
}
return false
}
// CheckRequiredFlags ensures that any required flags have been set either on
// the command line, or through envvars/prefs files.
func checkRequiredFlags(ctx *cli.Context) error {
missing := []string{}
for _, f := range ctx.Command.Flags {
var name string
flagMissing := false
switch pf := f.(type) {
case placeHolderStringFlag:
name = strings.SplitN(pf.GetName(), ",", 2)[0]
if pf.Required && ctx.String(name) == "" {
flagMissing = true
}
case placeHolderStringSliceFlag:
name = strings.SplitN(pf.GetName(), ",", 2)[0]
if pf.Required && len(ctx.StringSlice(name)) == 0 {
flagMissing = true
}
}
if flagMissing {
prefix := "-"
if len(name) > 1 {
prefix = "--"
}
missing = append(missing, prefix+name)
}
}
if len(missing) > 0 {
msg := "Missing flags: " + strings.Join(missing, ", ") + "\n"
msg += usageString(ctx)
return cli.NewExitError(msg, -1)
}
return nil
}