-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommand.go
432 lines (413 loc) · 8.78 KB
/
command.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Copyright 2018 Daniel Theophanes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package task
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// Command represents an Action that may be invoked with a name.
// Flags will be mapped to State bucket values.
// Extra arguments at the end of a command chain will be passed to the state as
// "args []string". To pass arguments to a command that has sub-commands, first
// pass in "--" then pass in the arguments.
//
// exec cmd arg1 arg2 # cmd has no sub-commands.
// exec cmd -- arg1 arg2 # cmd has one or more sub-commands.
type Command struct {
Name string
Usage string
Flags []*Flag
Commands []*Command
Action Action
}
// Flag represents values that may be set on comments.
// Values will be mapped to State bucket values.
type Flag struct {
Name string // Name of the flag.
ENV string // Optional env var to read from if flag not present.
Usage string
Required bool // Required flag, will error if not set.
Value any
Default any
Type FlagType
Validate func(v any) error
}
// FlagType is set in Flag and determins how the value is parsed.
type FlagType byte
// FlagType options. If a default is present the flag type may be left as
// Auto to choose the parse type based on the default type.
const (
FlagAuto FlagType = iota
FlagString
FlagBool
FlagInt64
FlagFloat64
FlagDuration
)
func (ft FlagType) spaceValue() bool {
switch ft {
default:
return true
case FlagBool:
return false
}
}
type flagStatus struct {
flag *Flag
used bool
env bool
}
func flagType(v any) FlagType {
switch v.(type) {
default:
return FlagAuto
case string, *string:
return FlagString
case bool, *bool:
return FlagBool
case int64, *int64:
return FlagInt64
case int32, *int32:
return FlagInt64
case int, *int:
return FlagInt64
case float64, *float64:
return FlagFloat64
case float32, *float32:
return FlagFloat64
case time.Duration, *time.Duration:
return FlagDuration
}
}
func (fs *flagStatus) init() error {
fl := fs.flag
// If a default value is set, automatically set the flag type.
if fl.Type == FlagAuto && fl.Value != nil {
fl.Type = flagType(fl.Value)
}
if fl.Type == FlagAuto && fl.Default != nil {
fl.Type = flagType(fl.Default)
}
if fl.Default != nil {
var ok bool
switch fl.Type {
default:
return fmt.Errorf("unknown flag type %v", fl.Type)
case FlagString:
_, ok = fl.Default.(string)
case FlagBool:
_, ok = fl.Default.(bool)
case FlagInt64:
switch v := fl.Default.(type) {
case int32:
fl.Default = int64(v)
ok = true
case int:
fl.Default = int64(v)
ok = true
case int64:
ok = true
}
case FlagFloat64:
switch v := fl.Default.(type) {
case float32:
fl.Default = float64(v)
ok = true
case float64:
ok = true
}
case FlagDuration:
_, ok = fl.Default.(time.Duration)
}
if !ok {
return fmt.Errorf("invalid default flag value %[1]v (%[1]T) for -%[2]s", fl.Default, fl.Name)
}
}
if fl.Value != nil {
var ok bool
switch fl.Type {
default:
return fmt.Errorf("unknown flag type %v", fl.Type)
case FlagString:
_, ok = fl.Value.(*string)
case FlagBool:
_, ok = fl.Value.(*bool)
case FlagInt64:
switch fl.Value.(type) {
case *int32:
ok = true
case *int:
ok = true
case *int64:
ok = true
}
case FlagFloat64:
switch fl.Value.(type) {
case *float32:
ok = true
case *float64:
ok = true
}
case FlagDuration:
_, ok = fl.Default.(*time.Duration)
}
if !ok {
return fmt.Errorf("invalid default flag value %[1]v (%[1]T) for -%[2]s", fl.Default, fl.Name)
}
}
return nil
}
func (fs *flagStatus) set(st *State, vs string, fromENV bool) error {
fl := fs.flag
if fs.used {
setFromENV := !fromENV && fs.env
if !setFromENV {
return fmt.Errorf("flag -%s already declared", fl.Name)
}
}
fs.used = true
if fromENV {
fs.env = true
}
var setv any
switch fl.Type {
default:
return fmt.Errorf("unknown flag type %v", fl.Type)
case FlagAuto:
setv = vs
case FlagString:
if x, ok := fl.Value.(*string); ok {
*x = vs
}
setv = vs
case FlagBool:
if vs == "" {
if x, ok := fl.Value.(*bool); ok {
*x = true
}
setv = true
} else {
v, err := strconv.ParseBool(vs)
if err != nil {
return err
}
if x, ok := fl.Value.(*bool); ok {
*x = v
}
setv = v
}
case FlagInt64:
v, err := strconv.ParseInt(vs, 10, 64)
if err != nil {
return err
}
switch x := fl.Value.(type) {
case *int32:
*x = int32(v)
case *int:
*x = int(v)
case *int64:
*x = int64(v)
}
setv = v
case FlagFloat64:
v, err := strconv.ParseFloat(vs, 64)
if err != nil {
return err
}
switch x := fl.Value.(type) {
case *float32:
*x = float32(v)
case *float64:
*x = float64(v)
}
setv = v
case FlagDuration:
v, err := time.ParseDuration(vs)
if err != nil {
return err
}
switch x := fl.Value.(type) {
case *time.Duration:
*x = v
}
setv = v
}
st.Set(fl.Name, setv)
if fl.Validate != nil {
err := fl.Validate(setv)
if err != nil {
return fmt.Errorf("%s: %w", fl.Name, err)
}
}
return nil
}
func (fs *flagStatus) setDefault(st *State) {
fl := fs.flag
if fl.Default == nil {
return
}
st.Set(fl.Name, fl.Default)
}
// Exec takes a command arguments and returns an Action, ready to be run.
func (c *Command) Exec(args []string) Action {
return ActionFunc(func(ctx context.Context, st *State, sc Script) error {
if sc == nil {
return errors.New("missing Script")
}
flagLookup := make(map[string]*flagStatus)
cmdLookup := make(map[string]*Command)
for _, cmd := range c.Commands {
cmdLookup[cmd.Name] = cmd
}
for _, fl := range c.Flags {
fs := &flagStatus{flag: fl}
if err := fs.init(); err != nil {
return err
}
if len(fs.flag.ENV) > 0 {
if v, ok := st.Env[fs.flag.ENV]; ok && len(v) > 0 {
if err := fs.set(st, v, true); err != nil {
return err
}
}
}
flagLookup[fl.Name] = fs
}
// First parse any flags.
// The first non-flag seen is a sub-command, stop after the cmd is found.
var nextFlag *flagStatus
for len(args) > 0 {
a := args[0]
prevArgs := args
args = args[1:]
if nextFlag != nil {
if err := nextFlag.set(st, a, false); err != nil {
return err
}
nextFlag.used = true
nextFlag = nil
continue
}
if len(a) == 0 {
continue
}
if a[0] != '-' {
if len(cmdLookup) == 0 {
// This is an argument.
st.Set("args", prevArgs)
break
}
// This is a subcommand.
for _, fs := range flagLookup {
if fs.used {
continue
}
fs.setDefault(st)
}
cmd, ok := cmdLookup[a]
if !ok {
return c.helpError("invalid command %q", a)
}
sc.Add(cmd.Exec(args))
return nil
}
a = a[1:]
if a == "-" { // "--"
st.Set("args", args)
break
}
// This is a flag.
nameValue := strings.SplitN(a, "=", 2)
fl, ok := flagLookup[nameValue[0]]
if !ok {
return c.helpError("invalid flag -%s", nameValue[0])
}
val := ""
if len(nameValue) == 1 {
if fl.flag.Type.spaceValue() {
nextFlag = fl
continue
}
} else {
val = nameValue[1]
}
if err := fl.set(st, val, false); err != nil {
return err
}
}
for _, fs := range flagLookup {
if fs.used {
continue
}
fs.setDefault(st)
if fs.flag.Required {
return c.helpError("flag %q required", fs.flag.Name)
}
}
if nextFlag != nil {
return fmt.Errorf("expected value after flag %q", nextFlag.flag.Name)
}
if c.Action == nil {
return c.helpError("incorrect command")
}
sc.Add(c.Action)
return nil
})
}
// ErrUsage signals that the error returned is not a runtime error
// but a usage message.
type ErrUsage string
func (err ErrUsage) Error() string {
return string(err)
}
func (c *Command) helpError(f string, v ...interface{}) error {
msg := &strings.Builder{}
if len(f) > 0 {
fmt.Fprintf(msg, f, v...)
msg.WriteRune('\n')
}
msg.WriteString(c.Name)
if len(c.Usage) > 0 {
msg.WriteString(" - ")
msg.WriteString(c.Usage)
}
msg.WriteString("\n")
for _, fl := range c.Flags {
msg.WriteString("\t")
msg.WriteRune('-')
if fl.Required {
msg.WriteString("*")
}
msg.WriteString(fl.Name)
if len(fl.ENV) > 0 {
msg.WriteString(" [")
msg.WriteString(fl.ENV)
msg.WriteString("]")
}
if len(fl.Usage) > 0 {
msg.WriteString(" - ")
msg.WriteString(fl.Usage)
}
if fl.Default != nil {
fmt.Fprintf(msg, " (%v)", fl.Default)
}
msg.WriteString("\n")
}
msg.WriteString("\n")
for _, sub := range c.Commands {
msg.WriteString("\t")
msg.WriteString(sub.Name)
if len(sub.Usage) > 0 {
msg.WriteString(" - ")
msg.WriteString(sub.Usage)
}
msg.WriteString("\n")
}
return ErrUsage(msg.String())
}