forked from urfave/cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
command.go
1299 lines (1086 loc) · 33.6 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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cli
import (
"bufio"
"context"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"unicode"
)
const (
// ignoreFlagPrefix is to ignore test flags when adding flags from other packages
ignoreFlagPrefix = "test."
commandContextKey = contextKey("cli.context")
)
type contextKey string
// Command contains everything needed to run an application that
// accepts a string slice of arguments such as os.Args. A given
// Command may contain Flags and sub-commands in Commands.
type Command struct {
// The name of the command
Name string `json:"name"`
// A list of aliases for the command
Aliases []string `json:"aliases"`
// A short description of the usage of this command
Usage string `json:"usage"`
// Text to override the USAGE section of help
UsageText string `json:"usageText"`
// A short description of the arguments of this command
ArgsUsage string `json:"argsUsage"`
// Version of the command
Version string `json:"version"`
// Longer explanation of how the command works
Description string `json:"description"`
// DefaultCommand is the (optional) name of a command
// to run if no command names are passed as CLI arguments.
DefaultCommand string `json:"defaultCommand"`
// The category the command is part of
Category string `json:"category"`
// List of child commands
Commands []*Command `json:"commands"`
// List of flags to parse
Flags []Flag `json:"flags"`
// Boolean to hide built-in help command and help flag
HideHelp bool `json:"hideHelp"`
// Ignored if HideHelp is true.
HideHelpCommand bool `json:"hideHelpCommand"`
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool `json:"hideVersion"`
// Boolean to enable shell completion commands
EnableShellCompletion bool `json:"-"`
// Shell Completion generation command name
ShellCompletionCommandName string `json:"-"`
// The function to call when checking for shell command completions
ShellComplete ShellCompleteFunc `json:"-"`
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
Before BeforeFunc `json:"-"`
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc `json:"-"`
// The function to call when this command is invoked
Action ActionFunc `json:"-"`
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc `json:"-"`
// Execute this function if a usage error occurs.
OnUsageError OnUsageErrorFunc `json:"-"`
// Execute this function when an invalid flag is accessed from the context
InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`
// Boolean to hide this command from help or completion
Hidden bool `json:"hidden"`
// List of all authors who contributed (string or fmt.Stringer)
// TODO: ~string | fmt.Stringer when interface unions are available
Authors []any `json:"authors"`
// Copyright of the binary if any
Copyright string `json:"copyright"`
// Reader reader to write input to (useful for tests)
Reader io.Reader `json:"-"`
// Writer writer to write output to
Writer io.Writer `json:"-"`
// ErrWriter writes error output
ErrWriter io.Writer `json:"-"`
// ExitErrHandler processes any error encountered while running an App before
// it is returned to the caller. If no function is provided, HandleExitCoder
// is used as the default behavior.
ExitErrHandler ExitErrHandlerFunc `json:"-"`
// Other custom info
Metadata map[string]interface{} `json:"metadata"`
// Carries a function which returns app specific info.
ExtraInfo func() map[string]string `json:"-"`
// CustomRootCommandHelpTemplate the text template for app help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomRootCommandHelpTemplate string `json:"-"`
// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
SliceFlagSeparator string `json:"sliceFlagSeparator"`
// DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`
// Boolean to enable short-option handling so user can combine several
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool `json:"useShortOptionHandling"`
// Enable suggestions for commands and flags
Suggest bool `json:"suggest"`
// Allows global flags set by libraries which use flag.XXXVar(...) directly
// to be parsed through this library
AllowExtFlags bool `json:"allowExtFlags"`
// Treat all flags as normal arguments if true
SkipFlagParsing bool `json:"skipFlagParsing"`
// CustomHelpTemplate the text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomHelpTemplate string `json:"-"`
// Use longest prefix match for commands
PrefixMatchCommands bool `json:"prefixMatchCommands"`
// Custom suggest command for matching
SuggestCommandFunc SuggestCommandFunc `json:"-"`
// Flag exclusion group
MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`
// Arguments to parse for this command
Arguments []Argument `json:"arguments"`
// Whether to read arguments from stdin
// applicable to root command only
ReadArgsFromStdin bool `json:"readArgsFromStdin"`
// categories contains the categorized commands and is populated on app startup
categories CommandCategories
// flagCategories contains the categorized flags and is populated on app startup
flagCategories FlagCategories
// flags that have been applied in current parse
appliedFlags []Flag
// The parent of this command. This value will be nil for the
// command at the root of the graph.
parent *Command
// the flag.FlagSet for this command
flagSet *flag.FlagSet
// parsed args
parsedArgs Args
// track state of error handling
isInError bool
// track state of defaults
didSetupDefaults bool
// whether in shell completion mode
shellCompletion bool
}
// FullName returns the full name of the command.
// For commands with parents this ensures that the parent commands
// are part of the command path.
func (cmd *Command) FullName() string {
namePath := []string{}
if cmd.parent != nil {
namePath = append(namePath, cmd.parent.FullName())
}
return strings.Join(append(namePath, cmd.Name), " ")
}
func (cmd *Command) Command(name string) *Command {
for _, subCmd := range cmd.Commands {
if subCmd.HasName(name) {
return subCmd
}
}
return nil
}
func (cmd *Command) setupDefaults(osArgs []string) {
if cmd.didSetupDefaults {
tracef("already did setup (cmd=%[1]q)", cmd.Name)
return
}
cmd.didSetupDefaults = true
isRoot := cmd.parent == nil
tracef("isRoot? %[1]v (cmd=%[2]q)", isRoot, cmd.Name)
if cmd.ShellComplete == nil {
tracef("setting default ShellComplete (cmd=%[1]q)", cmd.Name)
cmd.ShellComplete = DefaultCompleteWithFlags
}
if cmd.Name == "" && isRoot {
name := filepath.Base(osArgs[0])
tracef("setting cmd.Name from first arg basename (cmd=%[1]q)", name)
cmd.Name = name
}
if cmd.Usage == "" && isRoot {
tracef("setting default Usage (cmd=%[1]q)", cmd.Name)
cmd.Usage = "A new cli application"
}
if cmd.Version == "" {
tracef("setting HideVersion=true due to empty Version (cmd=%[1]q)", cmd.Name)
cmd.HideVersion = true
}
if cmd.Action == nil {
tracef("setting default Action as help command action (cmd=%[1]q)", cmd.Name)
cmd.Action = helpCommandAction
}
if cmd.Reader == nil {
tracef("setting default Reader as os.Stdin (cmd=%[1]q)", cmd.Name)
cmd.Reader = os.Stdin
}
if cmd.Writer == nil {
tracef("setting default Writer as os.Stdout (cmd=%[1]q)", cmd.Name)
cmd.Writer = os.Stdout
}
if cmd.ErrWriter == nil {
tracef("setting default ErrWriter as os.Stderr (cmd=%[1]q)", cmd.Name)
cmd.ErrWriter = os.Stderr
}
if cmd.AllowExtFlags {
tracef("visiting all flags given AllowExtFlags=true (cmd=%[1]q)", cmd.Name)
// add global flags added by other packages
flag.VisitAll(func(f *flag.Flag) {
// skip test flags
if !strings.HasPrefix(f.Name, ignoreFlagPrefix) {
cmd.Flags = append(cmd.Flags, &extFlag{f})
}
})
}
for _, subCmd := range cmd.Commands {
tracef("setting sub-command (cmd=%[1]q) parent as self (cmd=%[2]q)", subCmd.Name, cmd.Name)
subCmd.parent = cmd
}
cmd.ensureHelp()
if !cmd.HideVersion && isRoot {
tracef("appending version flag (cmd=%[1]q)", cmd.Name)
cmd.appendFlag(VersionFlag)
}
if cmd.PrefixMatchCommands && cmd.SuggestCommandFunc == nil {
tracef("setting default SuggestCommandFunc (cmd=%[1]q)", cmd.Name)
cmd.SuggestCommandFunc = suggestCommand
}
if cmd.EnableShellCompletion || cmd.Root().shellCompletion {
completionCommand := buildCompletionCommand()
if cmd.ShellCompletionCommandName != "" {
tracef(
"setting completion command name (%[1]q) from "+
"cmd.ShellCompletionCommandName (cmd=%[2]q)",
cmd.ShellCompletionCommandName, cmd.Name,
)
completionCommand.Name = cmd.ShellCompletionCommandName
}
tracef("appending completionCommand (cmd=%[1]q)", cmd.Name)
cmd.appendCommand(completionCommand)
}
tracef("setting command categories (cmd=%[1]q)", cmd.Name)
cmd.categories = newCommandCategories()
for _, subCmd := range cmd.Commands {
cmd.categories.AddCommand(subCmd.Category, subCmd)
}
tracef("sorting command categories (cmd=%[1]q)", cmd.Name)
sort.Sort(cmd.categories.(*commandCategories))
tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name)
for _, grp := range cmd.MutuallyExclusiveFlags {
grp.propagateCategory()
}
tracef("setting flag categories (cmd=%[1]q)", cmd.Name)
cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags())
if cmd.Metadata == nil {
tracef("setting default Metadata (cmd=%[1]q)", cmd.Name)
cmd.Metadata = map[string]any{}
}
if len(cmd.SliceFlagSeparator) != 0 {
tracef("setting defaultSliceFlagSeparator from cmd.SliceFlagSeparator (cmd=%[1]q)", cmd.Name)
defaultSliceFlagSeparator = cmd.SliceFlagSeparator
}
tracef("setting disableSliceFlagSeparator from cmd.DisableSliceFlagSeparator (cmd=%[1]q)", cmd.Name)
disableSliceFlagSeparator = cmd.DisableSliceFlagSeparator
}
func (cmd *Command) setupCommandGraph() {
tracef("setting up command graph (cmd=%[1]q)", cmd.Name)
for _, subCmd := range cmd.Commands {
subCmd.parent = cmd
subCmd.setupSubcommand()
subCmd.setupCommandGraph()
}
}
func (cmd *Command) setupSubcommand() {
tracef("setting up self as sub-command (cmd=%[1]q)", cmd.Name)
cmd.ensureHelp()
tracef("setting command categories (cmd=%[1]q)", cmd.Name)
cmd.categories = newCommandCategories()
for _, subCmd := range cmd.Commands {
cmd.categories.AddCommand(subCmd.Category, subCmd)
}
tracef("sorting command categories (cmd=%[1]q)", cmd.Name)
sort.Sort(cmd.categories.(*commandCategories))
tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name)
for _, grp := range cmd.MutuallyExclusiveFlags {
grp.propagateCategory()
}
tracef("setting flag categories (cmd=%[1]q)", cmd.Name)
cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags())
}
func (cmd *Command) hideHelp() bool {
tracef("hide help (cmd=%[1]q)", cmd.Name)
for c := cmd; c != nil; c = c.parent {
if c.HideHelp {
return true
}
}
return false
}
func (cmd *Command) ensureHelp() {
tracef("ensuring help (cmd=%[1]q)", cmd.Name)
helpCommand := buildHelpCommand(true)
if !cmd.hideHelp() {
if cmd.Command(helpCommand.Name) == nil {
if !cmd.HideHelpCommand {
tracef("appending helpCommand (cmd=%[1]q)", cmd.Name)
cmd.appendCommand(helpCommand)
}
}
if HelpFlag != nil {
tracef("appending HelpFlag (cmd=%[1]q)", cmd.Name)
cmd.appendFlag(HelpFlag)
}
}
}
func (cmd *Command) parseArgsFromStdin() ([]string, error) {
type state int
const (
stateSearchForToken state = -1
stateSearchForString state = 0
)
st := stateSearchForToken
linenum := 1
token := ""
args := []string{}
breader := bufio.NewReader(cmd.Reader)
outer:
for {
ch, _, err := breader.ReadRune()
if err == io.EOF {
switch st {
case stateSearchForToken:
if token != "--" {
args = append(args, token)
}
case stateSearchForString:
// make sure string is not empty
for _, t := range token {
if !unicode.IsSpace(t) {
args = append(args, token)
}
}
}
break outer
}
if err != nil {
return nil, err
}
switch st {
case stateSearchForToken:
if unicode.IsSpace(ch) || ch == '"' {
if ch == '\n' {
linenum++
}
if token != "" {
// end the processing here
if token == "--" {
break outer
}
args = append(args, token)
token = ""
}
if ch == '"' {
st = stateSearchForString
}
continue
}
token += string(ch)
case stateSearchForString:
if ch != '"' {
token += string(ch)
} else {
if token != "" {
args = append(args, token)
token = ""
}
/*else {
//TODO. Should we pass in empty strings ?
}*/
st = stateSearchForToken
}
}
}
tracef("parsed stdin args as %v (cmd=%[2]q)", args, cmd.Name)
return args, nil
}
// Run is the entry point to the command graph. The positional
// arguments are parsed according to the Flag and Command
// definitions and the matching Action functions are run.
func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) {
tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name)
cmd.setupDefaults(osArgs)
if v, ok := ctx.Value(commandContextKey).(*Command); ok {
tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name)
cmd.parent = v
}
if cmd.parent == nil {
if cmd.ReadArgsFromStdin {
if args, err := cmd.parseArgsFromStdin(); err != nil {
return err
} else {
osArgs = append(osArgs, args...)
}
}
// handle the completion flag separately from the flagset since
// completion could be attempted after a flag, but before its value was put
// on the command line. this causes the flagset to interpret the completion
// flag name as the value of the flag before it which is undesirable
// note that we can only do this because the shell autocomplete function
// always appends the completion flag at the end of the command
tracef("checking osArgs %v (cmd=%[2]q)", osArgs, cmd.Name)
cmd.shellCompletion, osArgs = checkShellCompleteFlag(cmd, osArgs)
tracef("setting cmd.shellCompletion=%[1]v from checkShellCompleteFlag (cmd=%[2]q)", cmd.shellCompletion && cmd.EnableShellCompletion, cmd.Name)
cmd.shellCompletion = cmd.EnableShellCompletion && cmd.shellCompletion
}
tracef("using post-checkShellCompleteFlag arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name)
tracef("setting self as cmd in context (cmd=%[1]q)", cmd.Name)
ctx = context.WithValue(ctx, commandContextKey, cmd)
if cmd.parent == nil {
cmd.setupCommandGraph()
}
args, err := cmd.parseFlags(&stringSliceArgs{v: osArgs})
tracef("using post-parse arguments %[1]q (cmd=%[2]q)", args, cmd.Name)
if checkCompletions(ctx, cmd) {
return nil
}
if err != nil {
tracef("setting deferErr from %[1]q (cmd=%[2]q)", err, cmd.Name)
deferErr = err
cmd.isInError = true
if cmd.OnUsageError != nil {
err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil)
err = cmd.handleExitCoder(ctx, err)
return err
}
fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error())
if cmd.Suggest {
if suggestion, err := cmd.suggestFlagFromError(err, ""); err == nil {
fmt.Fprintf(cmd.Root().ErrWriter, "%s", suggestion)
}
}
if !cmd.hideHelp() {
if cmd.parent == nil {
tracef("running ShowAppHelp")
if err := ShowAppHelp(cmd); err != nil {
tracef("SILENTLY IGNORING ERROR running ShowAppHelp %[1]v (cmd=%[2]q)", err, cmd.Name)
}
} else {
tracef("running ShowCommandHelp with %[1]q", cmd.Name)
if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil {
tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err)
}
}
}
return err
}
if cmd.checkHelp() {
return helpCommandAction(ctx, cmd)
} else {
tracef("no help is wanted (cmd=%[1]q)", cmd.Name)
}
if cmd.parent == nil && !cmd.HideVersion && checkVersion(cmd) {
ShowVersion(cmd)
return nil
}
if cmd.After != nil && !cmd.Root().shellCompletion {
defer func() {
if err := cmd.After(ctx, cmd); err != nil {
err = cmd.handleExitCoder(ctx, err)
if deferErr != nil {
deferErr = newMultiError(deferErr, err)
} else {
deferErr = err
}
}
}()
}
for _, grp := range cmd.MutuallyExclusiveFlags {
if err := grp.check(cmd); err != nil {
_ = ShowSubcommandHelp(cmd)
return err
}
}
if cmd.Before != nil && !cmd.Root().shellCompletion {
if bctx, err := cmd.Before(ctx, cmd); err != nil {
deferErr = cmd.handleExitCoder(ctx, err)
return deferErr
} else if bctx != nil {
ctx = bctx
}
}
tracef("running flag actions (cmd=%[1]q)", cmd.Name)
if err := cmd.runFlagActions(ctx); err != nil {
return err
}
var subCmd *Command
if args.Present() {
tracef("checking positional args %[1]q (cmd=%[2]q)", args, cmd.Name)
name := args.First()
tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name)
if cmd.SuggestCommandFunc != nil {
name = cmd.SuggestCommandFunc(cmd.Commands, name)
}
subCmd = cmd.Command(name)
if subCmd == nil {
hasDefault := cmd.DefaultCommand != ""
isFlagName := checkStringSliceIncludes(name, cmd.FlagNames())
if hasDefault {
tracef("using default command=%[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name)
}
if isFlagName || hasDefault {
argsWithDefault := cmd.argsWithDefaultCommand(args)
tracef("using default command args=%[1]q (cmd=%[2]q)", argsWithDefault, cmd.Name)
if !reflect.DeepEqual(args, argsWithDefault) {
subCmd = cmd.Command(argsWithDefault.First())
}
}
}
} else if cmd.parent == nil && cmd.DefaultCommand != "" {
tracef("no positional args present; checking default command %[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name)
if dc := cmd.Command(cmd.DefaultCommand); dc != cmd {
subCmd = dc
}
}
if subCmd != nil {
tracef("running sub-command %[1]q with arguments %[2]q (cmd=%[3]q)", subCmd.Name, cmd.Args(), cmd.Name)
return subCmd.Run(ctx, cmd.Args().Slice())
}
if cmd.Action == nil {
cmd.Action = helpCommandAction
} else {
if err := cmd.checkAllRequiredFlags(); err != nil {
cmd.isInError = true
_ = ShowSubcommandHelp(cmd)
return err
}
if len(cmd.Arguments) > 0 {
rargs := cmd.Args().Slice()
tracef("calling argparse with %[1]v", rargs)
for _, arg := range cmd.Arguments {
var err error
rargs, err = arg.Parse(rargs)
if err != nil {
tracef("calling with %[1]v (cmd=%[2]q)", err, cmd.Name)
return err
}
}
cmd.parsedArgs = &stringSliceArgs{v: rargs}
}
}
if err := cmd.Action(ctx, cmd); err != nil {
tracef("calling handleExitCoder with %[1]v (cmd=%[2]q)", err, cmd.Name)
deferErr = cmd.handleExitCoder(ctx, err)
}
tracef("returning deferErr (cmd=%[1]q) %[2]q", cmd.Name, deferErr)
return deferErr
}
func (cmd *Command) checkHelp() bool {
tracef("checking if help is wanted (cmd=%[1]q)", cmd.Name)
if HelpFlag == nil {
return false
}
for _, name := range HelpFlag.Names() {
if cmd.Bool(name) {
return true
}
}
return false
}
func (cmd *Command) newFlagSet() (*flag.FlagSet, error) {
allFlags := cmd.allFlags()
cmd.appliedFlags = append(cmd.appliedFlags, allFlags...)
tracef("making new flag set (cmd=%[1]q)", cmd.Name)
return newFlagSet(cmd.Name, allFlags)
}
func (cmd *Command) allFlags() []Flag {
var flags []Flag
flags = append(flags, cmd.Flags...)
for _, grpf := range cmd.MutuallyExclusiveFlags {
for _, f1 := range grpf.Flags {
flags = append(flags, f1...)
}
}
return flags
}
// useShortOptionHandling traverses Lineage() for *any* ancestors
// with UseShortOptionHandling
func (cmd *Command) useShortOptionHandling() bool {
for _, pCmd := range cmd.Lineage() {
if pCmd.UseShortOptionHandling {
return true
}
}
return false
}
func (cmd *Command) suggestFlagFromError(err error, commandName string) (string, error) {
fl, parseErr := flagFromError(err)
if parseErr != nil {
return "", err
}
flags := cmd.Flags
hideHelp := cmd.hideHelp()
if commandName != "" {
subCmd := cmd.Command(commandName)
if subCmd == nil {
return "", err
}
flags = subCmd.Flags
hideHelp = hideHelp || subCmd.HideHelp
}
suggestion := SuggestFlag(flags, fl, hideHelp)
if len(suggestion) == 0 {
return "", err
}
return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil
}
func (cmd *Command) parseFlags(args Args) (Args, error) {
tracef("parsing flags from arguments %[1]q (cmd=%[2]q)", args, cmd.Name)
cmd.parsedArgs = nil
if v, err := cmd.newFlagSet(); err != nil {
return args, err
} else {
cmd.flagSet = v
}
if cmd.SkipFlagParsing {
tracef("skipping flag parsing (cmd=%[1]q)", cmd.Name)
return cmd.Args(), cmd.flagSet.Parse(append([]string{"--"}, args.Tail()...))
}
tracef("walking command lineage for persistent flags (cmd=%[1]q)", cmd.Name)
for pCmd := cmd.parent; pCmd != nil; pCmd = pCmd.parent {
tracef(
"checking ancestor command=%[1]q for persistent flags (cmd=%[2]q)",
pCmd.Name, cmd.Name,
)
for _, fl := range pCmd.Flags {
flNames := fl.Names()
pfl, ok := fl.(LocalFlag)
if !ok || pfl.IsLocal() {
tracef("skipping non-persistent flag %[1]q (cmd=%[2]q)", flNames, cmd.Name)
continue
}
tracef(
"checking for applying persistent flag=%[1]q pCmd=%[2]q (cmd=%[3]q)",
flNames, pCmd.Name, cmd.Name,
)
applyPersistentFlag := true
cmd.flagSet.VisitAll(func(f *flag.Flag) {
for _, name := range flNames {
if name == f.Name {
applyPersistentFlag = false
break
}
}
})
if !applyPersistentFlag {
tracef("not applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name)
continue
}
tracef("applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name)
if err := fl.Apply(cmd.flagSet); err != nil {
return cmd.Args(), err
}
tracef("appending to applied flags flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name)
cmd.appliedFlags = append(cmd.appliedFlags, fl)
}
}
tracef("parsing flags iteratively tail=%[1]q (cmd=%[2]q)", args.Tail(), cmd.Name)
defer tracef("done parsing flags (cmd=%[1]q)", cmd.Name)
rargs := args.Tail()
posArgs := []string{}
for {
tracef("rearrange:1 (cmd=%[1]q) %[2]q", cmd.Name, rargs)
for {
tracef("rearrange:2 (cmd=%[1]q) %[2]q %[3]q", cmd.Name, posArgs, rargs)
// no more args to parse. Break out of inner loop
if len(rargs) == 0 {
break
}
if strings.TrimSpace(rargs[0]) == "" {
break
}
// stop parsing once we see a "--"
if rargs[0] == "--" {
posArgs = append(posArgs, rargs...)
cmd.parsedArgs = &stringSliceArgs{posArgs}
return cmd.parsedArgs, nil
}
// let flagset parse this
if rargs[0][0] == '-' {
break
}
tracef("rearrange-3 (cmd=%[1]q) check %[2]q", cmd.Name, rargs[0])
// if there is a command by that name let the command handle the
// rest of the parsing
if cmd.Command(rargs[0]) != nil {
posArgs = append(posArgs, rargs...)
cmd.parsedArgs = &stringSliceArgs{posArgs}
return cmd.parsedArgs, nil
}
posArgs = append(posArgs, rargs[0])
// if this is the sole argument then
// break from inner loop
if len(rargs) == 1 {
rargs = []string{}
break
}
rargs = rargs[1:]
}
if err := parseIter(cmd.flagSet, cmd, rargs, cmd.Root().shellCompletion); err != nil {
posArgs = append(posArgs, cmd.flagSet.Args()...)
tracef("returning-1 (cmd=%[1]q) args %[2]q", cmd.Name, posArgs)
cmd.parsedArgs = &stringSliceArgs{posArgs}
return cmd.parsedArgs, err
}
tracef("rearrange-4 (cmd=%[1]q) check %[2]q", cmd.Name, cmd.flagSet.Args())
rargs = cmd.flagSet.Args()
if len(rargs) == 0 || strings.TrimSpace(rargs[0]) == "" || rargs[0] == "-" {
break
}
}
posArgs = append(posArgs, cmd.flagSet.Args()...)
tracef("returning-2 (cmd=%[1]q) args %[2]q", cmd.Name, posArgs)
cmd.parsedArgs = &stringSliceArgs{posArgs}
return cmd.parsedArgs, nil
}
// Names returns the names including short names and aliases.
func (cmd *Command) Names() []string {
return append([]string{cmd.Name}, cmd.Aliases...)
}
// HasName returns true if Command.Name matches given name
func (cmd *Command) HasName(name string) bool {
for _, n := range cmd.Names() {
if n == name {
return true
}
}
return false
}
// VisibleCategories returns a slice of categories and commands that are
// Hidden=false
func (cmd *Command) VisibleCategories() []CommandCategory {
ret := []CommandCategory{}
for _, category := range cmd.categories.Categories() {
if visible := func() CommandCategory {
if len(category.VisibleCommands()) > 0 {
return category
}
return nil
}(); visible != nil {
ret = append(ret, visible)
}
}
return ret
}
// VisibleCommands returns a slice of the Commands with Hidden=false
func (cmd *Command) VisibleCommands() []*Command {
var ret []*Command
for _, command := range cmd.Commands {
if command.Hidden || command.Name == helpName {
continue
}
ret = append(ret, command)
}
return ret
}
// VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain
func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory {
if cmd.flagCategories == nil {
cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags())
}
return cmd.flagCategories.VisibleCategories()
}
// VisibleFlags returns a slice of the Flags with Hidden=false
func (cmd *Command) VisibleFlags() []Flag {
return visibleFlags(cmd.allFlags())
}
func (cmd *Command) appendFlag(fl Flag) {
if !hasFlag(cmd.Flags, fl) {
cmd.Flags = append(cmd.Flags, fl)
}
}
// VisiblePersistentFlags returns a slice of [LocalFlag] with Persistent=true and Hidden=false.
func (cmd *Command) VisiblePersistentFlags() []Flag {
var flags []Flag
for _, fl := range cmd.Root().Flags {
pfl, ok := fl.(LocalFlag)
if !ok || pfl.IsLocal() {
continue
}
flags = append(flags, fl)
}
return visibleFlags(flags)
}
func (cmd *Command) appendCommand(aCmd *Command) {
if !hasCommand(cmd.Commands, aCmd) {
aCmd.parent = cmd
cmd.Commands = append(cmd.Commands, aCmd)
}
}
func (cmd *Command) handleExitCoder(ctx context.Context, err error) error {
if cmd.parent != nil {
return cmd.parent.handleExitCoder(ctx, err)
}
if cmd.ExitErrHandler != nil {
cmd.ExitErrHandler(ctx, cmd, err)
return err
}
HandleExitCoder(err)
return err
}
func (cmd *Command) argsWithDefaultCommand(oldArgs Args) Args {
if cmd.DefaultCommand != "" {
rawArgs := append([]string{cmd.DefaultCommand}, oldArgs.Slice()...)
newArgs := &stringSliceArgs{v: rawArgs}
return newArgs
}
return oldArgs
}
// Root returns the Command at the root of the graph
func (cmd *Command) Root() *Command {
if cmd.parent == nil {
return cmd
}
return cmd.parent.Root()
}
func (cmd *Command) lookupFlag(name string) Flag {
for _, pCmd := range cmd.Lineage() {
for _, f := range pCmd.Flags {
for _, n := range f.Names() {
if n == name {
tracef("flag found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
return f
}
}
}
}
tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
return nil
}
func (cmd *Command) lookupFlagSet(name string) *flag.FlagSet {