-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
574 lines (509 loc) · 14.3 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package gommand
import (
"context"
"errors"
"fmt"
"os"
"slices"
"sort"
"strings"
"github.com/jimmykodes/gommand/flags"
"github.com/jimmykodes/gommand/internal/lexer"
)
var (
ErrNoRunner = errors.New("gommand: command has no run function")
ErrNoSubcommand = errors.New("gommand: must specify a subcommand")
errShowHelp = errors.New("show help")
errShowVersion = errors.New("show version")
)
// Command represents a command line command
//
// The order of functions is:
// - PersistentPreRun -- see note on field
// - PreRun
// - Run
// - PostRun
// - PersistentPostRun -- see note of field
//
// if PersistentPreRun or PreRun return an error, execution is stopped and the error is returned
// if Run returns an error and DeferPost is false, execution is stopped and the error is returned
// if DeferPost is true, PostRun and PersistentPostRun will be executed even if Run returns an error
type Command struct {
// Name is the name of the command.
// This is ignored if the command is invoked using Execute or ExecuteContext, but if registered as a subcommand
// of a function, the name defines how the subcommand is called.
// ex:
// c1 := &Command{Name: "entrypoint"}
// c2 := &Command{Name: "my-sub-command", Run: func(*Context) error { fmt.Println("sub"); return nil }}
//
// c1.SubCommand(c2)
//
// func main() {
// _ = c1.Execute()
// }
//
// c2 would be called by running
// entrypoint my-sub-command
//
// Anything included after a space is expected to be usage descriptions
// General syntax guidance
// ... indicates multiple of the preceding argument can be provided
// [ ] indicates optional arguments
// { } indicates a set of mutually exclusive required arguments
// | indicates mutually exclusive arguments, where only one value in the set
// should be provided at a time. As described above, if the set of arguments
// are optional, the set should be enclosed in [ ] otherwise they should be
// enclosed in { }
//
// Example: create {--from-file file | --from-gcs bucket} [-d destination] file_name...
Name string
// Usage is the short explanation of the command
Usage string
// Description is the longer description of the command printed out by the help text
Description string
// Aliases are aliases for the current command.
//
// Ex:
// c1 := &Command{Name: "items"}
// c2 := &Command{Name: "list", Aliases: []string{"ls", "l"}}
// c1.SubCommand(c2)
//
// items list
// items ls
// items l
//
// All are valid ways of executing the `list` command
Aliases []string
// Version is the value that will be printed when `--version` is passed to the command.
// When retrieving the command version, the call tree is traversed backwards until a Command
// is reached that has a non-zero value for the version. This means that it is possible
// to version individual branches of the call tree, though this is not recommended. It is
// intended to be set at the root of the tree, ideally through a package level var that can
// be set using ldflags at build time
// ie: go build -ldflags="cmd.Version=1.1.0"
Version string
// ArgValidator is an ArgValidator to be called on the args of the function being executed. This is called before any of
// the functions for this command are called.
// If this is not defined ArgsNone is used.
ArgValidator ArgValidator
// Flags are a slice of flags.Flag that will be used to initialize the command's FlagSet
FlagSet *flags.FlagSet
// PersistentFlags are a slice of flags.Flag that will be used to initialize the command's PersistentFlagSet
PersistentFlagSet *flags.FlagSet
// Run is the core function the command should execute
Run func(*Context) error
// PreRun will run immediately before Run, if defined
PreRun func(*Context) error
// PostRun will run immediately after Run if defined and either Run exits with no error or DeferPost is true
PostRun func(*Context) error
// PersistentPreRun is a function that will run before PreRun and will be run for any subcommands of this command.
//
// PersistentPreRun commands are executed in FIFO order
//
// ex:
// c1 := &Command{Name: "c1", PersistentPreRun: func(*Context) error { fmt.Println("c1"); return nil }}
// c2 := &Command{Name: "c2", PersistentPreRun: func(*Context) error { fmt.Println("c2"); return nil }}
// c3 := &Command{Name: "c3", Run: func(*Context) error { fmt.Println("c3"); return nil }}
//
// c1.SubCommand(c2)
// c2.SubCommand(c3)
//
// When c3 is run, stdout will see
// c1
// c2
// c3
//
// If any of the nested commands return an error, all execution is stopped and that error is returned.
PersistentPreRun func(*Context) error
// PersistentPostRun is a function that will run after PostRun and will be run for any subcommands of this command.
//
// PersistentPostRun commands are executed in LIFO order
//
// ex:
// c1 := &Command{Name: "c1", PersistentPostRun: func(*Context) error { fmt.Println("c1"); return nil }}
// c2 := &Command{Name: "c2", PersistentPostRun: func(*Context) error { fmt.Println("c2"); return nil }}
// c3 := &Command{Name: "c3", Run: func(*Context) error { fmt.Println("c3"); return nil }}
//
// c1.SubCommand(c2)
// c2.SubCommand(c3)
//
// when c3 is run, stdout will see
// c3
// c2
// c1
//
// If any of the nested commands return an error, execution will stop and the error will be returned, unless DeferPost
// is true, in which case the error will be recorded and returned at the end, but the remaining functions will still
// execute
PersistentPostRun func(*Context) error
// DeferPost will defer PersistentPostRun and PostRun functions.
// This will cause them to run even if the Run function exits with an error.
// Setting this value is persistent, meaning any subcommands from where this is set will
// also defer their post run functions
DeferPost bool
// SilenceHelp will not print the help message if the command exits with an error.
// This field will propagate to subcommands and cannot be overwritten by the child, so if any
// point of a command's upstream lineage has the value set, the help message will be silenced
SilenceHelp bool
// SilenceError is like SilenceHelp but does not print the "Error: xxx" message when the command
// exits with an error
SilenceError bool
parent *Command
commands commands
err error
}
func (c *Command) ExecuteContext(ctx context.Context) error {
cmdCtx := &Context{
Context: ctx,
args: os.Args[1:],
}
err := c.execute(cmdCtx)
if errors.Is(err, errShowHelp) {
cmdCtx.cmd.help()
return nil
}
if errors.Is(err, errShowVersion) {
v := c._version()
if v == "" {
v = "N/A"
}
fmt.Println(v)
return nil
}
if mErr := errors.Join(err, c.err); mErr != nil {
if !cmdCtx.silenceHelp {
cmdCtx.cmd.help()
}
if !cmdCtx.silenceError {
fmt.Println("Error:", mErr)
}
return mErr
}
return nil
}
func (c *Command) Execute() error {
return c.ExecuteContext(context.Background())
}
func (c *Command) SubCommand(cmds ...*Command) {
for _, command := range cmds {
c.subCommand(command)
}
}
func (c *Command) name() (name string) {
name, _, _ = strings.Cut(c.Name, " ")
return
}
func (c *Command) _version() string {
_c := c
for _c.Version == "" {
if _c.parent == nil {
break
}
_c = _c.parent
}
return _c.Version
}
func (c *Command) help() {
if c.Description != "" {
fmt.Println(c.Description)
fmt.Println()
} else if c.Usage != "" {
fmt.Println(c.Usage)
fmt.Println()
}
if v := c._version(); v != "" {
fmt.Println("Version:", v)
fmt.Println()
}
fmt.Println("Usage:")
usage := []string{c.Name}
for parent := c.parent; parent != nil; parent = parent.parent {
usage = append([]string{parent.name()}, usage...)
}
fmt.Print(" ", strings.Join(usage, " "))
if len(c.commands) > 0 {
fmt.Print(" [commands]")
}
fmt.Println()
fmt.Println()
if len(c.Aliases) > 0 {
fmt.Println("Aliases:")
fmt.Printf(" %s\n\n", strings.Join(c.Aliases, ", "))
}
fs := flags.NewFlagSet(flags.WithHelpFlag()).AddFlagSet(c.FlagSet)
pfs := flags.NewFlagSet()
for p := c; p != nil; p = p.parent {
pfs.AddFlagSet(p.PersistentFlagSet)
}
if len(c.commands) > 0 {
fmt.Println("Available Commands:")
fmt.Println(c.commands)
}
fsStr := fs.Repr()
pfsStr := pfs.Repr()
fmt.Println("Flags:")
fmt.Println(fsStr)
if pfsStr != "" {
fmt.Println()
fmt.Println("Global Flags:")
fmt.Println(pfsStr)
}
}
func (c *Command) subCommand(cmd *Command) {
// todo: how to handle commands with the same name
// warn? silently overwrite? return err?
if c.commands == nil {
c.commands = make(map[string]*Command)
}
c.commands[cmd.name()] = cmd
for _, alias := range cmd.Aliases {
c.commands[alias] = cmd
}
cmd.parent = c
}
func (c *Command) hasSubCommands() bool {
return len(c.commands) > 0
}
func (c *Command) execute(ctx *Context) error {
// ################
// Append any persistent configs
// ################
ctx.cmd = c
ctx.addPersistentFlags(c.PersistentFlagSet)
// append pre run functions to be executed in order
ctx.preRuns = append(ctx.preRuns, func(ctx *Context) error { return nil })
if c.PersistentPreRun != nil {
ctx.preRuns[ctx.depth] = c.PersistentPreRun
}
// append post run functions, to be defered in order
if c.PersistentPostRun != nil {
ctx.postRuns = append(ctx.postRuns, c.PersistentPostRun)
}
if c.DeferPost {
ctx.deferPost = true
}
if c.SilenceError {
ctx.silenceError = true
}
if c.SilenceHelp {
ctx.silenceHelp = true
}
// ################
// Walk the command tree
// ################
if c.hasSubCommands() {
if len(ctx.args) == 0 {
return fmt.Errorf("%s: %w", c.Name, ErrNoSubcommand)
}
next := c.commands[ctx.args[0]]
if next != nil {
ctx.depth++
ctx.args = ctx.args[1:]
return next.execute(ctx)
}
}
// ################
// Process Flags
// ################
fs := flags.NewFlagSet()
fs.AddFlagSet(ctx.persistentFlags())
fs.AddFlagSet(c.FlagSet)
ctx.flagGetter = flags.NewFlagGetter(fs)
var (
argLexer = lexer.New(ctx.args)
args []string
collectArgs bool
)
for {
token := argLexer.Read()
if token == nil {
break
}
switch token.Type {
case lexer.ValueType:
collectArgs = true
args = append(args, token.Value)
case lexer.MultiFlagType:
if collectArgs {
return fmt.Errorf("gommand: invalid flag position: flags must come before args: -%s", token.Name)
}
if token.Value != "" {
return fmt.Errorf("gommand: invalid multi-flag: cannot assign value to multi-flag: -%s", token.Name)
}
for _, chr := range token.Name {
if chr == 'h' {
return errShowHelp
}
f := fs.FromShort(chr)
if f == nil {
return fmt.Errorf("gommand: missing flag: -%s", string(chr))
}
if f.Type() != flags.BoolFlagType {
return fmt.Errorf("gommand: invalid multi-flag: -%s is not a boolean flag", string(chr))
}
_ = f.Set("true")
}
default:
if collectArgs {
prefix := "-"
if token.Type == lexer.LongFlagType {
prefix += "-"
}
return fmt.Errorf("gommand: invalid flag position: flags must come before args: %s%s", prefix, token.Name)
}
var f flags.Flag
switch token.Type {
case lexer.ShortFlagType:
if token.Name == "h" {
return errShowHelp
}
f = fs.FromShort(rune(token.Name[0]))
case lexer.LongFlagType:
if token.Name == "help" {
return errShowHelp
}
if token.Name == "version" {
return errShowVersion
}
f = fs.FromName(token.Name)
}
if f == nil {
prefix := "-"
if token.Type == lexer.LongFlagType {
prefix += "-"
}
return fmt.Errorf("gommand: missing flag: %s%s", prefix, token.Name)
}
var setErr error
if token.Value == "" {
if f.Type() == flags.BoolFlagType {
setErr = f.Set("true")
} else {
if peekToken := argLexer.Peek(); peekToken != nil && peekToken.Type == lexer.ValueType {
setErr = f.Set(argLexer.Read().Value)
}
}
} else {
setErr = f.Set(token.Value)
}
if setErr != nil {
return setErr
}
}
}
// ################
// Validate args
// ################
ctx.args = args
validator := c.ArgValidator
if validator == nil {
// default to allowing no args unless specified otherwise.
validator = ArgsNone()
}
if err := validator(ctx.args); err != nil {
return fmt.Errorf("gommand: invalid args: %w", err)
}
// ################
// Run the things!
// ################
return c.run(ctx)
}
func (c *Command) run(ctx *Context) (runErr error) {
// if there is no Run command, no need to do pre/post run setup things
if c.Run == nil {
return ErrNoRunner
}
for depth, run := range ctx.preRuns {
fs := ctx.persistentFlagSets[depth]
if fs == nil {
continue
}
fg := flags.NewFlagGetter(fs)
for _, f := range fg.All() {
if f.IsRequired() && !f.IsSet() {
if err := flags.SetFromSources(f); err != nil {
return err
}
if !f.IsSet() {
return flags.ErrMissingRequiredFlag{Flag: f}
}
}
}
if err := run(ctx); err != nil {
return err
}
}
if c.FlagSet != nil {
fg := flags.NewFlagGetter(c.FlagSet)
for _, f := range fg.All() {
if f.IsRequired() && !f.IsSet() {
if err := flags.SetFromSources(f); err != nil {
return err
}
if !f.IsSet() {
return flags.ErrMissingRequiredFlag{Flag: f}
}
}
}
}
if c.PreRun != nil {
if err := c.PreRun(ctx); err != nil {
return err
}
}
defer func() {
if runErr != nil && !ctx.deferPost {
return
}
if c.PostRun != nil {
if err := c.PostRun(ctx); err != nil {
c.err = errors.Join(c.err, err)
if !ctx.deferPost {
return
}
}
}
for i := len(ctx.postRuns) - 1; i >= 0; i-- {
if err := ctx.postRuns[i](ctx); err != nil {
c.err = errors.Join(c.err, err)
if !ctx.deferPost {
return
}
}
}
}()
defer func() {
if p := recover(); p != nil {
if !ctx.deferPost {
panic(p)
} else {
runErr = errors.Join(runErr, fmt.Errorf("panic: %v", p))
}
}
}()
runErr = c.Run(ctx)
return runErr
}
type commands map[string]*Command
func (c commands) String() string {
var (
sb strings.Builder
maxKey int
keys = make([]string, 0, len(c))
)
for name, command := range c {
if slices.Contains(command.Aliases, name) {
continue
}
keys = append(keys, name)
if l := len(name); l > maxKey {
maxKey = l
}
}
sort.Strings(keys)
for _, k := range keys {
padding := maxKey - len(k)
_, _ = fmt.Fprintf(&sb, " %s%s %s\n", k, strings.Repeat(" ", padding), c[k].Usage)
}
return sb.String()
}