Repository navigation
Expand file tree
/
Copy pathcommand_test.go
More file actions
2690 lines (2533 loc) · 85.6 KB
/
Copy pathcommand_test.go
File metadata and controls
2690 lines (2533 loc) · 85.6 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 climux
import (
"context"
"errors"
"flag"
"fmt"
"io"
"math/big"
"os"
"os/exec"
"slices"
"strings"
"testing"
"time"
"go.hotsrc.dev/climux/ir"
)
func TestSubcommands(t *testing.T) {
// ranCommands is a bit mask to identify which subcommand handlers were
// invoked
var ranCommands uint64
var setFlags uint64
// newCommand is a function to recursively create subcommands
var newCommand func(n, of uint64) *Command
newCommand = func(n, of uint64) *Command {
c := NewCommand(fmt.Sprintf("command%02d", n), "").
Flags(
BitField(
&setFlags,
uint64(1)<<(n-1),
fmt.Sprintf("x%02d", n),
""),
).
HandleFunc(func(ctx context.Context, inv *Invocation) error {
ranCommands |= 1 << (n - 1)
return nil
})
if n < of {
c.Subcommands(newCommand(n+1, of))
}
return c
}
// call each subcommand
cmdDepth := uint64(64)
cmd := NewCommand("test", "").
Subcommands(newCommand(1, cmdDepth))
for i := uint64(0); i < cmdDepth; i++ {
// build args to call subcommand i
ranCommands = 0
args := make([]string, 0)
for j := uint64(0); j < i+1; j++ {
args = append(
args,
fmt.Sprintf("command%02d", j+1), fmt.Sprintf("--x%02d", j+1),
)
}
// invoke the subcommand handler
if err := Dispatch(context.Background(), cmd, WithArgs(args...)); err != nil {
t.Error(err)
return
}
// check which commands run and flags were set
assertUint64(t, 1<<i, ranCommands)
expectFlags := uint64(0)
for j := uint64(0); j < i+1; j++ {
expectFlags |= 1 << j
}
assertUint64(t, expectFlags, setFlags)
}
}
// TestPosFlagOrdering enforces the rule that no positional arguments may be
// specified after another variable length positional argument as this would
// create ambiguity as to which flag a given argument belongs to. Fixed length
// positional arguments do not exhibit this problem.
func TestPosFlagOrdering(t *testing.T) {
var sink string
getFixture := func(flags ...Flag) *Command {
return NewCommand("test", "").Flags(flags...)
}
successCases := []*Command{
getFixture(
String("one", "").Bind(&sink).Positional(),
),
getFixture(
String("one", "").Bind(&sink).Positional(),
String("two", "").Bind(&sink).Positional(),
),
getFixture(
String("one", "").Bind(&sink).Positional().NArgs(0, 1),
String("two", "").Bind(&sink).Positional(),
),
getFixture(
String("one", "").Bind(&sink).Positional().NArgs(1, 1),
String("two", "").Bind(&sink).Positional(),
),
getFixture(
String("one", "").Bind(&sink).Positional().NArgs(1, 1),
String("two", "").Bind(&sink).Positional().NArgs(2, 2),
String("three", "").Bind(&sink).Positional().NArgs(3, 3),
String("four", "").Bind(&sink).Positional(),
),
}
for i, cmd := range successCases {
t.Run(fmt.Sprintf("SuccessCase%02d", i+1), func(t *testing.T) {
if err := cmd.validate(); err != nil {
t.Errorf("expected nil error, got: %v", err)
}
})
}
errorCases := []*Command{
getFixture(
String("one", "").Bind(&sink).Positional().NArgs(0, 0),
String("two", "").Bind(&sink).Positional(),
),
getFixture(
String("one", "").Bind(&sink).Positional().NArgs(1, 0),
String("two", "").Bind(&sink).Positional(),
),
}
for i, cmd := range errorCases {
t.Run(fmt.Sprintf("ErrorCase%02d", i+1), func(t *testing.T) {
if err := cmd.validate(); err == nil {
t.Errorf("expected error, got nil")
}
})
}
}
func TestPositionalFlags(t *testing.T) {
var foo, bar string
var baz, qux []string
cmd := NewCommand("test", "").Flags(
String("foo", "").Bind(&foo).Positional().Required(),
String("bar", "").Bind(&bar).Positional().Required(),
Strings("baz", "").Bind(&baz).Positional().NArgs(2, 2),
Strings("qux", "").Bind(&qux).Positional().NArgs(0, 0),
)
_, err := Parse(cmd, "one", "two", "three", "four", "five", "six")
if err != nil {
t.Error(err)
return
}
assertString(t, "one", foo)
assertString(t, "two", bar)
assertStrings(t, []string{"three", "four"}, baz)
assertStrings(t, []string{"five", "six"}, qux)
}
func TestFromFlagSet(t *testing.T) {
var foo, bar string
var baz, qux bool
flagSet := flag.NewFlagSet("native", flag.ContinueOnError)
flagSet.StringVar(&foo, "foo", "", "")
flagSet.BoolVar(&baz, "baz", false, "")
c := NewCommand("test", "").
Flags(
String("bar", "").Bind(&bar),
Bool("qux", "").Bind(&qux),
).
FlagGroups(FromFlagSet("native", "Native options", flagSet))
_, err := Parse(c, "--foo", "foo", "--bar", "bar", "--baz", "--qux")
if err != nil {
t.Fatal(err)
}
assertString(t, "foo", foo)
assertString(t, "bar", bar)
assertBool(t, true, baz)
assertBool(t, true, qux)
}
// TestFromFlagSetIsPersistent asserts that an imported flag stays valid
// beneath the command it is mounted on, since a flag set is written for a
// whole program rather than for one command.
func TestFromFlagSetIsPersistent(t *testing.T) {
var foo string
flagSet := flag.NewFlagSet("native", flag.ContinueOnError)
flagSet.StringVar(&foo, "foo", "", "")
c := NewCommand("test", "").
FlagGroups(FromFlagSet("native", "Native options", flagSet)).
Subcommands(NewCommand("sub", ""))
if _, err := Parse(c, "sub", "--foo", "foo"); err != nil {
t.Fatal(err)
}
assertString(t, "foo", foo)
}
// opaqueFlagValue implements flag.Value but not flag.Getter, the way a
// hand-written stdlib flag often does, so FromFlagSet has no concrete
// type to recover a narrower Kind from.
type opaqueFlagValue struct{ s string }
func (v *opaqueFlagValue) String() string { return v.s }
func (v *opaqueFlagValue) Set(s string) error { v.s = s; return nil }
// TestFromFlagSetRecoversKind asserts that a flag imported from a
// flag.FlagSet is described as precisely as a native one: its Kind is
// recovered from the concrete type its Value's Get returns, and a Value
// that does not implement flag.Getter at all compiles to ir.KindOpaque.
func TestFromFlagSetRecoversKind(t *testing.T) {
var s string
var b bool
var i int
var i64 int64
var u uint
var u64 uint64
var f float64
var d time.Duration
flagSet := flag.NewFlagSet("native", flag.ContinueOnError)
var txt big.Float
flagSet.BoolVar(&b, "b", false, "")
flagSet.BoolFunc("bf", "", func(string) error { return nil })
flagSet.DurationVar(&d, "d", 0, "")
flagSet.Float64Var(&f, "f", 0, "")
flagSet.Func("fn", "", func(string) error { return nil })
flagSet.IntVar(&i, "i", 0, "")
flagSet.Int64Var(&i64, "i64", 0, "")
flagSet.Var(&opaqueFlagValue{}, "opaque", "")
flagSet.StringVar(&s, "s", "", "")
flagSet.TextVar(&txt, "txt", &big.Float{}, "")
flagSet.UintVar(&u, "u", 0, "")
flagSet.Uint64Var(&u64, "u64", 0, "")
cmd := NewCommand("test", "").FlagGroups(FromFlagSet("native", "Native options", flagSet))
node, err := cmd.Compile()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// The implicit "options" group is first, empty here; the mounted
// group follows. VisitAll, which FromFlagSet reads, visits in
// lexicographical order.
for i, want := range []ir.Kind{
ir.KindBool, ir.KindBool, ir.KindDuration, ir.KindFloat,
ir.KindOpaque, ir.KindInt, ir.KindInt, ir.KindOpaque,
ir.KindString, ir.KindOpaque, ir.KindUint, ir.KindUint,
} {
if got := node.FlagGroups[1].Flags[i].Kind; got != want {
t.Errorf("Flags[%d].Kind = %q, want %q", i, got, want)
}
}
}
func TestCommandLineage(t *testing.T) {
a, b, c := NewCommand("a", ""), NewCommand("b", ""), NewCommand("c", "")
a.Subcommands(b)
b.Subcommands(c)
assertString(t, "a", a.name)
assertString(t, "b", a.subcommands[0].name)
assertString(t, "a", a.subcommands[0].parent.name)
assertString(t, "c", a.subcommands[0].subcommands[0].name)
assertString(t, "b", a.subcommands[0].subcommands[0].parent.name)
}
// TestSubcommandAlreadyParented asserts that Subcommands does not steal an
// already-parented command -- such as one a library exports and two trees
// both mount -- and that the mismatch is reported as a ConfigError rather
// than silently corrupting the original relationship.
func TestSubcommandAlreadyParented(t *testing.T) {
a, b, shared := NewCommand("a", ""), NewCommand("b", ""), NewCommand("shared", "")
a.Subcommands(shared)
b.Subcommands(shared)
assertString(t, "a", shared.parent.name)
if _, err := Parse(a); err != nil {
t.Errorf("a.Parse: expected nil error, got: %v", err)
}
assertConfigError(t, b, "a subcommand already parented elsewhere")
}
// TestSubcommandDuplicateName asserts that two children answering to one
// word are a configuration error. Dispatch resolves a name to a single
// command, so without the check the second is unreachable and nothing
// says which was meant.
func TestSubcommandDuplicateName(t *testing.T) {
handle := func(ctx context.Context, inv *Invocation) error { return nil }
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("x", "first").HandleFunc(handle),
NewCommand("x", "second").HandleFunc(handle),
), "two subcommands sharing a name")
}
// TestSubcommandAliasCollides asserts that an alias collides with a
// sibling's name or alias the way two names do, since dispatch resolves
// every one of them to a single command.
func TestSubcommandAliasCollides(t *testing.T) {
handle := func(ctx context.Context, inv *Invocation) error { return nil }
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("run", "").Aliases("r").HandleFunc(handle),
NewCommand("r", "").HandleFunc(handle),
), "an alias sharing a sibling's name")
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("run", "").Aliases("r").HandleFunc(handle),
NewCommand("remove", "").Aliases("r").HandleFunc(handle),
), "two siblings sharing an alias")
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("run", "").HiddenAliases("r").HandleFunc(handle),
NewCommand("r", "").HandleFunc(handle),
), "a hidden alias sharing a sibling's name")
}
// TestCommandEmptyName asserts that an empty command name or alias is
// a configuration error: no word on a command line reaches a subcommand
// by it, and the root's is what the program is printed as.
func TestCommandEmptyName(t *testing.T) {
handle := func(ctx context.Context, inv *Invocation) error { return nil }
assertConfigError(t, NewCommand("", "").HandleFunc(handle),
"an empty root name")
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("", "").HandleFunc(handle),
), "an empty subcommand name")
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("run", "").Aliases("").HandleFunc(handle),
), "an empty alias")
assertConfigError(t, NewCommand("app", "").Subcommands(
NewCommand("run", "").HiddenAliases("").HandleFunc(handle),
), "an empty hidden alias")
}
// TestSubcommandCycle asserts that a command tree that leads back into
// itself is reported as a ConfigError rather than walked forever. Every
// shape here wedged the process before the tree could be validated: the
// first three walking parent links to find a root that is not there, the
// last two descending subcommand links that lead back up.
func TestSubcommandCycle(t *testing.T) {
tests := []struct {
name string
cmd func() *Command
}{
{
// A command mounted under itself, which Subcommands accepts
// because its parent is nil at the time.
name: "Self",
cmd: func() *Command {
a := NewCommand("a", "")
return a.Subcommands(a)
},
},
{
name: "Mutual",
cmd: func() *Command {
a, b := NewCommand("a", ""), NewCommand("b", "")
a.Subcommands(b)
b.Subcommands(a)
return a
},
},
{
name: "Deep",
cmd: func() *Command {
a, b, c := NewCommand("a", ""), NewCommand("b", ""), NewCommand("c", "")
a.Subcommands(b)
b.Subcommands(c)
c.Subcommands(a)
return a
},
},
{
// The parent links are acyclic here -- Subcommands leaves b's
// parent alone, since a already claimed it -- so only the
// descent through subcommands leads back up.
name: "SubcommandsOnly",
cmd: func() *Command {
a, b, c := NewCommand("a", ""), NewCommand("b", ""), NewCommand("c", "")
a.Subcommands(b)
b.Subcommands(c)
c.Subcommands(b)
return a
},
},
{
name: "MountedTwice",
cmd: func() *Command {
a, b := NewCommand("a", ""), NewCommand("b", "")
return a.Subcommands(b, b)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assertConfigError(t, tt.cmd(), "a cycle in the command tree")
})
}
}
// TestSubcommandCycleFromDescendant asserts that the cycle is reported
// wherever Compile is called from, not only from the command that closes
// it.
func TestSubcommandCycleFromDescendant(t *testing.T) {
a, b := NewCommand("a", ""), NewCommand("b", "")
a.Subcommands(b)
b.Subcommands(a)
assertConfigError(t, b, "a cycle reached from a descendant")
}
func ExampleCommand_FlagGroups() {
cmd := NewCommand("helloworld", "").
HelpFlag().
// n flag defines how many times to print "Hello, World!".
Flags(Int("n", "Print n times").Default(1)).
// Mount a flag group for language-related flags.
FlagGroups(NewFlagGroup(
"language",
"Language options",
String("encoding", "Text encoding").Default("utf-8"),
Bool("rtl", "Print right-to-left"),
))
// Print the help page
Run(context.Background(), cmd, WithArgs("--help"))
// Output:
// Usage: helloworld [OPTIONS]
//
// Options:
// -h, --help Show this help message and exit
// -n Print n times
//
// Language options:
// --encoding Text encoding
// --rtl Print right-to-left
}
func ExampleFromFlagSet() {
// create a Go-native flag set
flagSet := flag.NewFlagSet("native", flag.ExitOnError)
message := flagSet.String("m", "Hello, World!", "Message to print")
// import the flagset into an climux command as a flag group
cmd := NewCommand("helloworld", "").
HelpFlag().
FlagGroups(FromFlagSet("native", "Native options", flagSet)).
HandleFunc(func(ctx context.Context, inv *Invocation) error {
fmt.Println(*message)
return nil
})
ctx := context.Background()
// Print the help page
fmt.Println("+ helloworld --help")
Run(ctx, cmd, WithArgs("--help"))
// Run the command
fmt.Println()
fmt.Println("+ helloworld")
Run(ctx, cmd, WithArgs())
// Output:
// + helloworld --help
// Usage: helloworld [OPTIONS]
//
// Options:
// -h, --help Show this help message and exit
//
// Native options:
// -m Message to print
//
// + helloworld
// Hello, World!
}
func ExampleCommand_Subcommands() {
// a persistent "n" flag, declared once and read by both subcommands
n := Int("n", "Affect n widgets").Default(1).Persistent().State()
// configure a "create" subcommand
create := NewCommand("create", "Make new widgets").
HandleFunc(func(ctx context.Context, inv *Invocation) error {
fmt.Printf("Created %d widget(s)\n", n.Value())
return nil
})
// configure a "destroy" subcommand
destroy := NewCommand("destroy", "Destroy widgets").
HandleFunc(func(ctx context.Context, inv *Invocation) error {
fmt.Printf("Destroyed %d widget(s)\n", n.Value())
return nil
})
// configure the main command with two subcommands and the persistent
// flag, so it can be given after either of them.
cmd := NewCommand("widgets", "").
HelpFlag().
Flags(n).
Subcommands(create, destroy)
ctx := context.Background()
// Print the help page
fmt.Println("+ widgets --help")
Run(ctx, cmd, WithArgs("--help"))
// Invoke the "create" subcommand
fmt.Println()
fmt.Println("+ widgets create -n=3")
Run(ctx, cmd, WithArgs("create", "-n=3"))
// Output:
// + widgets --help
// Usage: widgets [OPTIONS] COMMAND
//
// Options:
// -h, --help Show this help message and exit
// -n Affect n widgets
//
// Commands:
// create Make new widgets
// destroy Destroy widgets
//
// + widgets create -n=3
// Created 3 widget(s)
}
func ExampleCommand_Aliases() {
remove := NewCommand("remove", "Remove widgets").
Aliases("rm").
HandleFunc(func(ctx context.Context, inv *Invocation) error {
fmt.Println("Running", inv.Cmd.FullName)
return nil
})
cmd := NewCommand("widgets", "").HelpFlag().Subcommands(remove)
ctx := context.Background()
fmt.Println("+ widgets --help")
Run(ctx, cmd, WithArgs("--help"))
fmt.Println()
fmt.Println("+ widgets rm")
Run(ctx, cmd, WithArgs("rm"))
// Output:
// + widgets --help
// Usage: widgets [OPTIONS] COMMAND
//
// Options:
// -h, --help Show this help message and exit
//
// Commands:
// remove, rm Remove widgets
//
// + widgets rm
// Running widgets remove
}
func ExampleCommand_HiddenAliases() {
remove := NewCommand("remove", "Remove widgets").
Aliases("rm").
HiddenAliases("delete").
HandleFunc(func(ctx context.Context, inv *Invocation) error {
fmt.Println("Running", inv.Cmd.FullName)
return nil
})
cmd := NewCommand("widgets", "").HelpFlag().Subcommands(remove)
ctx := context.Background()
fmt.Println("+ widgets --help")
Run(ctx, cmd, WithArgs("--help"))
fmt.Println()
fmt.Println("+ widgets delete")
Run(ctx, cmd, WithArgs("delete"))
// Output:
// + widgets --help
// Usage: widgets [OPTIONS] COMMAND
//
// Options:
// -h, --help Show this help message and exit
//
// Commands:
// remove, rm Remove widgets
//
// + widgets delete
// Running widgets remove
}
func ExampleCommand_Description() {
cmd := NewCommand("helloworld", "Say \"Hello, World!\"").
HelpFlag().
// Configure a description to print detailed information on the help
// page.
Description(
"This utility prints \"Hello, World!\" to the standard output.\n" +
"Print more than once with -n.",
).
Flags(Int("n", "Print n times").Default(1))
// Print the help page
Run(context.Background(), cmd, WithArgs("--help"))
// Output:
// Usage: helloworld [OPTIONS]
//
// Say "Hello, World!"
//
// Options:
// -h, --help Show this help message and exit
// -n Print n times
//
// This utility prints "Hello, World!" to the standard output.
// Print more than once with -n.
}
func ExampleFlagBuilder_EndOfOptions() {
verbose := Bool("v", "Print verbose output").State()
// once the first argument is taken, options have ended, so echo's own
// options reach it rather than echo_wrapper
args := Strings("arg", "Arguments to pass to echo").
Positional().
EndOfOptions().
State()
// create a command that hands its arguments to another program
cmd := NewCommand("echo_wrapper", "wraps the echo command").
Flags(verbose, args).
HandleFunc(func(ctx context.Context, inv *Invocation) error {
if verbose.Value() {
fmt.Printf("+ echo %s\n", strings.Join(args.Value(), " "))
}
fmt.Println(strings.Join(args.Value(), " "))
return nil
})
// -v is echo_wrapper's; -n comes after the first argument, so it is echo's
Run(context.Background(), cmd, WithArgs("-v", "Hello,", "World!", "-n"))
// Output:
// + echo Hello, World! -n
// Hello, World! -n
}
func TestCompileRoot(t *testing.T) {
sub := NewCommand("sub", "Sub command summary")
root := NewCommand("root", "Root command summary").
Description("Root description").
Subcommands(sub)
node, err := root.Compile()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got, want := node.Name, "root"; got != want {
t.Errorf("Name = %q, want %q", got, want)
}
if got, want := node.Summary, "Root command summary"; got != want {
t.Errorf("Summary = %q, want %q", got, want)
}
if got, want := node.Description, "Root description"; got != want {
t.Errorf("Description = %q, want %q", got, want)
}
if got, want := len(node.Ancestry), 1; got != want {
t.Errorf("len(Ancestry) = %d, want %d for a root", got, want)
}
if got, want := len(node.Subcommands), 1; got != want {
t.Fatalf("len(Subcommands) = %d, want %d", got, want)
}
if got, want := node.Subcommands[0].Name, "sub"; got != want {
t.Errorf("Subcommands[0].Name = %q, want %q", got, want)
}
subNode := node.Subcommands[0]
if got, want := subNode.Ancestry, []*ir.Command{node, subNode}; !slices.Equal(got, want) {
t.Errorf("Subcommands[0].Ancestry = %v, want %v", got, want)
}
}
func TestCompileSubcommand(t *testing.T) {
foo := NewCommand("foo", "Foo summary")
bar := NewCommand("bar", "Bar summary")
NewCommand("root", "Root summary").Subcommands(foo, bar)
node, err := foo.Compile()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got, want := node.Name, "foo"; got != want {
t.Errorf("Name = %q, want %q", got, want)
}
if got, want := len(node.Ancestry), 2; got != want {
t.Fatalf("len(Ancestry) = %d, want %d", got, want)
}
root := node.Ancestry[0]
if got, want := root.Name, "root"; got != want {
t.Errorf("Ancestry[0].Name = %q, want %q", got, want)
}
if got, want := root, node.Root; got != want {
t.Errorf("Ancestry[0] = %v, want it to be Root %v", got, want)
}
var names []string
for _, c := range root.Subcommands {
names = append(names, c.Name)
}
assertStrings(t, []string{"foo", "bar"}, names)
}
// TestCompileValidationError asserts that Compile returns the same
// configuration error that Parse would for a misconfigured tree.
func TestCompileValidationError(t *testing.T) {
var a, b string
cmd := NewCommand("test", "").Flags(
String("foo", "").Bind(&a),
String("foo", "").Bind(&b),
)
_, compileErr := cmd.Compile()
if compileErr == nil {
t.Fatal("expected error from Compile for duplicate flag name, got nil")
}
_, parseErr := Parse(cmd)
if parseErr == nil {
t.Fatal("expected error from Parse for duplicate flag name, got nil")
}
if got, want := compileErr.Error(), parseErr.Error(); got != want {
t.Errorf("Compile error %q, want the Parse error %q", got, want)
}
}
// TestCompileIsPure asserts that Compile does not mutate the command tree
// or the variables flags are bound to: it must reflect neither a Parse that
// ran before it, nor any bookkeeping of its own.
func TestCompileIsPure(t *testing.T) {
var s string
cmd := NewCommand("test", "").Flags(
String("name", "").Bind(&s).Default("default-value").NArgs(0, 1),
)
if _, err := Parse(cmd, "--name=parsed-value"); err != nil {
t.Fatalf("unexpected error from Parse: %v", err)
}
if got, want := s, "parsed-value"; got != want {
t.Fatalf("s = %q, want %q after Parse", got, want)
}
node, err := cmd.Compile()
if err != nil {
t.Fatalf("unexpected error from Compile: %v", err)
}
// The bound variable must still hold the parsed value: Compile must
// not have written back to it.
if got, want := s, "parsed-value"; got != want {
t.Errorf("s = %q, want %q after Compile", got, want)
}
// The projected default must still show the value captured at
// construction, not the live/parsed value.
df := node.FlagGroups[0].Flags[0]
if got, want := df.Default, "default-value"; got != want {
t.Errorf("Default = %q, want %q", got, want)
}
}
// assertParseError asserts that parsing cmd fails, naming the invalid
// configuration under test in the failure message.
func assertParseError(t *testing.T, cmd *Command, reason string) bool {
t.Helper()
if _, err := Parse(cmd); err == nil {
t.Errorf("expected error for %s, got nil", reason)
return false
}
return true
}
func TestValidateDuplicateFlagName(t *testing.T) {
var a, b string
assertParseError(t, NewCommand("test", "").Flags(
String("foo", "").Bind(&a),
String("foo", "").Bind(&b),
), "duplicate flag name")
}
func TestValidateDuplicateShortName(t *testing.T) {
var a, b string
assertParseError(t, NewCommand("test", "").Flags(
String("x", "").Bind(&a),
String("x", "").Bind(&b),
), "duplicate short name")
}
// TestValidateDuplicatePositionalName asserts that a duplicate name
// between two positional flags is reported as a duplicate operand, in
// the vocabulary a user of the command line would recognize, rather than
// the "flag" wording that fits an option.
func TestValidateDuplicatePositionalName(t *testing.T) {
var a, b string
_, err := Parse(NewCommand("test", "").Flags(
String("file", "").Bind(&a).Positional(),
String("file", "").Bind(&b).Positional(),
))
if err == nil {
t.Fatal("expected error, got nil")
}
if got, want := humanMessage(err), "test: operand declared more than once: FILE"; got != want {
t.Errorf("message = %q, want %q", got, want)
}
}
// TestConfigErrorNamesGrandchildByPath asserts that a ConfigError on a
// deep subcommand reports where it lives: the bare name "add" could be
// any command called "add", but "app remote add" is not.
func TestConfigErrorNamesGrandchildByPath(t *testing.T) {
var a, b string
add := NewCommand("add", "").Flags(
String("name", "").Bind(&a),
String("name", "").Bind(&b),
)
remote := NewCommand("remote", "").Subcommands(add)
app := NewCommand("app", "").Subcommands(remote)
_, err := Parse(app)
if err == nil {
t.Fatal("expected error, got nil")
}
want := `app remote add: flag declared more than once: --name`
if got := humanMessage(err); got != want {
t.Errorf("message = %q, want %q", got, want)
}
}
// TestValidateAncestorShadowing asserts that a persistent flag's options
// may not be claimed again beneath it, by either spelling, however far up
// the path the ancestor is: both would be writable after the descendant is
// named. See docs/adr/flags-are-local-by-default.md.
//
// The error names both commands, since ancestry is what tells a reader
// which end to change, and neither is called the offender: which was
// declared first is an accident of mount order. The command the error is
// reported against is still named by its full path, since a bare "sub" or
// "leaf" would not say which among possibly many.
func TestValidateAncestorShadowing(t *testing.T) {
for _, tt := range []struct {
name string
cmd *Command
want string
}{
{
name: "LongName",
cmd: NewCommand("root", "").
Flags(Bool("force", "").Persistent()).
Subcommands(NewCommand("sub", "").Flags(
Bool("force", ""),
)),
want: `root sub: flag declared on both "root" and "sub": --force`,
},
{
name: "ShortName",
cmd: NewCommand("root", "").
Flags(String("file", "").Aliases("f").Persistent()).
Subcommands(NewCommand("sub", "").Flags(
String("output", "").Aliases("f"),
)),
want: `root sub: flag declared on both "root" and "sub": -f`,
},
{
name: "GrandparentClaim",
cmd: NewCommand("root", "").
Flags(Bool("force", "").Persistent()).
Subcommands(NewCommand("mid", "").Subcommands(
NewCommand("leaf", "").Flags(
Bool("force", ""),
),
)),
want: `root mid leaf: flag declared on both "root" and "leaf": --force`,
},
} {
t.Run(tt.name, func(t *testing.T) {
_, err := Parse(tt.cmd)
if err == nil {
t.Fatal("expected error, got nil")
}
if got, want := humanMessage(err), tt.want; got != want {
t.Errorf("message = %q, want %q", got, want)
}
})
}
}
// TestSiblingFlagReuse asserts that commands in different subtrees may declare the same names, and each
// spelling binds the variable of whichever sibling was invoked.
func TestSiblingFlagReuse(t *testing.T) {
var deleteForce, pushForce bool
app := NewCommand("app", "").Subcommands(
NewCommand("delete", "").Flags(
Bool("force", "").Bind(&deleteForce).Aliases("f"),
),
NewCommand("push", "").Flags(
Bool("force", "").Bind(&pushForce).Aliases("f"),
),
)
inv, err := Parse(app, "delete", "--force")
if err != nil {
t.Fatal(err)
}
if got, want := inv.Cmd.Name, "delete"; got != want {
t.Errorf("Cmd = %q, want %q", got, want)
}
assertBool(t, true, deleteForce)
assertBool(t, false, pushForce)
inv, err = Parse(app, "push", "-f")
if err != nil {
t.Fatal(err)
}
if got, want := inv.Cmd.Name, "push"; got != want {
t.Errorf("Cmd = %q, want %q", got, want)
}
assertBool(t, true, pushForce)
}
// newRemoteTree returns a "remote" command with a handler of
// its own and an "add" subcommand, each declaring a --verbose of its own.
// remote's is persistent when persistent is set, and add's is omitted
// then, since the name would collide.
func newRemoteTree(remoteVerbose, addVerbose *bool, persistent bool) *Command {
verbose := Bool("verbose", "").Bind(remoteVerbose)
add := NewCommand("add", "")
if persistent {
verbose.Persistent()
} else {
add.Flags(Bool("verbose", "").Bind(addVerbose))
}
return NewCommand("app", "").Subcommands(
NewCommand("remote", "").Flags(verbose).Subcommands(add),
)
}
// TestLocalFlagScope asserts that a local flag is valid from its own
// command's name until the line dispatches, and unknown after that, while
// a persistent one stays valid beneath its command. See
// docs/adr/flags-are-local-by-default.md.
func TestLocalFlagScope(t *testing.T) {
t.Run("WrittenBeforeDispatch", func(t *testing.T) {
var remoteVerbose, addVerbose bool
inv, err := Parse(newRemoteTree(&remoteVerbose, &addVerbose, false),
"remote", "--verbose", "add")
if err != nil {
t.Fatal(err)
}
if got, want := inv.Cmd.Name, "add"; got != want {
t.Errorf("Cmd = %q, want %q", got, want)
}
assertBool(t, true, remoteVerbose)
assertBool(t, false, addVerbose)
})
t.Run("ShadowedAfterDispatch", func(t *testing.T) {
var remoteVerbose, addVerbose bool
_, err := Parse(newRemoteTree(&remoteVerbose, &addVerbose, false),
"remote", "--verbose", "add", "--verbose")
if err != nil {
t.Fatal(err)
}
assertBool(t, true, remoteVerbose)
assertBool(t, true, addVerbose)
})
t.Run("UnknownAfterDispatch", func(t *testing.T) {
tree := NewCommand("app", "").Subcommands(
NewCommand("remote", "").
Flags(Bool("verbose", "")).
Subcommands(NewCommand("add", "")),
)
_, err := Parse(tree, "remote", "add", "--verbose")
if err == nil {
t.Fatal("expected error, got nil")
}
if got, want := humanMessage(err),
`unrecognized option: --verbose (an option of "app remote")`; got != want {
t.Errorf("message = %q, want %q", got, want)
}
})
t.Run("PersistentAfterDispatch", func(t *testing.T) {
var remoteVerbose bool
if _, err := Parse(newRemoteTree(&remoteVerbose, nil, true),
"remote", "add", "--verbose"); err != nil {
t.Fatal(err)
}
assertBool(t, true, remoteVerbose)
})
// A word naming a subcommand is data while the command's positionals
// are still filling, so the line has not dispatched and the command's
// local flags stay valid.
t.Run("PositionalDoesNotDispatch", func(t *testing.T) {
var files []string
var verbose bool
app := NewCommand("app", "").
Flags(
Strings("file", "").Bind(&files).Positional(),
Bool("verbose", "").Bind(&verbose),
).
Subcommands(NewCommand("run", ""))
inv, err := Parse(app, "x", "run", "--verbose")
if err != nil {
t.Fatal(err)
}
if got, want := inv.Cmd.Name, "app"; got != want {
t.Errorf("Cmd = %q, want %q", got, want)