-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand_test.go
More file actions
2295 lines (2161 loc) · 71.9 KB
/
Copy pathcommand_test.go
File metadata and controls
2295 lines (2161 loc) · 71.9 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),
false,
"",
),
).
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(&sink, "one", "", "").Positional(),
),
getFixture(
String(&sink, "one", "", "").Positional(),
String(&sink, "two", "", "").Positional(),
),
getFixture(
String(&sink, "one", "", "").Positional().NArgs(0, 1),
String(&sink, "two", "", "").Positional(),
),
getFixture(
String(&sink, "one", "", "").Positional().NArgs(1, 1),
String(&sink, "two", "", "").Positional(),
),
getFixture(
String(&sink, "one", "", "").Positional().NArgs(1, 1),
String(&sink, "two", "", "").Positional().NArgs(2, 2),
String(&sink, "three", "", "").Positional().NArgs(3, 3),
String(&sink, "four", "", "").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(&sink, "one", "", "").Positional().NArgs(0, 0),
String(&sink, "two", "", "").Positional(),
),
getFixture(
String(&sink, "one", "", "").Positional().NArgs(1, 0),
String(&sink, "two", "", "").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, "foo", "", "").Positional().Required(),
String(&bar, "bar", "", "").Positional().Required(),
Strings(&baz, "baz", nil, "").Positional().NArgs(2, 2),
Strings(&qux, "qux", nil, "").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, "bar", "", ""),
Bool(&qux, "qux", false, ""),
).
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)
}
// 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 a shared registry like
// climux.CommandLine -- 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")
}
// 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() {
var n int
var rightToLeft bool
var endcoding string
cmd := NewCommand("helloworld", "").
HelpFlag().
// n flag defines how many times to print "Hello, World!".
Flags(Int(&n, "n", 1, "Print n times")).
// Mount a flag group for language-related flags.
FlagGroups(NewFlagGroup(
"language",
"Language options",
String(&endcoding, "encoding", "utf-8", "Text encoding"),
Bool(&rightToLeft, "rtl", false, "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() {
var n int
// 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)
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)
return nil
})
// configure the main command with two subcommands and a global "n" flag.
cmd := NewCommand("widgets", "").
HelpFlag().
Flags(Int(&n, "n", 1, "Affect n widgets")).
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_Description() {
var n int
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, "n", 1, "Print n times"))
// 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 ExampleCommand_ForwardArgs() {
var verbose bool
// create a command that forwards arguments to another program
cmd := NewCommand("echo_wrapper", "wraps the echo command").
Flags(
Bool(&verbose, "v", false, "Print verbose output"),
).
ForwardArgs(). // enable the "--" terminator
HandleFunc(func(ctx context.Context, inv *Invocation) error {
// read verbose argument which was parsed by climux
if verbose {
fmt.Printf("+ echo %s\n", strings.Join(inv.Forwarded, " "))
}
// inv.Forwarded holds everything after the "--" terminator,
// untouched by the parser, ready to hand to the wrapped
// program
fmt.Println(strings.Join(inv.Forwarded, " "))
return nil
})
// run in verbose mode and pass ["Hello,", "World!"] through the terminator
Run(context.Background(), cmd, WithArgs("-v", "--", "Hello,", "World!"))
// Output:
// + echo Hello, World!
// Hello, World!
}
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(&a, "foo", "", ""),
String(&b, "foo", "", ""), // duplicate name: invalid
)
_, 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(&s, "name", "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(&a, "foo", "", ""),
String(&b, "foo", "", ""),
), "duplicate flag name")
}
func TestValidateDuplicateShortName(t *testing.T) {
var a, b string
assertParseError(t, NewCommand("test", "").Flags(
String(&a, "x", "", ""),
String(&b, "x", "", ""),
), "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(&a, "file", "", "").Positional(),
String(&b, "file", "", "").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(&a, "name", "", ""),
String(&b, "name", "", ""),
)
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 the path-scoped naming rule: one
// option may not be claimed twice along an ancestor-descendant chain, by
// either spelling, however far up the path the ancestor is. See
// docs/adr/path-scoped-flag-names.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(new(bool), "force", false, "")).
Subcommands(NewCommand("sub", "").Flags(
Bool(new(bool), "force", false, ""),
)),
want: `root sub: flag declared on both "root" and "sub": --force`,
},
{
name: "ShortName",
cmd: NewCommand("root", "").
Flags(String(new(string), "file", "", "").Aliases("f")).
Subcommands(NewCommand("sub", "").Flags(
String(new(string), "output", "", "").Aliases("f"),
)),
want: `root sub: flag declared on both "root" and "sub": -f`,
},
{
name: "GrandparentClaim",
cmd: NewCommand("root", "").
Flags(Bool(new(bool), "force", false, "")).
Subcommands(NewCommand("mid", "").Subcommands(
NewCommand("leaf", "").Flags(
Bool(new(bool), "force", false, ""),
),
)),
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 the freedom the path-scoped rule buys:
// 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(&deleteForce, "force", false, "").Aliases("f"),
),
NewCommand("push", "").Flags(
Bool(&pushForce, "force", false, "").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)
}
func TestValidatePositionalWithSubcommands(t *testing.T) {
var a string
cmd := NewCommand("test", "").
Flags(String(&a, "foo", "", "").Positional()).
Subcommands(NewCommand("sub", ""))
assertParseError(t, cmd, "positional flag alongside subcommands")
}
func TestValidatePositionalAfterUnbounded(t *testing.T) {
var a, b string
assertParseError(t, NewCommand("test", "").Flags(
String(&a, "one", "", "").Positional().NArgs(0, 0),
String(&b, "two", "", "").Positional(),
), "positional after unbounded positional")
}
// TestArgumentErrorNamesTheFlag asserts that every parse error a user can
// provoke names the flag it is about. The flag is carried on the error either
// way, but a human reading stderr only sees Message.
func TestArgumentErrorNamesTheFlag(t *testing.T) {
// Each case builds its own command, since validateNArgs reports the
// first unsatisfied flag and a shared one would let cases mask each
// other.
for _, tt := range []struct {
name string
flag *Flag
args []string
want string
}{
{
"MissingRequired",
String(new(string), "req", "", "").Required(),
nil,
"missing required argument: --req",
},
{
"TooFewExactCount",
Strings(&[]string{}, "pair", nil, "").NArgs(2, 2),
[]string{"--pair", "a"},
"expected 2 arguments, got 1: --pair",
},
{
"TooFewAtLeast",
Strings(&[]string{}, "least", nil, "").NArgs(2, 0),
[]string{"--least", "a"},
"expected at least 2 arguments, got 1: --least",
},
{
"TooManyOccurrences",
Strings(&[]string{}, "many", nil, "").NArgs(0, 2),
[]string{"--many", "a", "--many", "b", "--many", "c"},
"argument specified too many times: --many",
},
{
"OptionNeedsValue",
String(new(string), "opt", "", ""),
[]string{"--opt"},
"option requires an argument: --opt",
},
{
"UnrecognizedOption",
String(new(string), "opt", "", ""),
[]string{"--nope"},
"unrecognized option: --nope",
},
} {
t.Run(tt.name, func(t *testing.T) {
_, err := Parse(NewCommand("test", "").Flags(tt.flag), tt.args...)
if err == nil {
t.Fatalf("expected error for %v, got nil", tt.args)
}
if got, want := humanMessage(err), tt.want; got != want {
t.Errorf("message = %q, want %q", got, want)
}
})
}
}
// TestArgumentErrorNamesPositional asserts the same for a positional, which
// renders as its upper-cased name rather than with a leading dash.
func TestArgumentErrorNamesPositional(t *testing.T) {
var files []string
cmd := NewCommand("test", "").Flags(
Strings(&files, "file", nil, "").Positional().NArgs(1, 0),
)
_, err := Parse(cmd)
if err == nil {
t.Fatal("expected error, got nil")
}
if got, want := humanMessage(err), "missing required argument: FILE"; got != want {
t.Errorf("message = %q, want %q", got, want)
}
}
func TestValidateInvalidNArgs(t *testing.T) {
for _, tt := range []struct {
name string
min, max int
want string
}{
{"MinExceedsMax", 2, 1, "minimum count 2 exceeds maximum count 1"},
{"NegativeMin", -1, 1, "minimum count must not be negative: -1"},
{"NegativeMax", 0, -1, "maximum count must not be negative: -1"},
} {
t.Run(tt.name, func(t *testing.T) {
var a string
cmd := NewCommand("test", "").Flags(
String(&a, "foo", "", "").NArgs(tt.min, tt.max),
)
_, err := Parse(cmd)
if err == nil {
t.Fatalf("NArgs(%d, %d): expected error, got nil", tt.min, tt.max)
}
if got, want := humanMessage(err), "--foo: "+tt.want; got != want {
t.Errorf("message = %q, want %q", got, want)
}
})
}
}
// TestValidateUnboundedMaxIsNotExceeded asserts that a max of 0 means
// unbounded rather than a ceiling the min can breach, so required-and-
// repeatable is a valid configuration.
func TestValidateUnboundedMaxIsNotExceeded(t *testing.T) {
var a []string
cmd := NewCommand("test", "").Flags(
Strings(&a, "foo", nil, "").NArgs(1, 0),
)
if _, err := Parse(cmd, "--foo", "x"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
// TestValidateShortName asserts POSIX guideline 3: a short name is one
// character from [A-Za-z0-9].
func TestValidateShortName(t *testing.T) {
for _, shortName := range []string{
"!", // outside the portable character set
"=", // ... and this one the parser reads as a delimiter
"-",
" ",
"é", // one character, but not one byte, and still not portable
} {
t.Run(shortName, func(t *testing.T) {
var a string
assertParseError(t, NewCommand("test", "").Flags(
String(&a, "foo", "", "").Aliases(shortName),
), "illegal short name")
})
}
for _, shortName := range []string{"x", "X", "0"} {
t.Run(shortName, func(t *testing.T) {
var a string
cmd := NewCommand("test", "").Flags(
String(&a, "foo", "", "").Aliases(shortName),
)
if _, err := Parse(cmd); err != nil {
t.Errorf("expected %q to be a legal short name: %v", shortName, err)
}
})
}
}
// TestValidateCollectsAllErrors asserts that a malformed tree reports
// every configuration error in one run -- they surface in a batch at
// startup -- and that Run prints each on its own prefixed line.
func TestValidateCollectsAllErrors(t *testing.T) {
var a, b, c string
cmd := NewCommand("test", "").Flags(
String(&a, "foo", "", ""),
String(&b, "foo", "", ""), // duplicate name
String(&c, "bar", "", "").Aliases("!"), // illegal short name
)
_, err := Parse(cmd)
if err == nil {
t.Fatal("expected error, got nil")
}
var cfgErr *ir.ConfigError
if !errors.As(err, &cfgErr) {
t.Fatalf("expected a *ConfigError in %v", err)
}
var code int
stderr := captureStderr(t, func() {
code = Run(context.Background(), cmd, WithArgs())
})
if got, want := code, 2; got != want {
t.Errorf("exit code = %d, want %d", got, want)
}
// Model errors precede spelling errors: Compile runs ir's validation,
// which reads each flag on its own terms, before argv's, which reads
// the spellings they render to. Order within a batch is not part of
// the contract; that every error appears exactly once is.
want := "Program error: --bar: short name must be one character from [A-Za-z0-9]: \"!\"\n" +
"Program error: test: flag declared more than once: --foo\n"
if got := stderr; got != want {
t.Errorf("os.Stderr = %q, want %q", got, want)
}
}
// TestConfigErrorReportsOnRunsStderr asserts that a tree which fails to
// compile reports on the stderr its Run call was given. The tree is what
// failed, so nothing it says about itself is worth trusting; the caller's
// stderr is.
func TestConfigErrorReportsOnRunsStderr(t *testing.T) {
sub := NewCommand("sub", "").
Flags(
String(new(string), "foo", "", ""),
String(new(string), "foo", "", ""),
)