-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
1318 lines (1159 loc) · 33.7 KB
/
command.go
File metadata and controls
1318 lines (1159 loc) · 33.7 KB
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 redant
import (
"cmp"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/spf13/pflag"
)
// Command describes an executable command.
type Command struct {
// parent is the parent command.
parent *Command
// Children is a list of direct descendants.
Children []*Command
// Use is provided in form "command [flags] [args...]".
Use string
// Aliases is a list of alternative names for the command.
Aliases []string
// Short is a one-line description of the command.
Short string
// Hidden determines whether the command should be hidden from help.
Hidden bool
// Deprecated indicates whether this command is deprecated.
// If empty, the command is not deprecated.
// If set, the value is used as the deprecation message.
Deprecated string `json:"deprecated,omitempty"`
// Metadata stores extensible command annotations for higher-level behaviors
// (for example: mode=agent, agent.command=true).
Metadata map[string]string `json:"metadata,omitempty"`
// RawArgs determines whether the command should receive unparsed arguments.
// No flags are parsed when set, and the command is responsible for parsing
// its own flags.
RawArgs bool
// Long is a detailed description of the command,
// presented on its help page. It may contain examples.
Long string
Options OptionSet
Args ArgSet
// Middleware is called before the Handler.
// Use Chain() to combine multiple middlewares.
Middleware MiddlewareFunc
Handler HandlerFunc
ResponseHandler ResponseHandler
ResponseStreamHandler ResponseStreamHandler
}
func ascendingSortFn[T cmp.Ordered](a, b T) int {
if a < b {
return -1
} else if a == b {
return 0
}
return 1
}
func appendMissingGlobalOptions(base, globals OptionSet) OptionSet {
existing := make(map[string]struct{}, len(base))
for _, opt := range base {
if opt.Flag == "" {
continue
}
existing[opt.Flag] = struct{}{}
}
for _, opt := range globals {
if opt.Flag == "" {
base = append(base, opt)
continue
}
if _, ok := existing[opt.Flag]; ok {
continue
}
base = append(base, opt)
existing[opt.Flag] = struct{}{}
}
return base
}
// init performs initialization and linting on the command and all its children.
func (c *Command) init() error {
if c.Use == "" {
c.Use = "unnamed"
}
var merr error
// Add global flags to the root command only
if c.parent == nil {
globalFlags := GlobalFlags()
c.Options = appendMissingGlobalOptions(c.Options, globalFlags)
}
for i := range c.Options {
opt := &c.Options[i]
// Validate that option has an identifier (Flag or Env)
if opt.Flag == "" && len(opt.Envs) == 0 {
merr = errors.Join(merr, fmt.Errorf("option must have a Flag or Env field"))
}
if opt.Description != "" {
opt.Description = strings.Trim(strings.ToTitle(strings.TrimSpace(opt.Description)), ".") + "."
}
}
if _, err := c.resolveConfiguredHandler(); err != nil {
merr = errors.Join(merr, err)
}
slices.SortFunc(c.Options, func(a, b Option) int {
// Use Flag for sorting, fallback to Env if Flag is empty
nameA := a.Flag
if nameA == "" && len(a.Envs) > 0 {
nameA = a.Envs[0]
}
nameB := b.Flag
if nameB == "" && len(b.Envs) > 0 {
nameB = b.Envs[0]
}
return ascendingSortFn(nameA, nameB)
})
slices.SortFunc(c.Children, func(a, b *Command) int {
return ascendingSortFn(a.Name(), b.Name())
})
for _, child := range c.Children {
child.parent = c
err := child.init()
if err != nil {
merr = errors.Join(merr, fmt.Errorf("command %v: %w", child.Name(), err))
}
}
return merr
}
// Name returns the first word in the Use string.
func (c *Command) Name() string {
return strings.Split(c.Use, " ")[0]
}
// Meta returns the metadata value for key. Key lookup is case-insensitive.
func (c *Command) Meta(key string) string {
if c == nil || len(c.Metadata) == 0 {
return ""
}
key = strings.TrimSpace(key)
if key == "" {
return ""
}
if v, ok := c.Metadata[key]; ok {
return strings.TrimSpace(v)
}
for k, v := range c.Metadata {
if strings.EqualFold(strings.TrimSpace(k), key) {
return strings.TrimSpace(v)
}
}
return ""
}
// FullName returns the full invocation name of the command,
// as seen on the command line.
func (c *Command) FullName() string {
var names []string
if c.parent != nil {
names = append(names, c.parent.FullName())
}
names = append(names, c.Name())
return strings.Join(names, " ")
}
// Parent returns the parent command of this command.
func (c *Command) Parent() *Command {
return c.parent
}
func (c *Command) FullUsage() string {
var uses []string
if c.parent != nil {
uses = append(uses, c.parent.FullName())
}
uses = append(uses, c.Use)
return strings.Join(uses, " ")
}
// FullOptions returns the options of the command and its parents.
func (c *Command) FullOptions() OptionSet {
var opts OptionSet
if c.parent != nil {
opts = append(opts, c.parent.FullOptions()...)
}
opts = append(opts, c.Options...)
return opts
}
// GetGlobalFlags returns the global flags from the root command
// All non-hidden options in the root command are considered global flags
func (c *Command) GetGlobalFlags() OptionSet {
// Traverse to the root command
root := c
for root.parent != nil {
root = root.parent
}
// Return all non-hidden options from root command as global flags
var globalFlags OptionSet
for _, opt := range root.Options {
if opt.Flag != "" && !opt.Hidden {
globalFlags = append(globalFlags, opt)
}
}
return globalFlags
}
// Invoke creates a new invocation of the command, with
// stdio discarded.
//
// The returned invocation is not live until Run() is called.
func (c *Command) Invoke(args ...string) *Invocation {
return &Invocation{
Command: c,
Args: args,
Stdout: io.Discard,
Stderr: io.Discard,
Stdin: strings.NewReader(""),
}
}
func (c *Command) Run(ctx context.Context) error {
i := &Invocation{
Command: c,
Stdout: io.Discard,
Stderr: io.Discard,
Stdin: strings.NewReader(""),
}
return i.WithOS().WithContext(ctx).Run()
}
// Invocation represents an instance of a command being executed.
type Invocation struct {
ctx context.Context
Command *Command
Flags *pflag.FlagSet
// Args is reduced into the remaining arguments after parsing flags
// during Run.
Args []string
// Arg0 is the executable name used to invoke the program (typically os.Args[0]).
// It enables busybox-style dispatch where the binary name maps directly to
// a subcommand.
Arg0 string
Stdout io.Writer
Stderr io.Writer
Stdin io.Reader
responseStream chan any
responseValue any
// Annotations is a map of arbitrary annotations to attach to the invocation.
Annotations map[string]any
// testing
signalNotifyContext func(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)
}
// WithOS returns the invocation as a main package, filling in the invocation's unset
// fields with OS defaults.
func (inv *Invocation) WithOS() *Invocation {
return inv.with(func(i *Invocation) {
i.Stdout = os.Stdout
i.Stderr = os.Stderr
i.Stdin = os.Stdin
i.Arg0 = os.Args[0]
i.Args = os.Args[1:]
})
}
// WithArgv0 overrides the executable name used for busybox-style dispatch.
// This is primarily useful for testing or when simulating invocation via
// symlinked binaries.
func (inv *Invocation) WithArgv0(arg0 string) *Invocation {
return inv.with(func(i *Invocation) {
i.Arg0 = arg0
})
}
// WithTestSignalNotifyContext allows overriding the default implementation of SignalNotifyContext.
// This should only be used in testing.
func (inv *Invocation) WithTestSignalNotifyContext(
_ testing.TB, // ensure we only call this from tests
f func(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc),
) *Invocation {
return inv.with(func(i *Invocation) {
i.signalNotifyContext = f
})
}
// SignalNotifyContext is equivalent to signal.NotifyContext, but supports being overridden in
// tests.
func (inv *Invocation) SignalNotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc) {
if inv.signalNotifyContext == nil {
return signal.NotifyContext(parent, signals...)
}
return inv.signalNotifyContext(parent, signals...)
}
func (inv *Invocation) WithTestParsedFlags(
_ testing.TB, // ensure we only call this from tests
parsedFlags *pflag.FlagSet,
) *Invocation {
return inv.with(func(i *Invocation) {
i.Flags = parsedFlags
})
}
// ResponseStream returns the invocation response stream channel.
//
// The stream is internally owned by Invocation and is closed automatically when
// ResponseStreamHandler execution finishes.
func (inv *Invocation) ResponseStream() <-chan any {
return inv.ensureResponseStream()
}
func (inv *Invocation) ensureResponseStream() chan any {
if inv.responseStream != nil {
return inv.responseStream
}
inv.responseStream = make(chan any, defaultStreamResponseBuffer)
return inv.responseStream
}
func (inv *Invocation) closeResponseStream() {
if inv.responseStream == nil {
return
}
ch := inv.responseStream
inv.responseStream = nil
close(ch)
}
func (inv *Invocation) Context() context.Context {
if inv.ctx == nil {
return context.Background()
}
return inv.ctx
}
// Response returns the unary response produced by ResponseHandler in current run.
func (inv *Invocation) Response() (any, bool) {
if inv == nil || inv.responseValue == nil {
return nil, false
}
return inv.responseValue, true
}
func (inv *Invocation) setResponse(v any) {
if inv == nil {
return
}
inv.responseValue = v
}
func (inv *Invocation) clearResponse() {
if inv == nil {
return
}
inv.responseValue = nil
}
func (inv *Invocation) ParsedFlags() *pflag.FlagSet {
if inv.Flags == nil {
panic("flags not parsed, has Run() been called?")
}
return inv.Flags
}
type runState struct {
allArgs []string
commandDepth int
flagParseErr error
}
func copyFlagSetWithout(fs *pflag.FlagSet, without string) *pflag.FlagSet {
fs2 := pflag.NewFlagSet("", pflag.ContinueOnError)
fs2.Usage = func() {}
fs.VisitAll(func(f *pflag.Flag) {
if f.Name == without {
return
}
fs2.AddFlag(f)
})
return fs2
}
func (inv *Invocation) CurWords() (prev, cur string) {
switch len(inv.Args) {
// All the shells we support will supply at least one argument (empty string),
// but we don't want to panic.
case 0:
cur = ""
prev = ""
case 1:
cur = inv.Args[0]
prev = ""
default:
cur = inv.Args[len(inv.Args)-1]
prev = inv.Args[len(inv.Args)-2]
}
return prev, cur
}
func getExecCommand(parentCmd *Command, commands map[string]*Command, args []string) (*Command, int) {
for i := 0; i < len(args); i++ {
// Stop at first flag
if strings.HasPrefix(args[i], "-") {
args = args[:i]
break
}
// If the argument contains '=', treat it as a parameter and stop processing
if strings.Contains(args[i], "=") {
args = args[:i]
break
}
}
if len(args) == 0 {
return parentCmd, 0
}
// Try to find command by colon-separated path
if strings.Contains(args[0], ":") {
if cmd, exists := commands[args[0]]; exists {
return cmd, 1
}
// If not found, try to find parent command and process subcommands
parts := strings.Split(args[0], ":")
if len(parts) > 0 {
cmd := parentCmd
for _, part := range parts {
found := false
for _, child := range cmd.Children {
if child.Name() == part {
cmd = child
found = true
break
}
}
if !found {
return parentCmd, 0 // Return parent if path not found
}
}
return cmd, 1
}
}
currentCmd := parentCmd
consumedArgs := 0
// Seed the traversal using the command map (supports aliases) if available.
if cmd, exists := commands[args[0]]; exists {
currentCmd = cmd
consumedArgs = 1
}
// Walk down the command tree using remaining args.
for i := consumedArgs; i < len(args); i++ {
arg := args[i]
found := false
for _, child := range currentCmd.Children {
if child.Name() == arg {
currentCmd = child
consumedArgs = i + 1
found = true
break
}
}
if !found {
break // Stop if command not found
}
}
return currentCmd, consumedArgs
}
func normalizeArgv0(arg0 string) string {
if arg0 == "" {
return ""
}
base := filepath.Base(arg0)
ext := filepath.Ext(base)
if ext != "" {
base = strings.TrimSuffix(base, ext)
}
return base
}
func addCommandMapping(commandMap map[string]*Command, key string, cmd *Command) {
if key == "" {
return
}
if existing := commandMap[key]; existing != nil && existing != cmd {
log.Panicf("duplicate command name: %s", key)
}
commandMap[key] = cmd
}
func getCommands(cmd *Command, parentName string) map[string]*Command {
if cmd == nil {
return nil
}
commandMap := make(map[string]*Command)
name := parentName + ":" + cmd.Name()
if parentName == "" {
name = cmd.Name()
}
addCommandMapping(commandMap, name, cmd)
// Allow busybox-style short lookups for root-level children (one hop away from root).
if cmd.parent != nil && cmd.parent.parent == nil {
addCommandMapping(commandMap, cmd.Name(), cmd)
}
for _, alias := range cmd.Aliases {
alias = strings.TrimSpace(alias)
if alias == "" {
continue
}
aliasName := parentName + ":" + alias
if parentName == "" {
aliasName = alias
}
addCommandMapping(commandMap, aliasName, cmd)
if cmd.parent != nil && cmd.parent.parent == nil {
addCommandMapping(commandMap, alias, cmd)
}
}
for _, child := range cmd.Children {
for n, command := range getCommands(child, name) {
addCommandMapping(commandMap, n, command)
}
}
return commandMap
}
func resolveArgv0Command(arg0 string, commands map[string]*Command) *Command {
normalized := normalizeArgv0(arg0)
if normalized == "" {
return nil
}
cmd, ok := commands[normalized]
if !ok {
return nil
}
return cmd
}
func (inv *Invocation) setParentCommand(parent *Command, children []*Command) {
for _, child := range children {
child.parent = parent
inv.setParentCommand(child, child.Children)
}
}
// run recursively executes the command and its children.
// allArgs is wired through the stack so that global flags can be accepted
// anywhere in the command invocation.
func (inv *Invocation) run(state *runState) error {
parent := inv.Command
inv.setParentCommand(inv.Command, inv.Command.Children)
if inv.Command.Deprecated != "" {
if _, err := fmt.Fprintf(inv.Stderr, "%s %q is deprecated!. %s\n",
prettyHeader("warning"),
inv.Command.FullName(),
inv.Command.Deprecated,
); err != nil {
return fmt.Errorf("write deprecated warning: %w", err)
}
}
// Organize command tree
commands := getCommands(parent, "")
// Use the command returned by getExecCommand
var consumed int
inv.Command, consumed = getExecCommand(parent, commands, state.allArgs)
if consumed == 0 {
if cmd := resolveArgv0Command(inv.Arg0, commands); cmd != nil {
inv.Command = cmd
}
}
if consumed > 0 && consumed <= len(state.allArgs) {
state.allArgs = state.allArgs[consumed:]
}
// Check for global flags before proceeding
if inv.Flags == nil {
inv.Flags = pflag.NewFlagSet(inv.Command.Name(), pflag.ContinueOnError)
// We handle Usage ourselves.
inv.Flags.Usage = func() {}
}
// Add global flags to the flag set
globalFlags := inv.Command.GetGlobalFlags()
globalFlagSet := globalFlags.FlagSet(inv.Command.Name())
globalFlagSet.VisitAll(func(f *pflag.Flag) {
if inv.Flags.Lookup(f.Name) == nil {
inv.Flags.AddFlag(f)
}
})
// Add flags from all parent commands to support flag inheritance
// This allows child commands to use flags defined in parent commands
for p := inv.Command.parent; p != nil; p = p.parent {
p.Options.FlagSet(p.Name()).VisitAll(func(f *pflag.Flag) {
if inv.Flags.Lookup(f.Name) == nil {
inv.Flags.AddFlag(f)
}
})
}
// If we find a duplicate flag, we want the deeper command's flag to override
// the shallow one. Unfortunately, pflag has no way to remove a flag, so we
// have to create a copy of the flagset without a value.
inv.Command.Options.FlagSet(inv.Command.Name()).VisitAll(func(f *pflag.Flag) {
if inv.Flags.Lookup(f.Name) != nil {
inv.Flags = copyFlagSetWithout(inv.Flags, f.Name)
}
inv.Flags.AddFlag(f)
})
var parsedArgs []string
// Parse flags first to get the correct command context
if !inv.Command.RawArgs {
// Flag parsing will fail on intermediate commands in the command tree,
// so we check the error after looking for a child command.
state.flagParseErr = inv.Flags.Parse(state.allArgs)
parsedArgs = inv.Flags.Args()
}
// Handle global flags
if inv.Flags != nil {
// Check for --list-commands flag
if listCommands, err := inv.Flags.GetBool("list-commands"); err == nil && listCommands {
PrintCommands(parent) // Use parent to show full tree
return nil
}
// Check for --list-flags flag
if listFlags, err := inv.Flags.GetBool("list-flags"); err == nil && listFlags {
PrintFlags(parent)
return nil
}
}
// Run child command if found (next child only)
// We must setParentCommand subcommand detection after flag parsing so we don't mistake flag
// values for subcommand names.
if len(parsedArgs) > state.commandDepth {
nextArg := parsedArgs[state.commandDepth]
if child, ok := inv.Command.children()[nextArg]; ok {
child.parent = inv.Command
inv.Command = child
state.commandDepth++
// Clear the Deprecated field on already-parsed flags to avoid
// printing duplicate deprecated warnings when re-parsing in child commands.
// The flags are shared between parent and child FlagSets.
inv.Flags.VisitAll(func(f *pflag.Flag) {
if f.Changed {
f.Deprecated = ""
}
})
return inv.run(state)
}
}
// At this point, we have the final command, so collect remaining args
// (non-flag arguments) for the handler
// Note: flags have already been parsed above, so parsedArgs contains
// the remaining positional arguments
ignoreFlagParseErrors := inv.Command.RawArgs
// Flag parse errors are irrelevant for raw args commands.
if !ignoreFlagParseErrors && state.flagParseErr != nil && !errors.Is(state.flagParseErr, pflag.ErrHelp) {
return fmt.Errorf(
"parsing flags (%v) for %q: %w",
state.allArgs,
inv.Command.FullName(), state.flagParseErr,
)
}
// Check for help flag before validating required options
isHelpRequested := false
if inv.Flags != nil {
if help, err := inv.Flags.GetBool("help"); err == nil && help {
isHelpRequested = true
} else if h, err := inv.Flags.GetBool("h"); err == nil && h {
isHelpRequested = true
}
}
// All options should be set. Check all required options have sources,
// meaning they were set by the user in some way (env, flag, etc).
// Don't validate required flags if help was requested or if there's a help error.
if !isHelpRequested && !errors.Is(state.flagParseErr, pflag.ErrHelp) {
var missing []string
for _, opt := range inv.Command.Options {
if opt.Required {
// Required means the flag must have a value, not that the flag must be present.
// A flag has a value if:
// 1. User explicitly set it (flag.Changed)
// 2. It has a default value (opt.Default != "")
// 3. It can be set via environment variable (opt.Envs)
hasValue := false
if inv.Flags != nil && opt.Flag != "" {
if flag := inv.Flags.Lookup(opt.Flag); flag != nil {
// Flag was explicitly set by user
hasValue = flag.Changed
}
}
// If not set by user, check if there's a default value
if !hasValue && opt.Default != "" {
hasValue = true
}
// If still no value, check if environment variable is available
// (we can't check if env var is actually set here, but if it's configured,
// we assume it might be set)
if !hasValue && len(opt.Envs) > 0 {
hasValue = true
}
if !hasValue {
name := opt.Flag
// use env as a fallback if flag is empty
if name == "" && len(opt.Envs) > 0 {
name = opt.Envs[0]
}
missing = append(missing, name)
}
}
}
if len(missing) > 0 {
return fmt.Errorf("missing values for the required flags: %s", strings.Join(missing, ", "))
}
}
// Execute Action callbacks for options that were set
// Don't execute actions if help was requested
if !isHelpRequested && !errors.Is(state.flagParseErr, pflag.ErrHelp) && inv.Flags != nil {
// Use a map to track which flags we've already processed
// This prevents executing Action multiple times for the same flag
processedFlags := make(map[string]bool)
// Execute actions for flags, starting from the current command and moving up to the root.
// This ensures that if a flag is defined in multiple commands (e.g., overridden),
// the action of the most specific command (the current one) is executed.
for cmd := inv.Command; cmd != nil; cmd = cmd.parent {
for _, opt := range cmd.Options {
if opt.Action != nil && opt.Flag != "" && !processedFlags[opt.Flag] {
if ff := inv.Flags.Lookup(opt.Flag); ff != nil && ff.Changed {
if err := opt.Action(ff.Value); err != nil {
return fmt.Errorf("action for flag %q failed: %w", opt.Flag, err)
}
processedFlags[opt.Flag] = true
}
}
}
}
}
// Parse and assign arguments
if inv.Command.RawArgs {
// If we're at the root command, then the name is omitted
// from the arguments, so we can just use the entire slice.
if state.commandDepth == 0 {
inv.Args = state.allArgs
} else {
argPos, err := findArg(inv.Command.Name(), state.allArgs, inv.Flags)
if err != nil {
panic(err)
}
inv.Args = state.allArgs[argPos+1:]
}
} else {
// In non-raw-arg mode, we want to skip over flags.
inv.Args = parsedArgs[state.commandDepth:]
}
if inv.Flags != nil {
if internalArgsFlag := inv.Flags.Lookup(internalArgsOverrideFlag); internalArgsFlag != nil && internalArgsFlag.Changed {
var overriddenArgs []string
switch v := internalArgsFlag.Value.(type) {
case *StringArray:
overriddenArgs = append(overriddenArgs, (*v)...)
default:
parsed, err := readAsCSV(internalArgsFlag.Value.String())
if err != nil {
return fmt.Errorf("reading %q override values: %w", internalArgsOverrideFlag, err)
}
overriddenArgs = append(overriddenArgs, parsed...)
}
inv.Args = append([]string(nil), overriddenArgs...)
}
}
// Parse args and set values to Arg.Value if Args are defined
// Skip args parsing and validation if help was requested
if len(inv.Command.Args) > 0 && !isHelpRequested && !errors.Is(state.flagParseErr, pflag.ErrHelp) {
if err := parseAndSetArgs(inv.Command.Args, inv.Args); err != nil {
return fmt.Errorf("parsing args: %w", err)
}
} else {
// If Command doesn't define Args, auto-create them from parsed args
// Name will be arg1, arg2, arg3, etc.
if len(inv.Args) > 0 {
autoArgs := make(ArgSet, len(inv.Args))
for i, argStr := range inv.Args {
autoArgs[i] = Arg{
Name: fmt.Sprintf("arg%d", i+1),
}
// Create a String value for auto-created args
strVal := StringOf(new(string))
autoArgs[i].Value = strVal
// Set the value
if err := strVal.Set(argStr); err != nil {
return fmt.Errorf("setting arg%d value: %w", i+1, err)
}
}
inv.Command.Args = autoArgs
}
}
// Collect all middlewares from root to current command
// We collect from current (child) to root (parent), then reverse
// to get [root, parent, ..., child] order. Chain() will reverse again
// to ensure execution order is root -> parent -> ... -> child -> handler
var middlewareChain []MiddlewareFunc
for cmd := inv.Command; cmd != nil; cmd = cmd.parent {
if cmd.Middleware != nil {
middlewareChain = append(middlewareChain, cmd.Middleware)
}
}
// Reverse to get order from root (parent) to current (child)
// This ensures Chain() will execute them in the correct order: root -> parent -> child -> handler
for i, j := 0, len(middlewareChain)-1; i < j; i, j = i+1, j-1 {
middlewareChain[i], middlewareChain[j] = middlewareChain[j], middlewareChain[i]
}
var mw MiddlewareFunc
if len(middlewareChain) > 0 {
mw = Chain(middlewareChain...)
} else {
mw = Chain()
}
ctx := inv.ctx
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
inv.ctx = ctx
// Check for help flag
if inv.Flags != nil {
if help, err := inv.Flags.GetBool("help"); err == nil && help {
return DefaultHelpFn()(ctx, inv)
}
}
handler, resolveErr := inv.Command.resolveConfiguredHandler()
if resolveErr != nil {
return &RunCommandError{Cmd: inv.Command, Err: resolveErr}
}
if handler == nil || errors.Is(state.flagParseErr, pflag.ErrHelp) {
return DefaultHelpFn()(ctx, inv)
}
err := mw(handler)(ctx, inv)
if err != nil {
return &RunCommandError{
Cmd: inv.Command,
Err: err,
}
}
return nil
}
type RunCommandError struct {
Cmd *Command
Err error
}
func (e *RunCommandError) Unwrap() error {
return e.Err
}
func (e *RunCommandError) Error() string {
return fmt.Sprintf("running command %q: %+v", e.Cmd.FullName(), e.Err)
}
// findArg returns the index of the first occurrence of arg in args, skipping
// over all flags.
func findArg(want string, args []string, fs *pflag.FlagSet) (int, error) {
for i := 0; i < len(args); i++ {
arg := args[i]
if !strings.HasPrefix(arg, "-") {
if arg == want {
return i, nil
}
continue
}
// This is a flag!
if strings.Contains(arg, "=") {
// The flag contains the value in the same arg, just skip.
continue
}
// We need to check if NoOptValue is set, then we should not wait
// for the next arg to be the value.
f := fs.Lookup(strings.TrimLeft(arg, "-"))
if f == nil {
return -1, fmt.Errorf("unknown flag: %s", arg)
}
if f.NoOptDefVal != "" {
continue
}
if i == len(args)-1 {
return -1, fmt.Errorf("flag %s requires a value", arg)
}
// Skip the value.
i++
}
return -1, fmt.Errorf("arg %s not found", want)
}
// parseAndSetArgs parses args and sets values to Arg.Value
// It handles different arg formats: positional, query string, form data, and JSON
func parseAndSetArgs(argsDef ArgSet, args []string) error {
if len(args) == 0 {
// Check for required args and set defaults
for i, argDef := range argsDef {
if argDef.Required && argDef.Default == "" {
name := argDef.Name
if name == "" {
name = fmt.Sprintf("arg%d", i+1)
}
return fmt.Errorf("required argument %q is missing", name)
}
// Set default value if available
if argDef.Default != "" && argDef.Value != nil {
if err := argDef.Value.Set(argDef.Default); err != nil {