-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
688 lines (548 loc) · 13.8 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
package cli
import (
"fmt"
"io"
"os"
"sort"
"strings"
"unicode"
"github.com/rdeusser/cli/ast"
"github.com/rdeusser/cli/help"
"github.com/rdeusser/cli/internal/errors"
"github.com/rdeusser/cli/internal/join"
"github.com/rdeusser/cli/internal/multierror"
"github.com/rdeusser/cli/internal/slice"
"github.com/rdeusser/cli/parser"
"github.com/rdeusser/cli/tablewriter"
)
type VisitOption int
const (
VisitStartingAtChild VisitOption = iota
VisitStartingAtParent
VisitStartingAtChildReverse
)
type VisitFunc func(*Command) error
// Command is a command. How else are you supposed to describe this?
// e.g. `go run main.go`
type Command struct {
// Name is the name of the command.
Name string
// Desc is the short description the command.
Desc string
// LongDesc is the long description of the command.
LongDesc string
// Flags is the full set of flags passed to the command.
Flags Flags
// Args is the arguments passed to the command after flags have been
// processed.
Args Args
// parent of the current command.
parent *Command
// commands is a map of command names to the commands command.
commands map[string]*Command
// The order for the below setters and runners is as follows:
// 1. OptionSetter
// 2. PersistentPreRunner
// 3. PreRunner
// 4. Runner
// 5. PostRunner
// 6. PersistentPostRunner
// optionSetter sets options from parent commands.
optionSetter OptionSetter
// persistentPreRunner is inherited and run by all children of this command
// before all other runners.
persistentPreRunner PersistentPreRunner
// preRunner is run before the main runner.
preRunner PreRunner
// runner is the runner for the current command.
runner Runner
// postRunner is run after the main runner.
postRunner PostRunner
// persistentPostRunner is inherited and run by all children of this command
// after all other runners.
persistentPostRunner PersistentPostRunner
// stmt is the parsed statement.
stmt *ast.Statement
// usage is the combined usage of commands, flags, and arguments.
usage string
// output is where help and errors are written to.
output io.Writer
}
// AddCommands adds commands to the current command as children.
func (c *Command) AddCommands(runners ...Runner) {
c.init()
for _, runner := range runners {
cmd := runner.Init()
cmd.setRunners(runner)
cmd.init()
cmd.parent = c
cmd.stmt = c.stmt
cmd.output = c.Output()
c.commands[cmd.Name] = cmd
}
}
// Output returns the io.Writer that the command uses to write output to.
func (c *Command) Output() io.Writer {
if c.output == nil {
return os.Stdout
}
return c.output
}
// SetOutput sets the io.Writer that the command uses to write output to.
func (c *Command) SetOutput(w io.Writer) {
c.output = w
}
// FullName returns the full name of the command starting from the root.
func (c *Command) FullName() string {
commands := make([]string, 0)
c.Visit(func(cmd *Command) error {
commands = append(commands, cmd.Name)
return nil
}, VisitStartingAtParent)
return strings.Join(commands, " ")
}
// HasFlag checks to see if the provided flag is already added to the command.
func (c *Command) HasFlag(name, shorthand string) bool {
seen := make(map[string]struct{})
for _, flag := range c.Flags {
opt := flag.Options()
seen[opt.Name] = struct{}{}
seen[opt.Shorthand] = struct{}{}
}
_, ok := seen[name]
if !ok {
return false
}
if shorthand != "" {
_, ok = seen[shorthand]
if !ok {
return false
}
}
return true
}
// PrintHelp prints the command's help.
func (c *Command) PrintHelp() {
c.Output().Write([]byte(c.usage))
}
// Visit runs fn for each command starting from the top-most parent.
func (c *Command) Visit(fn VisitFunc, option VisitOption) error {
commands := make([]*Command, 0)
commands = append(commands, c)
switch option {
case VisitStartingAtChild:
for _, cmd := range c.commands {
commands = append(commands, cmd)
}
return visit(fn, commands)
default:
parent := c.parent
for parent != nil {
commands = append(commands, parent)
parent = parent.parent
}
switch option {
case VisitStartingAtParent:
// We're starting from the rightmost command, so we have to reverse the
// slice to get the leftmost command in the first index.
for i := len(commands)/2 - 1; i >= 0; i-- {
j := len(commands) - i - 1
commands[i], commands[j] = commands[j], commands[i]
}
case VisitStartingAtChildReverse:
// `commands` is already in correct order for this visit option.
}
return visit(fn, commands)
}
}
// parseCommands is the main method. It adds parent flags (if applicable), sorts
// commands and flags, generates the usage string, parses the args, sets
// options, runs the runners, and checks for unknown and required
// arguments/flags.
func (c *Command) parseCommands(args []string) error {
c.init()
if err := c.addParentFlags(); err != nil {
return err
}
c.sortCommands()
c.sortFlags()
c.generateUsage()
noFlags, err := c.parseFlags(args)
if err != nil {
return c.errOrPrintHelp(err)
}
for _, arg := range noFlags {
if cmd, ok := c.commands[arg]; ok {
return cmd.parseCommands(noFlags)
}
}
noFlagsOrArgs, err := c.parseArgs(noFlags)
if err != nil {
return c.errOrPrintHelp(err)
}
if err := c.checkUnknown(noFlagsOrArgs); err != nil {
return c.errOrPrintHelp(err)
}
if err := c.checkRequired(); err != nil {
return c.errOrPrintHelp(err)
}
if c.optionSetter != nil {
if c.parent == nil {
return ErrMustHaveParent
}
if err := c.optionSetter.SetOptions(c.parent.Flags); err != nil {
return c.errOrPrintHelp(err)
}
}
if err := c.Visit(func(cmd *Command) error {
if cmd.persistentPreRunner != nil {
if err := cmd.persistentPreRunner.PersistentPreRun(); err != nil {
return cmd.errOrPrintHelp(err)
}
}
return nil
}, VisitStartingAtParent); err != nil {
return c.errOrPrintHelp(err)
}
if c.preRunner != nil {
if err := c.preRunner.PreRun(); err != nil {
return c.errOrPrintHelp(err)
}
}
if err := c.runner.Run(); err != nil {
return c.errOrPrintHelp(err)
}
if c.postRunner != nil {
if err := c.postRunner.PostRun(); err != nil {
return c.errOrPrintHelp(err)
}
}
if err := c.Visit(func(cmd *Command) error {
if cmd.persistentPostRunner != nil {
if err := cmd.persistentPostRunner.PersistentPostRun(); err != nil {
return cmd.errOrPrintHelp(err)
}
}
return nil
}, VisitStartingAtChildReverse); err != nil {
return c.errOrPrintHelp(err)
}
return nil
}
// init just makes sure slices and maps are initialized before use.
func (c *Command) init() {
if c.Args == nil {
c.Args = make(Args, 0)
}
if c.Flags == nil {
c.Flags = make(Flags, 0)
}
if c.commands == nil {
c.commands = make(map[string]*Command)
}
if c.output == nil {
c.SetOutput(os.Stdout)
}
}
// addParentFlags adds the flags the parent currently has to this command.
func (c *Command) addParentFlags() error {
var merr multierror.Error
if c.parent == nil {
return nil
}
for _, flag := range c.Flags {
opt := flag.Options()
if c.parent.HasFlag(opt.Name, opt.Shorthand) {
merr.Append(ErrFlagAlreadyDefined{
Name: opt.Name,
Shorthand: opt.Shorthand,
})
}
}
c.Flags = append(c.Flags, c.parent.Flags...)
return merr.ErrorOrNil()
}
// setRunners sets thee
func (c *Command) setRunners(runner Runner) {
if v, ok := runner.(OptionSetter); ok {
c.optionSetter = v
}
if v, ok := runner.(PersistentPreRunner); ok {
c.persistentPreRunner = v
}
if v, ok := runner.(PreRunner); ok {
c.preRunner = v
}
c.runner = runner
if v, ok := runner.(PostRunner); ok {
c.postRunner = v
}
if v, ok := runner.(PersistentPostRunner); ok {
c.persistentPostRunner = v
}
}
func (c *Command) parseFlags(args []string) ([]string, error) {
buf := args
for i, arg := range args {
if matchesFlag(arg, HelpFlag) {
return buf, ErrPrintHelp
}
if !isFlag(arg) {
continue
}
flag := c.Flags.Lookup(arg)
if flag == nil {
continue
}
if err := flag.Init(); err != nil {
return buf, err
}
opt := flag.Options()
switch opt.Value.(type) {
case *bool:
if err := flag.Set("true"); err != nil {
return buf, err
}
buf = slice.Remove(buf, i, i+1)
default:
if opt.IsSlice && opt.Separator == 0 {
return buf, ErrFlagSliceMustHaveSeparator
}
if err := flag.Set(args[i+1]); err != nil {
return buf, err
}
buf = slice.Remove(buf, i, i+1)
}
}
return buf, nil
}
func (c *Command) parseArgs(args []string) ([]string, error) {
buf := make([]string, 0)
for i := range args {
arg := c.Args.Lookup(i)
if arg == nil {
continue
}
if err := arg.Init(); err != nil {
return buf, err
}
buf = slice.Reduce(args[i:], func(a string) bool {
return !isFlag(a)
})
if err := arg.Set(join.Args(buf)); err != nil {
return buf, err
}
}
return buf, nil
}
func (c *Command) checkUnknown(args []string) error {
seen := make(map[string]struct{})
for _, cmd := range c.getCommands() {
seen[cmd.Name] = struct{}{}
}
for _, flag := range c.Flags {
opt := flag.Options()
shorthand := fmt.Sprintf("-%s", opt.Shorthand)
name := fmt.Sprintf("--%s", opt.Name)
if opt.Shorthand != "" {
seen[shorthand] = struct{}{}
}
if opt.Name != "" {
seen[name] = struct{}{}
}
seen[flag.String()] = struct{}{}
}
for _, arg := range c.Args {
seen[arg.String()] = struct{}{}
}
for _, arg := range args {
if _, ok := seen[arg]; !ok {
start, end := c.stmt.Lookup(arg).Pos()
return ErrUnknown{
Input: c.stmt.String(),
Arg: arg,
StartPos: start,
EndPos: end,
}
}
}
return nil
}
func (c *Command) checkRequired() error {
var merr multierror.Error
for _, flag := range c.Flags {
opt := flag.Options()
if opt.Required && (!opt.HasBeenSet || trimBrackets(flag) == "") {
merr.Append(ErrFlagRequired{
Name: opt.Name,
Shorthand: opt.Shorthand,
})
}
}
for _, arg := range c.Args {
opt := arg.Options()
if opt.Required && !opt.HasBeenSet {
merr.Append(ErrArgRequired{
Name: opt.Name,
})
}
}
return merr.ErrorOrNil()
}
// errOrPrintHelp checks if the error returned is ErrPrintHelp. If so, then the
// user intends to print help text to the command's output and not actually
// return an error.
func (c *Command) errOrPrintHelp(err error) error {
if errors.Is(err, ErrPrintHelp) {
c.PrintHelp()
return nil
}
return err
}
func (c *Command) getCommands() []*Command {
commands := make([]*Command, 0, len(c.commands))
for _, cmd := range c.commands {
commands = append(commands, cmd)
}
sort.Sort(SortCommandsByName(commands))
return commands
}
func (c *Command) sortCommands() {
commands := c.getCommands()
m := make(map[string]*Command)
for _, cmd := range commands {
m[cmd.Name] = cmd
}
c.commands = m
}
// sortFlags sorts flags by name.
func (c *Command) sortFlags() {
sort.Sort(SortFlagsByName(c.Flags))
}
// generateUsage generates usage strings for commands, flags, and arguments.
func (c *Command) generateUsage() {
builder := help.NewBuilder()
indent := 4
padding := 4
description := c.LongDesc
if description == "" {
description = formatDesc(c.Desc)
}
builder.Text(description)
builder.Newline()
builder.Newline()
builder.Header("USAGE:")
builder.Newline()
builder.Text(builder.WithIndent(c.FullName(), 4))
if len(c.Flags) > 0 {
builder.Text(" [flags]")
}
for _, arg := range c.Args {
opt := arg.Options()
if opt.IsSlice {
builder.Text(" <%s>...", opt.Name)
} else {
builder.Text(" <%s>", opt.Name)
}
}
if len(c.commands) > 0 {
builder.Text(" [command]")
}
if len(c.commands) > 0 {
commands := tablewriter.NewWriter()
builder.Newline()
builder.Newline()
builder.Header("COMMANDS:")
builder.Newline()
for _, cmd := range c.getCommands() {
commands.AddLine(
tablewriter.Cell{
Indent: indent,
Padding: padding,
Text: builder.Green(cmd.Name),
},
tablewriter.Cell{
Padding: padding,
Text: formatDesc(cmd.Desc),
},
)
}
builder.Table(commands)
}
if len(c.Flags) > 0 {
flags := tablewriter.NewWriter()
builder.Newline()
builder.Newline()
builder.Header("FLAGS:")
builder.Newline()
for _, flag := range c.Flags {
opt := flag.Options()
flags.AddLine(
tablewriter.Cell{
Indent: indent,
Text: builder.Green("-%s", opt.Shorthand),
Suffix: ", ",
},
tablewriter.Cell{
Padding: padding,
Text: builder.Green("--%s", opt.Name),
},
tablewriter.Cell{
Text: formatDesc(opt.Desc),
},
)
}
builder.Table(flags)
}
if len(c.Args) > 0 {
args := tablewriter.NewWriter()
builder.Newline()
builder.Newline()
builder.Header("ARGS:")
builder.Newline()
for _, arg := range c.Args {
opt := arg.Options()
text := builder.Green("<%s>", opt.Name)
if opt.IsSlice {
text += builder.Green("...")
}
args.AddLine(
tablewriter.Cell{
Indent: indent,
Padding: padding,
Text: text,
},
tablewriter.Cell{
Text: formatDesc(opt.Desc),
},
)
}
builder.Table(args)
}
if len(c.commands) > 0 {
builder.Newline()
builder.Newline()
builder.Text("Use \"%s [command] --help\" for more information about a command.", c.FullName())
}
c.usage = builder.String()
}
// SortCommandsByName sorts commands by name.
type SortCommandsByName []*Command
func (n SortCommandsByName) Len() int { return len(n) }
func (n SortCommandsByName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n SortCommandsByName) Less(i, j int) bool {
return strings.Map(unicode.ToUpper, n[i].Name) < strings.Map(unicode.ToUpper, n[j].Name)
}
// Execute parses args and sets up the root command and it's children.
func Execute(runner Runner, args []string) error {
p := parser.New(args)
cmd := runner.Init()
cmd.setRunners(runner)
cmd.init()
cmd.stmt = p.Parse()
cmd.output = os.Stdout
if !cmd.HasFlag(HelpFlag.Name, HelpFlag.Shorthand) {
cmd.Flags = append(cmd.Flags, HelpFlag)
}
return cmd.parseCommands(args[1:])
}