-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_test.go
More file actions
1004 lines (941 loc) · 29.4 KB
/
parse_test.go
File metadata and controls
1004 lines (941 loc) · 29.4 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 cli
import (
"bytes"
"context"
"errors"
"flag"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testState is a helper struct to hold the commands for testing
//
// root --verbose --version
// ├── add --dry-run
// └── nested --force
// └── sub --echo
// └── hello --mandatory-flag=false --another-mandatory-flag some-value
type testState struct {
add *Command
nested, sub, hello *Command
root *Command
}
func newTestState() testState {
exec := func(ctx context.Context, s *State) error { return errors.New("not implemented") }
add := &Command{
Name: "add",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.Bool("dry-run", false, "enable dry-run mode")
}),
Exec: exec,
}
sub := &Command{
Name: "sub",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.String("echo", "", "echo the message")
}),
FlagOptions: []FlagOption{
{Name: "echo", Required: false}, // not required
},
Exec: exec,
}
hello := &Command{
Name: "hello",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.Bool("mandatory-flag", false, "mandatory flag")
fset.String("another-mandatory-flag", "", "another mandatory flag")
}),
FlagOptions: []FlagOption{
{Name: "mandatory-flag", Required: true},
{Name: "another-mandatory-flag", Required: true},
},
Exec: exec,
}
nested := &Command{
Name: "nested",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.Bool("force", false, "force the operation")
}),
SubCommands: []*Command{sub, hello},
Exec: exec,
}
root := &Command{
Name: "todo",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.Bool("verbose", false, "enable verbose mode")
fset.Bool("version", false, "show version")
}),
SubCommands: []*Command{add, nested},
Exec: exec,
}
return testState{
add: add,
nested: nested,
sub: sub,
root: root,
hello: hello,
}
}
func TestParse(t *testing.T) {
t.Parallel()
t.Run("error on parse with no exec", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "foo",
Exec: func(ctx context.Context, s *State) error { return nil },
SubCommands: []*Command{
{
Name: "bar",
Exec: func(ctx context.Context, s *State) error { return nil },
SubCommands: []*Command{
{
Name: "baz",
},
},
},
},
}
err := Parse(cmd, []string{"bar", "baz"})
require.Error(t, err)
assert.ErrorContains(t, err, `command "foo bar baz": no exec function defined`)
})
t.Run("parsing errors", func(t *testing.T) {
t.Parallel()
err := Parse(nil, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "command is nil")
err = Parse(&Command{}, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "root command has no name")
})
t.Run("subcommand nil flags", func(t *testing.T) {
t.Parallel()
err := Parse(&Command{
Name: "root",
SubCommands: []*Command{{
Name: "sub",
Exec: func(ctx context.Context, s *State) error { return nil },
}},
Exec: func(ctx context.Context, s *State) error { return nil },
}, []string{"sub"})
require.NoError(t, err)
})
t.Run("default flag usage", func(t *testing.T) {
t.Parallel()
by := bytes.NewBuffer(nil)
root := &Command{
Name: "root",
Usage: "root [flags]",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.SetOutput(by)
}),
}
err := Parse(root, []string{"--help"})
require.Error(t, err)
require.ErrorIs(t, err, flag.ErrHelp)
require.Empty(t, by.String())
})
t.Run("no flags", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "item1"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
require.Equal(t, s.add, cmd)
require.False(t, GetFlag[bool](s.root.state, "dry-run"))
})
t.Run("unknown flag", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "--unknown", "item1"})
require.Error(t, err)
require.Contains(t, err.Error(), `command "todo add": flag provided but not defined: -unknown`)
})
t.Run("with subcommand flags", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "--dry-run", "item1"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.add, cmd)
assert.True(t, GetFlag[bool](s.root.state, "dry-run"))
})
t.Run("help flag", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"--help"})
require.Error(t, err)
require.ErrorIs(t, err, flag.ErrHelp)
})
t.Run("help flag with subcommand", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "--help"})
require.Error(t, err)
require.ErrorIs(t, err, flag.ErrHelp)
})
t.Run("help flag with subcommand at s.root", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"--help", "add"})
require.Error(t, err)
require.ErrorIs(t, err, flag.ErrHelp)
})
t.Run("help flag with subcommand and other flags", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "--help", "--dry-run"})
require.Error(t, err)
require.ErrorIs(t, err, flag.ErrHelp)
})
t.Run("unknown subcommand", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"unknown"})
require.Error(t, err)
require.Contains(t, err.Error(), "unknown command")
})
t.Run("flags at multiple levels", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "--dry-run", "item1", "--verbose"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.add, cmd)
assert.True(t, GetFlag[bool](s.root.state, "dry-run"))
assert.True(t, GetFlag[bool](s.root.state, "verbose"))
})
t.Run("nested subcommand and root flag", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"--verbose", "nested", "sub", "--echo", "hello"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.sub, cmd)
assert.Equal(t, "hello", GetFlag[string](s.root.state, "echo"))
assert.True(t, GetFlag[bool](s.root.state, "verbose"))
})
t.Run("nested subcommand with mixed flags", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"nested", "sub", "--echo", "hello", "--verbose"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.sub, cmd)
assert.Equal(t, "hello", GetFlag[string](s.root.state, "echo"))
assert.True(t, GetFlag[bool](s.root.state, "verbose"))
})
t.Run("end of options delimiter", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"--verbose", "--", "nested", "sub", "--echo", "hello"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.root, cmd)
assert.Equal(t, []string{"nested", "sub", "--echo", "hello"}, s.root.state.Args)
assert.True(t, GetFlag[bool](s.root.state, "verbose"))
})
t.Run("flags and args", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"add", "item1", "--dry-run", "item2"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.add, cmd)
assert.True(t, GetFlag[bool](s.root.state, "dry-run"))
assert.Equal(t, []string{"item1", "item2"}, s.root.state.Args)
})
t.Run("nested subcommand with flags and args", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"nested", "sub", "--echo", "hello", "world"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.sub, cmd)
assert.Equal(t, "hello", GetFlag[string](s.root.state, "echo"))
assert.Equal(t, []string{"world"}, s.root.state.Args)
})
t.Run("subcommand flags not available in parent", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"--dry-run"})
require.Error(t, err)
require.ErrorContains(t, err, "flag provided but not defined")
})
t.Run("parent flags inherited in subcommand", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"nested", "sub", "--force"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.sub, cmd)
assert.True(t, GetFlag[bool](s.root.state, "force"))
})
t.Run("unrelated subcommand flags not inherited in other subcommands", func(t *testing.T) {
t.Parallel()
s := newTestState()
err := Parse(s.root, []string{"nested", "sub", "--dry-run"})
require.Error(t, err)
require.ErrorContains(t, err, "flag provided but not defined")
})
t.Run("empty name in subcommand", func(t *testing.T) {
t.Parallel()
s := newTestState()
s.sub.Name = ""
err := Parse(s.root, nil)
require.Error(t, err)
require.ErrorContains(t, err, `subcommand in path [todo, nested] has no name`)
})
t.Run("required flag", func(t *testing.T) {
t.Parallel()
{
s := newTestState()
err := Parse(s.root, []string{"nested", "hello"})
require.Error(t, err)
require.ErrorContains(t, err, `command "todo nested hello": required flags "-mandatory-flag, -another-mandatory-flag" not set`)
}
{
// Correct type - true
s := newTestState()
err := Parse(s.root, []string{"nested", "hello", "--mandatory-flag=true", "--another-mandatory-flag", "some-value"})
require.NoError(t, err)
cmd := getCommand(t, s.root)
assert.Equal(t, s.hello, cmd)
require.True(t, GetFlag[bool](s.root.state, "mandatory-flag"))
}
{
// Correct type - false
s := newTestState()
err := Parse(s.root, []string{"nested", "hello", "--mandatory-flag=false", "--another-mandatory-flag=some-value"})
require.NoError(t, err)
cmd := s.root.terminal()
assert.Equal(t, s.hello, cmd)
require.False(t, GetFlag[bool](s.root.state, "mandatory-flag"))
}
{
// Incorrect type
s := newTestState()
err := Parse(s.root, []string{"nested", "hello", "--mandatory-flag=not-a-bool"})
require.Error(t, err)
require.ErrorContains(t, err, `command "todo nested hello": invalid boolean value "not-a-bool" for -mandatory-flag: parse error`)
}
})
t.Run("unknown required flag set by cli author", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
FlagOptions: []FlagOption{
{Name: "some-other-flag", Required: true},
},
}
err := Parse(cmd, nil)
require.Error(t, err)
require.ErrorContains(t, err, `flag option references unknown flag "some-other-flag"`)
})
t.Run("space in command name", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
SubCommands: []*Command{
{Name: "sub command"},
},
}
err := Parse(cmd, nil)
require.Error(t, err)
require.ErrorContains(t, err, `failed to parse: command ["root", "sub command"]: name must start with a letter and contain only letters, numbers, dashes (-) or underscores (_)`)
})
t.Run("dash in command name", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
SubCommands: []*Command{
{Name: "sub-command"},
},
}
err := Parse(cmd, nil)
require.NoError(t, err)
})
t.Run("underscore in command name", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
SubCommands: []*Command{
{Name: "sub_command", Exec: func(ctx context.Context, s *State) error { return nil }},
},
}
err := Parse(cmd, []string{"sub_command"})
require.NoError(t, err)
})
t.Run("command name starting with number", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
SubCommands: []*Command{
{Name: "1command"},
},
}
err := Parse(cmd, nil)
require.Error(t, err)
require.ErrorContains(t, err, `name must start with a letter`)
})
t.Run("command name with special characters", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
SubCommands: []*Command{
{Name: "sub@command"},
},
}
err := Parse(cmd, nil)
require.Error(t, err)
require.ErrorContains(t, err, `name must start with a letter and contain only letters, numbers, dashes (-) or underscores (_)`)
})
t.Run("very long command name", func(t *testing.T) {
t.Parallel()
longName := "very-long-command-name-that-exceeds-normal-expectations-and-continues-for-a-while-to-test-edge-cases"
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
SubCommands: []*Command{
{Name: longName, Exec: func(ctx context.Context, s *State) error { return nil }},
},
}
err := Parse(cmd, []string{longName})
require.NoError(t, err)
})
t.Run("empty args list", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{})
require.NoError(t, err)
require.Len(t, cmd.state.Args, 0)
})
t.Run("args with whitespace only", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{" ", "\t", ""})
require.NoError(t, err)
require.Equal(t, []string{" ", "\t", ""}, cmd.state.Args)
})
t.Run("flag with empty value", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.String("config", "", "config file")
}),
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"--config="})
require.NoError(t, err)
require.Equal(t, "", GetFlag[string](cmd.state, "config"))
})
t.Run("boolean flag with explicit false", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.Bool("verbose", true, "verbose mode")
}),
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"--verbose=false"})
require.NoError(t, err)
require.False(t, GetFlag[bool](cmd.state, "verbose"))
})
t.Run("deeply nested command hierarchy", func(t *testing.T) {
t.Parallel()
level5 := &Command{
Name: "level5",
Exec: func(ctx context.Context, s *State) error { return nil },
}
level4 := &Command{
Name: "level4",
SubCommands: []*Command{level5},
}
level3 := &Command{
Name: "level3",
SubCommands: []*Command{level4},
}
level2 := &Command{
Name: "level2",
SubCommands: []*Command{level3},
}
level1 := &Command{
Name: "level1",
SubCommands: []*Command{level2},
}
root := &Command{
Name: "root",
SubCommands: []*Command{level1},
}
err := Parse(root, []string{"level1", "level2", "level3", "level4", "level5"})
require.NoError(t, err)
terminal := root.terminal()
require.Equal(t, level5, terminal)
})
t.Run("many subcommands", func(t *testing.T) {
t.Parallel()
var subcommands []*Command
for i := 0; i < 25; i++ {
subcommands = append(subcommands, &Command{
Name: "cmd" + string(rune('a'+i%26)),
Exec: func(ctx context.Context, s *State) error { return nil },
})
}
root := &Command{
Name: "root",
SubCommands: subcommands,
}
err := Parse(root, []string{"cmda"})
require.NoError(t, err)
terminal := root.terminal()
require.Equal(t, "cmda", terminal.Name)
})
t.Run("duplicate subcommand names", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
SubCommands: []*Command{
{Name: "duplicate", Exec: func(ctx context.Context, s *State) error { return nil }},
{Name: "duplicate", Exec: func(ctx context.Context, s *State) error { return nil }},
},
}
// This library may not check for duplicate names, so just verify it works
err := Parse(cmd, []string{"duplicate"})
require.NoError(t, err)
// Just ensure it doesn't crash and can parse the first match
})
t.Run("flag option for non-existent flag", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.String("existing", "", "existing flag")
}),
FlagOptions: []FlagOption{
{Name: "existing", Required: true},
{Name: "nonexistent", Required: true},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"--existing=value"})
require.Error(t, err)
require.ErrorContains(t, err, `flag option references unknown flag "nonexistent"`)
})
t.Run("args with special characters", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
}
specialArgs := []string{"file with spaces.txt", "file@symbol.txt", "file\"quote.txt", "file'apostrophe.txt"}
err := Parse(cmd, specialArgs)
require.NoError(t, err)
require.Equal(t, specialArgs, cmd.state.Args)
})
t.Run("very long argument list", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Exec: func(ctx context.Context, s *State) error { return nil },
}
var longArgList []string
for i := 0; i < 100; i++ {
longArgList = append(longArgList, "arg"+string(rune('0'+i%10)))
}
err := Parse(cmd, longArgList)
require.NoError(t, err)
require.Equal(t, longArgList, cmd.state.Args)
})
t.Run("positional arg matching command name", func(t *testing.T) {
t.Parallel()
add := &Command{
Name: "add",
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "mycli",
SubCommands: []*Command{add},
}
err := Parse(root, []string{"add", "add"})
require.NoError(t, err)
assert.Equal(t, add, getCommand(t, root))
// The second "add" is a positional arg, not a command traversal.
assert.Equal(t, []string{"add"}, root.state.Args)
})
t.Run("ancestor flag value not treated as command", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Exec: func(ctx context.Context, s *State) error { return nil },
}
parent := &Command{
Name: "parent",
SubCommands: []*Command{child},
}
root := &Command{
Name: "mycli",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.String("output", "", "output file")
}),
SubCommands: []*Command{parent},
}
// Root flag --output used between parent and child: the value "foo" should be skipped
// during command resolution, not treated as an unknown command.
err := Parse(root, []string{"parent", "--output", "foo", "child"})
require.NoError(t, err, "ancestor flag value should not be treated as unknown command")
assert.Equal(t, child, getCommand(t, root))
assert.Equal(t, "foo", GetFlag[string](root.state, "output"))
})
t.Run("required flag set to default value", func(t *testing.T) {
t.Parallel()
root := &Command{
Name: "mycli",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.String("port", "8080", "port number")
}),
FlagOptions: []FlagOption{
{Name: "port", Required: true},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// Explicitly passing the default value should satisfy the required check.
err := Parse(root, []string{"--port", "8080"})
require.NoError(t, err, "explicitly setting required flag to its default value should not fail")
assert.Equal(t, "8080", GetFlag[string](root.state, "port"))
})
t.Run("required bool flag prefix match not too broad", func(t *testing.T) {
t.Parallel()
root := &Command{
Name: "mycli",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("force", false, "force operation")
f.Bool("force-all", false, "force all")
}),
FlagOptions: []FlagOption{
{Name: "force", Required: true},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// --force-all should NOT satisfy the required --force flag.
err := Parse(root, []string{"--force-all"})
require.Error(t, err, "--force-all should not satisfy required --force")
assert.Contains(t, err.Error(), "required flag")
})
t.Run("mixed flags and args in various orders", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(fset *flag.FlagSet) {
fset.String("flag1", "", "first flag")
fset.String("flag2", "", "second flag")
}),
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"arg1", "--flag1=val1", "arg2", "--flag2", "val2", "arg3"})
require.NoError(t, err)
require.Equal(t, "val1", GetFlag[string](cmd.state, "flag1"))
require.Equal(t, "val2", GetFlag[string](cmd.state, "flag2"))
require.Equal(t, []string{"arg1", "arg2", "arg3"}, cmd.state.Args)
})
}
func TestShortFlags(t *testing.T) {
t.Parallel()
t.Run("short flag sets value", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
f.String("output", "", "output file")
}),
FlagOptions: []FlagOption{
{Name: "verbose", Short: "v"},
{Name: "output", Short: "o"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"-v", "-o", "file.txt"})
require.NoError(t, err)
require.True(t, GetFlag[bool](cmd.state, "verbose"))
require.Equal(t, "file.txt", GetFlag[string](cmd.state, "output"))
})
t.Run("long flag still works with short alias defined", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "verbose", Short: "v"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{"-verbose"})
require.NoError(t, err)
require.True(t, GetFlag[bool](cmd.state, "verbose"))
})
t.Run("short flag with subcommand", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.String("name", "", "the name")
}),
FlagOptions: []FlagOption{
{Name: "name", Short: "n"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "verbose")
}),
FlagOptions: []FlagOption{
{Name: "verbose", Short: "v"},
},
SubCommands: []*Command{child},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(root, []string{"-v", "child", "-n", "hello"})
require.NoError(t, err)
require.True(t, GetFlag[bool](root.state, "verbose"))
require.Equal(t, "hello", GetFlag[string](root.state, "name"))
})
t.Run("short and long flags are aliases sharing same value", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Int("count", 0, "number of items")
}),
FlagOptions: []FlagOption{
{Name: "count", Short: "c"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// Use short flag
err := Parse(cmd, []string{"-c", "42"})
require.NoError(t, err)
// Both short and long name should return the same value
require.Equal(t, 42, GetFlag[int](cmd.state, "count"))
})
t.Run("option references unknown flag", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "vrbose", Short: "v"}, // typo in Name
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{})
require.Error(t, err)
require.Contains(t, err.Error(), `flag option references unknown flag "vrbose"`)
})
t.Run("short alias must be single ASCII letter", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "verbose", Short: "vv"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{})
require.Error(t, err)
require.Contains(t, err.Error(), "short alias must be a single ASCII letter")
})
t.Run("duplicate short alias", func(t *testing.T) {
t.Parallel()
cmd := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("verbose", false, "enable verbose output")
f.Bool("version", false, "show version")
}),
FlagOptions: []FlagOption{
{Name: "verbose", Short: "v"},
{Name: "version", Short: "v"},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(cmd, []string{})
require.Error(t, err)
require.Contains(t, err.Error(), `duplicate short flag "v"`)
})
}
func TestLocalFlags(t *testing.T) {
t.Parallel()
t.Run("local flag on parent not available to child", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("version", false, "show version")
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "version", Local: true},
},
SubCommands: []*Command{child},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// --version on child should fail because it's local to root
err := Parse(root, []string{"child", "--version"})
require.Error(t, err)
require.ErrorContains(t, err, "flag provided but not defined")
// --verbose on child should still work (not local)
root2 := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("version", false, "show version")
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "version", Local: true},
},
SubCommands: []*Command{{
Name: "child",
Exec: func(ctx context.Context, s *State) error { return nil },
}},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err = Parse(root2, []string{"child", "--verbose"})
require.NoError(t, err)
assert.True(t, GetFlag[bool](root2.state, "verbose"))
})
t.Run("local flag works on defining command", func(t *testing.T) {
t.Parallel()
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("version", false, "show version")
}),
FlagOptions: []FlagOption{
{Name: "version", Local: true},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(root, []string{"--version"})
require.NoError(t, err)
assert.True(t, GetFlag[bool](root.state, "version"))
})
t.Run("local required flag only enforced on defining command", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.String("token", "", "auth token")
}),
FlagOptions: []FlagOption{
{Name: "token", Required: true, Local: true},
},
SubCommands: []*Command{child},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// Child command should not require parent's local required flag
err := Parse(root, []string{"child"})
require.NoError(t, err)
// But root command itself should still require it
root2 := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.String("token", "", "auth token")
}),
FlagOptions: []FlagOption{
{Name: "token", Required: true, Local: true},
},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err = Parse(root2, []string{})
require.Error(t, err)
require.ErrorContains(t, err, "required flag")
})
t.Run("usage excludes local parent flags from inherited flags", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("dry-run", false, "dry run mode")
}),
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("version", false, "show version")
f.Bool("verbose", false, "enable verbose output")
}),
FlagOptions: []FlagOption{
{Name: "version", Local: true},
},
SubCommands: []*Command{child},
Exec: func(ctx context.Context, s *State) error { return nil },
}
err := Parse(root, []string{"child", "--help"})
require.ErrorIs(t, err, flag.ErrHelp)
usage := DefaultUsage(root)
// --verbose should appear in inherited flags (not local)
assert.Contains(t, usage, "--verbose")
// --version should NOT appear (local to root, not inherited)
assert.NotContains(t, usage, "--version")
// --dry-run should appear in local flags
assert.Contains(t, usage, "--dry-run")
})
t.Run("local flag with short alias not inherited", func(t *testing.T) {
t.Parallel()
child := &Command{
Name: "child",
Exec: func(ctx context.Context, s *State) error { return nil },
}
root := &Command{
Name: "root",
Flags: FlagsFunc(func(f *flag.FlagSet) {
f.Bool("version", false, "show version")
}),
FlagOptions: []FlagOption{
{Name: "version", Short: "V", Local: true},
},
SubCommands: []*Command{child},
Exec: func(ctx context.Context, s *State) error { return nil },
}
// Short alias -V should also not work on child
err := Parse(root, []string{"child", "-V"})
require.Error(t, err)
require.ErrorContains(t, err, "flag provided but not defined")
})
}
func getCommand(t *testing.T, c *Command) *Command {
require.NotNil(t, c)
require.NotNil(t, c.state)
require.NotEmpty(t, c.state.path)