Debian Codegraph @

command.go

raw symbols SCIP
1 package cli
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "slices"
8 "strings"
9 )
10
11 const (
12 // ignoreFlagPrefix is to ignore test flags when adding flags from other packages
13 ignoreFlagPrefix = "test."
14
15 commandContextKey = contextKey("cli.context")
16 )
17
18 type contextKey string
19
20 // Command contains everything needed to run an application that
21 // accepts a string slice of arguments such as os.Args. A given
22 // Command may contain Flags and sub-commands in Commands.
23 type Command struct {
24 // The name of the command
25 Name string `json:"name"`
26 // A list of aliases for the command
27 Aliases []string `json:"aliases"`
28 // A short description of the usage of this command
29 Usage string `json:"usage"`
30 // Text to override the USAGE section of help
31 UsageText string `json:"usageText"`
32 // A short description of the arguments of this command
33 ArgsUsage string `json:"argsUsage"`
34 // Version of the command
35 Version string `json:"version"`
36 // Longer explanation of how the command works
37 Description string `json:"description"`
38 // DefaultCommand is the (optional) name of a command
39 // to run if no command names are passed as CLI arguments.
40 DefaultCommand string `json:"defaultCommand"`
41 // The category the command is part of
42 Category string `json:"category"`
43 // List of child commands
44 Commands []*Command `json:"commands"`
45 // List of flags to parse
46 Flags []Flag `json:"flags"`
47 // Boolean to hide built-in help command and help flag
48 HideHelp bool `json:"hideHelp"`
49 // Ignored if HideHelp is true.
50 HideHelpCommand bool `json:"hideHelpCommand"`
51 // Boolean to hide built-in version flag and the VERSION section of help
52 HideVersion bool `json:"hideVersion"`
53 // Boolean to enable shell completion commands
54 EnableShellCompletion bool `json:"-"`
55 // Shell Completion generation command name
56 ShellCompletionCommandName string `json:"-"`
57 // The function to call when checking for shell command completions
58 ShellComplete ShellCompleteFunc `json:"-"`
59 // The function to configure a shell completion command
60 ConfigureShellCompletionCommand ConfigureShellCompletionCommand `json:"-"`
61 // An action to execute before any subcommands are run, but after the context is ready
62 // If a non-nil error is returned, no subcommands are run
63 Before BeforeFunc `json:"-"`
64 // An action to execute after any subcommands are run, but after the subcommand has finished
65 // It is run even if Action() panics
66 After AfterFunc `json:"-"`
67 // The function to call when this command is invoked
68 Action ActionFunc `json:"-"`
69 // Execute this function if the proper command cannot be found
70 CommandNotFound CommandNotFoundFunc `json:"-"`
71 // Execute this function if a usage error occurs.
72 OnUsageError OnUsageErrorFunc `json:"-"`
73 // Execute this function when an invalid flag is accessed from the context
74 InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"`
75 // Boolean to hide this command from help or completion
76 Hidden bool `json:"hidden"`
77 // List of all authors who contributed (string or fmt.Stringer)
78 // TODO: ~string | fmt.Stringer when interface unions are available
79 Authors []any `json:"authors"`
80 // Copyright of the binary if any
81 Copyright string `json:"copyright"`
82 // Reader reader to write input to (useful for tests)
83 Reader io.Reader `json:"-"`
84 // Writer writer to write output to
85 Writer io.Writer `json:"-"`
86 // ErrWriter writes error output
87 ErrWriter io.Writer `json:"-"`
88 // ExitErrHandler processes any error encountered while running a Command before it is
89 // returned to the caller. If no function is provided, HandleExitCoder is used as the
90 // default behavior.
91 ExitErrHandler ExitErrHandlerFunc `json:"-"`
92 // Other custom info
93 Metadata map[string]any `json:"metadata"`
94 // Carries a function which returns app specific info.
95 ExtraInfo func() map[string]string `json:"-"`
96 // CustomRootCommandHelpTemplate the text template for app help topic.
97 // cli.go uses text/template to render templates. You can
98 // render custom help text by setting this variable.
99 CustomRootCommandHelpTemplate string `json:"-"`
100 // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
101 SliceFlagSeparator string `json:"sliceFlagSeparator"`
102 // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false
103 DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"`
104 // MapFlagKeyValueSeparator is used to customize the separator for MapFlag, the default is "="
105 MapFlagKeyValueSeparator string `json:"mapFlagKeyValueSeparator"`
106 // Boolean to enable short-option handling so user can combine several
107 // single-character bool arguments into one
108 // i.e. foobar -o -v -> foobar -ov
109 UseShortOptionHandling bool `json:"useShortOptionHandling"`
110 // Enable suggestions for commands and flags
111 Suggest bool `json:"suggest"`
112 // Allows global flags set by libraries which use flag.XXXVar(...) directly
113 // to be parsed through this library
114 AllowExtFlags bool `json:"allowExtFlags"`
115 // Treat all flags as normal arguments if true
116 SkipFlagParsing bool `json:"skipFlagParsing"`
117 // CustomHelpTemplate the text template for the command help topic.
118 // cli.go uses text/template to render templates. You can
119 // render custom help text by setting this variable.
120 CustomHelpTemplate string `json:"-"`
121 // Use longest prefix match for commands
122 PrefixMatchCommands bool `json:"prefixMatchCommands"`
123 // Custom suggest command for matching
124 SuggestCommandFunc SuggestCommandFunc `json:"-"`
125 // Flag exclusion group
126 MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"`
127 // Arguments to parse for this command
128 Arguments []Argument `json:"arguments"`
129 // Whether to read arguments from stdin
130 // applicable to root command only
131 ReadArgsFromStdin bool `json:"readArgsFromStdin"`
132 // StopOnNthArg provides v2-like behavior for specific commands by stopping
133 // flag parsing after N positional arguments are encountered. When set to N,
134 // all remaining arguments after the Nth positional argument will be treated
135 // as arguments, not flags.
136 //
137 // A value of 0 means all arguments are treated as positional (no flag parsing).
138 // A nil value means normal v3 flag parsing behavior (flags can appear anywhere).
139 StopOnNthArg *int `json:"stopOnNthArg"`
140
141 // categories contains the categorized commands and is populated on app startup
142 categories CommandCategories
143 // flagCategories contains the categorized flags and is populated on app startup
144 flagCategories FlagCategories
145 // flags that have been applied in current parse
146 appliedFlags []Flag
147 // flags that have been set
148 setFlags map[Flag]struct{}
149 // The parent of this command. This value will be nil for the
150 // command at the root of the graph.
151 parent *Command
152 // parsed args
153 parsedArgs Args
154 // track state of error handling
155 isInError bool
156 // track state of defaults
157 didSetupDefaults bool
158 // whether in shell completion mode
159 shellCompletion bool
160 // whether global help flag was added
161 globaHelpFlagAdded bool
162 // whether global version flag was added
163 globaVersionFlagAdded bool
164 // generated root version flag
165 versionFlag Flag
166 // whether this is a completion command
167 isCompletionCommand bool
168 // whether this is the built-in help command
169 builtInHelp bool
170 }
171
172 func (cmd *Command) Command(name string) *Command {
173 for _, subCmd := range cmd.Commands {
174 if subCmd.HasName(name) {
175 return subCmd
176 }
177 }
178
179 return nil
180 }
181
182 func (cmd *Command) checkHelp() bool {
183 tracef("checking if help is wanted (cmd=%[1]q)", cmd.Name)
184
185 return HelpFlag != nil && slices.ContainsFunc(HelpFlag.Names(), cmd.Bool)
186 }
187
188 func (cmd *Command) allFlags() []Flag {
189 var flags []Flag
190 flags = append(flags, cmd.Flags...)
191 for _, grpf := range cmd.MutuallyExclusiveFlags {
192 for _, f1 := range grpf.Flags {
193 flags = append(flags, f1...)
194 }
195 }
196 return flags
197 }
198
199 // useShortOptionHandling traverses Lineage() for *any* ancestors
200 // with UseShortOptionHandling
201 func (cmd *Command) useShortOptionHandling() bool {
202 for _, pCmd := range cmd.Lineage() {
203 if pCmd.UseShortOptionHandling {
204 return true
205 }
206 }
207
208 return false
209 }
210
211 func (cmd *Command) suggestFlagFromError(err error, commandName string) (string, error) {
212 fl, parseErr := flagFromError(err)
213 if parseErr != nil {
214 return "", err
215 }
216
217 flags := cmd.Flags
218 hideHelp := cmd.hideHelp()
219
220 if commandName != "" {
221 subCmd := cmd.Command(commandName)
222 if subCmd == nil {
223 return "", err
224 }
225 flags = subCmd.Flags
226 hideHelp = hideHelp || subCmd.HideHelp
227 }
228
229 suggestion := SuggestFlag(flags, fl, hideHelp)
230 if len(suggestion) == 0 {
231 return "", err
232 }
233
234 return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil
235 }
236
237 // Names returns the names including short names and aliases.
238 func (cmd *Command) Names() []string {
239 return append([]string{cmd.Name}, cmd.Aliases...)
240 }
241
242 // HasName returns true if Command.Name matches given name
243 func (cmd *Command) HasName(name string) bool {
244 return slices.Contains(cmd.Names(), name)
245 }
246
247 // VisibleCategories returns a slice of categories and commands that are
248 // Hidden=false
249 func (cmd *Command) VisibleCategories() []CommandCategory {
250 ret := []CommandCategory{}
251 for _, category := range cmd.categories.Categories() {
252 if visible := func() CommandCategory {
253 if len(category.VisibleCommands()) > 0 {
254 return category
255 }
256 return nil
257 }(); visible != nil {
258 ret = append(ret, visible)
259 }
260 }
261 return ret
262 }
263
264 // VisibleCommands returns a slice of the Commands with Hidden=false
265 func (cmd *Command) VisibleCommands() []*Command {
266 var ret []*Command
267 for _, command := range cmd.Commands {
268 if command.Hidden || command.Name == helpName {
269 continue
270 }
271 ret = append(ret, command)
272 }
273 return ret
274 }
275
276 // VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain
277 func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory {
278 if cmd.flagCategories == nil {
279 cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags())
280 }
281 return cmd.flagCategories.VisibleCategories()
282 }
283
284 // VisibleFlags returns a slice of the Flags with Hidden=false
285 func (cmd *Command) VisibleFlags() []Flag {
286 return visibleFlags(cmd.allFlags())
287 }
288
289 func (cmd *Command) appendFlag(fl Flag) {
290 if !hasFlag(cmd.Flags, fl) {
291 cmd.Flags = append(cmd.Flags, fl)
292 }
293 }
294
295 // VisiblePersistentFlags returns a slice of [LocalFlag] with Persistent=true and Hidden=false.
296 func (cmd *Command) VisiblePersistentFlags() []Flag {
297 if cmd.isCompletionCommand {
298 return nil
299 }
300 var flags []Flag
301 for _, fl := range cmd.Root().Flags {
302 pfl, ok := fl.(LocalFlag)
303 if !ok || pfl.IsLocal() {
304 continue
305 }
306 flags = append(flags, fl)
307 }
308 return visibleFlags(flags)
309 }
310
311 func (cmd *Command) appendCommand(aCmd *Command) {
312 if !slices.Contains(cmd.Commands, aCmd) {
313 aCmd.parent = cmd
314 cmd.Commands = append(cmd.Commands, aCmd)
315 }
316 }
317
318 func (cmd *Command) handleExitCoder(ctx context.Context, err error) error {
319 if cmd.parent != nil {
320 return cmd.parent.handleExitCoder(ctx, err)
321 }
322
323 if cmd.ExitErrHandler != nil {
324 cmd.ExitErrHandler(ctx, cmd, err)
325 return err
326 }
327
328 HandleExitCoder(err)
329 return err
330 }
331
332 func (cmd *Command) argsWithDefaultCommand(oldArgs Args) Args {
333 rawArgs := append([]string{cmd.DefaultCommand}, oldArgs.Slice()...)
334 newArgs := &stringSliceArgs{v: rawArgs}
335
336 return newArgs
337 }
338
339 // Root returns the Command at the root of the graph
340 func (cmd *Command) Root() *Command {
341 if cmd.parent == nil {
342 return cmd
343 }
344
345 return cmd.parent.Root()
346 }
347
348 func (cmd *Command) set(fName string, f Flag, val string) error {
349 cmd.setFlags[f] = struct{}{}
350 cmd.setMultiValueParsingConfig(f)
351 if err := f.Set(fName, val); err != nil {
352 return fmt.Errorf("invalid value %q for flag -%s: %v", val, fName, err)
353 }
354 return nil
355 }
356
357 func (cmd *Command) lFlag(name string) Flag {
358 for _, f := range cmd.allFlags() {
359 if slices.Contains(f.Names(), name) {
360 tracef("flag found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
361 return f
362 }
363 }
364 return nil
365 }
366
367 func (cmd *Command) hasPersistentFlagOnAncestor(fl Flag) bool {
368 for pCmd := cmd.parent; pCmd != nil; pCmd = pCmd.parent {
369 for _, pFl := range pCmd.allFlags() {
370 if pFl != fl {
371 continue
372 }
373
374 pfl, ok := pFl.(LocalFlag)
375 if ok && !pfl.IsLocal() {
376 return true
377 }
378 }
379 }
380 return false
381 }
382
383 func (cmd *Command) lookupFlag(name string) Flag {
384 for _, pCmd := range cmd.Lineage() {
385 if f := pCmd.lFlag(name); f != nil {
386 return f
387 }
388 }
389
390 tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
391 cmd.onInvalidFlag(context.TODO(), name)
392 return nil
393 }
394
395 // this looks up only allowed flags, i.e. local flags for current command
396 // or persistent flags from ancestors
397 func (cmd *Command) lookupAppliedFlag(name string) Flag {
398 for _, f := range cmd.appliedFlags {
399 if slices.Contains(f.Names(), name) {
400 tracef("appliedFlag found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
401 return f
402 }
403 }
404
405 tracef("lookupAppliedflag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
406 cmd.onInvalidFlag(context.TODO(), name)
407 return nil
408 }
409
410 func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) {
411 if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
412 flagName := f.Names()[0]
413 if !f.IsSet() {
414 return false, flagName
415 }
416 }
417 return true, ""
418 }
419
420 func (cmd *Command) checkAllRequiredFlags() requiredFlagsErr {
421 // The help and completion commands are allowed to run without
422 // enforcement of required flags, since they do not invoke user
423 // actions that depend on those flag values.
424 if cmd.builtInHelp || cmd.isCompletionCommand {
425 return nil
426 }
427 for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent {
428 if err := pCmd.checkRequiredFlags(); err != nil {
429 return err
430 }
431 }
432 return nil
433 }
434
435 func (cmd *Command) checkRequiredFlags() requiredFlagsErr {
436 tracef("checking for required flags (cmd=%[1]q)", cmd.Name)
437
438 missingFlags := []string{}
439
440 for _, f := range cmd.appliedFlags {
441 if ok, name := cmd.checkRequiredFlag(f); !ok {
442 missingFlags = append(missingFlags, name)
443 }
444 }
445
446 if len(missingFlags) != 0 {
447 tracef("found missing required flags %[1]q (cmd=%[2]q)", missingFlags, cmd.Name)
448
449 return &errRequiredFlags{missingFlags: missingFlags}
450 }
451
452 tracef("all required flags set (cmd=%[1]q)", cmd.Name)
453
454 return nil
455 }
456
457 func (cmd *Command) onInvalidFlag(ctx context.Context, name string) {
458 for cmd != nil {
459 if cmd.InvalidFlagAccessHandler != nil {
460 cmd.InvalidFlagAccessHandler(ctx, cmd, name)
461 break
462 }
463 cmd = cmd.parent
464 }
465 }
466
467 // NumFlags returns the number of flags set
468 func (cmd *Command) NumFlags() int {
469 tracef("numFlags numAppliedFlags %d", len(cmd.appliedFlags))
470 count := 0
471 for _, f := range cmd.appliedFlags {
472 if f.IsSet() {
473 count++
474 }
475 }
476 return count // cmd.flagSet.NFlag()
477 }
478
479 func (cmd *Command) setMultiValueParsingConfig(f Flag) {
480 tracef("setMultiValueParsingConfig %T, %+v", f, f)
481 if cf, ok := f.(multiValueParsingConfigSetter); ok {
482 cf.setMultiValueParsingConfig(multiValueParsingConfig{
483 SliceFlagSeparator: cmd.SliceFlagSeparator,
484 DisableSliceFlagSeparator: cmd.DisableSliceFlagSeparator,
485 MapFlagKeyValueSeparator: cmd.MapFlagKeyValueSeparator,
486 })
487 }
488 }
489
490 // Set sets a context flag to a value.
491 func (cmd *Command) Set(name, value string) error {
492 if f := cmd.lookupFlag(name); f != nil {
493 cmd.setMultiValueParsingConfig(f)
494 return f.Set(name, value)
495 }
496
497 return fmt.Errorf("no such flag -%s", name)
498 }
499
500 // IsSet determines if the flag was actually set
501 func (cmd *Command) IsSet(name string) bool {
502 fl := cmd.lookupFlag(name)
503 if fl == nil {
504 tracef("flag with name %[1]q NOT found; assuming not set (cmd=%[2]q)", name, cmd.Name)
505 return false
506 }
507
508 isSet := fl.IsSet()
509 if isSet {
510 tracef("flag with name %[1]q is set (cmd=%[2]q)", name, cmd.Name)
511 } else {
512 tracef("flag with name %[1]q is no set (cmd=%[2]q)", name, cmd.Name)
513 }
514
515 return isSet
516 }
517
518 // LocalFlagNames returns a slice of flag names used in this
519 // command.
520 func (cmd *Command) LocalFlagNames() []string {
521 names := []string{}
522
523 // Check the flags which have been set via env or file
524 for _, f := range cmd.allFlags() {
525 if f.IsSet() {
526 names = append(names, f.Names()...)
527 }
528 }
529
530 // Sort out the duplicates since flag could be set via multiple
531 // paths
532 m := map[string]struct{}{}
533 uniqNames := []string{}
534
535 for _, name := range names {
536 if _, ok := m[name]; !ok {
537 m[name] = struct{}{}
538 uniqNames = append(uniqNames, name)
539 }
540 }
541
542 return uniqNames
543 }
544
545 // FlagNames returns a slice of flag names used by the this command
546 // and all of its parent commands.
547 func (cmd *Command) FlagNames() []string {
548 names := cmd.LocalFlagNames()
549
550 if cmd.parent != nil {
551 names = append(cmd.parent.FlagNames(), names...)
552 }
553
554 return names
555 }
556
557 // Lineage returns *this* command and all of its ancestor commands
558 // in order from child to parent
559 func (cmd *Command) Lineage() []*Command {
560 lineage := []*Command{cmd}
561
562 if cmd.parent != nil {
563 lineage = append(lineage, cmd.parent.Lineage()...)
564 }
565
566 return lineage
567 }
568
569 // FullName returns the full name of the command.
570 // Includes parent commands separated by space.
571 func (cmd *Command) FullName() string {
572 return strings.Join(cmd.Path(), " ")
573 }
574
575 // Path returns the path of command names from the root to cmd, inclusive.
576 // Each element is a Command.Name. Path traverses upward via parent pointers
577 // similar to Lineage. FullName() is equivalent to strings.Join(cmd.Path(), " ").
578 func (cmd *Command) Path() []string {
579 if cmd.parent != nil {
580 return append(cmd.parent.Path(), cmd.Name)
581 }
582 return []string{cmd.Name}
583 }
584
585 // Walk visits cmd and every descendant. If fn returns a non-nil error, the
586 // walk terminates and the error is returned to the caller.
587 func (cmd *Command) Walk(fn func(*Command) error) error {
588 if fn == nil {
589 return nil
590 }
591 if err := fn(cmd); err != nil {
592 return err
593 }
594 for _, sub := range cmd.Commands {
595 if err := sub.Walk(fn); err != nil {
596 return err
597 }
598 }
599 return nil
600 }
601
602 // Count returns the num of occurrences of this flag
603 func (cmd *Command) Count(name string) int {
604 if cf, ok := cmd.lookupFlag(name).(Countable); ok {
605 return cf.Count()
606 }
607 return 0
608 }
609
610 // Value returns the value of the flag corresponding to `name`
611 func (cmd *Command) Value(name string) any {
612 if fs := cmd.lookupFlag(name); fs != nil {
613 tracef("value found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
614 return fs.Get()
615 }
616
617 tracef("value NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name)
618 return nil
619 }
620
621 // Args returns the command line arguments associated with the
622 // command.
623 func (cmd *Command) Args() Args {
624 return cmd.parsedArgs
625 }
626
627 // NArg returns the number of the command line arguments.
628 func (cmd *Command) NArg() int {
629 return cmd.Args().Len()
630 }
631
632 func (cmd *Command) runFlagActions(ctx context.Context) error {
633 tracef("runFlagActions")
634 // run the flag actions in the same order that they are defined
635 // to maintain consistency.
636 for _, fl := range cmd.appliedFlags {
637 if _, inSet := cmd.setFlags[fl]; inSet {
638 if af, ok := fl.(ActionableFlag); ok {
639 if err := af.RunAction(ctx, cmd); err != nil {
640 return err
641 }
642 }
643 }
644 }
645
646 return nil
647 }