-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_test.go
More file actions
778 lines (719 loc) · 18.7 KB
/
parser_test.go
File metadata and controls
778 lines (719 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
package verbs
import (
"fmt"
"strconv"
"strings"
"testing"
)
func setupGitCLI() *CLI {
var gitAddCommand = Command{
Name: "add|stage",
Summary: "Add files to staging area",
Tag: "add",
Options: []*Option{
{
Name: "f|force",
Description: "Allow adding otherwise " +
"ignored files.",
Tag: "force",
},
},
Args: []*Arg{
{
Name: "<path>",
Occurrence: ZeroOrMore,
Tag: "path",
},
},
}
var gitCommitCommand = Command{
Name: "commit",
Summary: "Record changes to the repository",
Tag: "commit",
Options: []*Option{
{
Name: "m|message",
Param: "<msg>",
Description: "Use <msg> as the commit message.",
Tag: "message",
},
{
Name: "amend",
Description: "Amend the tip of the " +
"current branch.",
Tag: "amend",
},
},
}
var gitRemoteAddCommand = Command{
Name: "add",
Summary: "Add a remote repository",
Tag: "remote-add",
Options: []*Option{
{
Name: "f",
Description: "Run fetch immediately after " +
"the remote information is set up.",
Tag: "fetch-immediately",
},
},
Args: []*Arg{
{
Name: "NAME",
Occurrence: Required,
Tag: "name",
},
{
Name: "URL",
Occurrence: Required,
Tag: "url",
},
},
}
return &CLI{
ProgramName: "git",
Summary: "Search for patterns in files",
OptionResolution: Scoped,
Namespaces: []*Namespace{
{
Name: "remote",
Commands: []*Command{&gitRemoteAddCommand},
},
},
Commands: []*Command{
&gitAddCommand,
&gitCommitCommand,
},
Options: []*Option{
{
Name: "work-tree",
Param: "<path>",
},
},
}
}
func setupGrepCLI() *CLI {
return &CLI{
ProgramName: "grep",
Summary: "Search for patterns in files",
Description: "grep searches for patterns in " +
"files and prints matching lines.",
Options: []*Option{
{
Name: "i|ignore-case",
Description: "Ignore case",
Tag: "ignore-case",
},
{
Name: "v|invert-match",
Description: "Invert match",
Tag: "invert",
},
{
Name: "c|count",
Param: "N",
Description: "Count",
Tag: "count",
},
},
Args: []*Arg{
{
Name: "PATTERN",
Occurrence: Required,
Description: "The pattern to search for",
Tag: "pattern",
},
{
Name: "FILE",
Occurrence: ZeroOrMore,
Description: "Files to search",
Tag: "file",
},
},
}
}
func interceptErrors(cli *CLI) *string {
errorMessage := new(string)
cli.OnError = func(err error) {
*errorMessage = err.Error()
}
return errorMessage
}
func expectError(t *testing.T, errorMessage, expectedError string) {
if errorMessage != expectedError {
t.Errorf("Expected the error message to be \"%s\", "+
"got \"%s\"", expectedError, errorMessage)
}
}
func expectPanic(t *testing.T, v string) {
if r := recover(); r != nil {
if r != v {
t.Errorf("Expected panic \"%v\", got \"%v\"", v, r)
}
} else {
t.Errorf("Expected panic \"%v\" but there was no panic", v)
}
}
func TestConfigValidation(t *testing.T) {
t.Run("namespace-command name conflict", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Commands = append(invalidCLI.Commands,
&Command{Name: "remote"})
defer expectPanic(t, "remote: name conflict")
NewParser(invalidCLI)
})
t.Run("duplicate command names", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Namespaces[0].Commands = append(
invalidCLI.Namespaces[0].Commands,
&Command{Name: "add"})
defer expectPanic(t, "remote add: name conflict")
NewParser(invalidCLI)
})
t.Run("option name conflict with ancestor", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Options = append(invalidCLI.Options,
&Option{Name: "amend"})
defer expectPanic(t, "commit: the --amend option "+
"conflicts with a previous definition")
NewParser(invalidCLI)
})
t.Run("option name conflict with sibling", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.OptionResolution = Global
defer expectPanic(t, "add|stage: the -f option "+
"conflicts with a previous definition")
NewParser(invalidCLI)
})
for _, o := range []Occurrence{Optional, OneOrMore, ZeroOrMore} {
t.Run(fmt.Sprintf(
"ambiguity check %d", o), func(t *testing.T) {
invalidCLI := setupGitCLI()
for _, command := range invalidCLI.Commands {
if command.Tag == "add" {
command.Args =
append(command.Args, &Arg{
Name: "<file>",
Occurrence: o,
})
}
}
defer expectPanic(t,
"add|stage: repeatable arg cannot be "+
"followed by optional/repeatable args")
NewParser(invalidCLI)
})
}
t.Run("empty namespace", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Namespaces = append(invalidCLI.Namespaces,
&Namespace{Name: "empty"})
defer expectPanic(t, "empty: empty namespace")
NewParser(invalidCLI)
})
t.Run("help topic name conflict", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.HelpTopics = append(invalidCLI.HelpTopics,
&HelpTopic{Keyword: "add"})
defer expectPanic(t, "help topic 'add' conflicts with "+
"another name in the global scope")
NewParser(invalidCLI)
})
t.Run("global arguments in command-driven mode", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Args = []*Arg{{Name: "FILE"}}
defer expectPanic(t, "global arguments are not allowed "+
"when commands are defined")
NewParser(invalidCLI)
})
t.Run("empty namespace name", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Namespaces = append(invalidCLI.Namespaces,
&Namespace{})
defer expectPanic(t, "namespace name cannot be empty")
NewParser(invalidCLI)
})
t.Run("empty command name", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Commands = append(invalidCLI.Commands, &Command{})
defer expectPanic(t, "command name cannot be empty")
NewParser(invalidCLI)
})
t.Run("empty option name", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Options = append(invalidCLI.Options, &Option{})
defer expectPanic(t, "option name cannot be empty")
NewParser(invalidCLI)
})
t.Run("empty argument name", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.Args = append(invalidCLI.Args, &Arg{})
defer expectPanic(t, "argument name cannot be empty")
NewParser(invalidCLI)
})
t.Run("empty help topic keyword", func(t *testing.T) {
invalidCLI := setupGitCLI()
invalidCLI.HelpTopics = append(invalidCLI.HelpTopics,
&HelpTopic{})
defer expectPanic(t, "help topic keyword cannot be empty")
NewParser(invalidCLI)
})
t.Run("help topics without commands", func(t *testing.T) {
invalidCLI := setupGrepCLI()
invalidCLI.HelpTopics = append(invalidCLI.HelpTopics,
&HelpTopic{Keyword: "tutorial"})
defer expectPanic(t, "help topics are not allowed "+
"when no commands are defined")
NewParser(invalidCLI)
})
}
func TestAdvanceScope(t *testing.T) {
parser := NewParser(setupGitCLI())
ps := newParseState(parser)
ps.advance("add")
func() {
defer expectPanic(t, "attempt to advance scope past a command")
ps.advance("add")
}()
}
func expectTags(t *testing.T, optsAndArgs []*ParsedArg, expectedTags []any) {
if len(optsAndArgs) != len(expectedTags) {
t.Fatalf("Expected %d parsed items, got %d",
len(expectedTags), len(optsAndArgs))
}
for i, expectedTag := range expectedTags {
if optsAndArgs[i].Tag != expectedTag {
t.Errorf("Tag mismatch at index %d: expected %v, "+
"got %v", i, expectedTag,
optsAndArgs[i].Tag)
}
}
}
func expectPositionalArgTagAssignment(
t *testing.T,
argOccurrences []Occurrence,
expectedError string,
expectedTags []any,
) {
var argDefs []*Arg
for i, occurrence := range argOccurrences {
argDefs = append(argDefs, &Arg{Occurrence: occurrence, Tag: i})
}
ps := parseState{scope: &nameScope{argDefs: argDefs}}
var positionalArgIndices []int
for i := range expectedTags {
ps.optsAndArgs = append(ps.optsAndArgs,
&ParsedArg{Value: strconv.Itoa(i)})
positionalArgIndices = append(positionalArgIndices, i)
}
err := ps.resolvePositionalArgs(positionalArgIndices)
if expectedError != "" {
if err == nil {
t.Errorf("Expected error \"%s\", got no error",
expectedError)
} else if !strings.Contains(err.Error(), expectedError) {
t.Errorf("Expected error \"%s\" to contain \"%s\"",
err.Error(), expectedError)
}
} else if err != nil {
t.Errorf("Expected no error, got error \"%s\"",
err.Error())
} else {
expectTags(t, ps.optsAndArgs, expectedTags)
}
}
func TestPositionalArgTagAssignment(t *testing.T) {
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, ZeroOrMore},
"", []any{})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, OneOrMore, Required},
"", []any{0, 1, 1, 1, 2})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required, Optional, Required},
"", []any{1, 3})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required, Optional, Required},
"", []any{0, 1, 3})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required, Optional, ZeroOrMore,
Required, Required}, "", []any{0, 1, 2, 3, 3, 4, 5})
expectPositionalArgTagAssignment(t,
[]Occurrence{},
"too many positional arguments", []any{0, 1})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required, Optional, Required, Required},
"too few positional arguments", []any{1, 3})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required, Optional},
"too many positional arguments", []any{0, 1, 2, 0})
expectPositionalArgTagAssignment(t,
[]Occurrence{Optional, Required},
"too few positional arguments", []any{})
}
func TestArgumentOnlyMode(t *testing.T) {
cli := setupGrepCLI()
// Test basic parsing
args := strings.Split("grep -i -v test file1.txt file2.txt", " ")
parsed := NewParser(cli).Parse(args).OptsAndArgs
if len(parsed) != 5 {
t.Fatalf("Expected 5 parsed items, got %d", len(parsed))
}
// Check options
if parsed[0].Tag != "ignore-case" || parsed[0].Value != "true" {
t.Errorf("Expected ignore-case option, got %v = %s",
parsed[0].Tag, parsed[0].Value)
}
if parsed[1].Tag != "invert" || parsed[1].Value != "true" {
t.Errorf("Expected invert option, got %v = %s",
parsed[1].Tag, parsed[1].Value)
}
// Check positional args
if parsed[2].Tag != "pattern" || parsed[2].Value != "test" {
t.Errorf("Expected pattern arg, got %v = %s",
parsed[2].Tag, parsed[2].Value)
}
if parsed[3].Tag != "file" || parsed[3].Value != "file1.txt" {
t.Errorf("Expected file arg, got %v = %s",
parsed[3].Tag, parsed[3].Value)
}
if parsed[4].Tag != "file" || parsed[4].Value != "file2.txt" {
t.Errorf("Expected file arg, got %v = %s",
parsed[4].Tag, parsed[4].Value)
}
}
func TestCommandDrivenMode(t *testing.T) {
cli := setupGitCLI()
errorMessage := interceptErrors(cli)
parser := NewParser(cli)
t.Run("missing command", func(t *testing.T) {
parser.Parse(strings.Split("git --work-tree subdir", " "))
expectError(t, *errorMessage, "missing command")
*errorMessage = ""
parser.Parse(strings.Split("git --work-tree=subdir", " "))
expectError(t, *errorMessage, "missing command")
})
t.Run("successful command parsing", func(t *testing.T) {
result := parser.Parse(
strings.Split("git add -f file.txt", " "))
cmd, args := result.Command, result.OptsAndArgs
if cmd == nil {
t.Fatal("Expected a command, got nil")
}
if cmd.Tag != "add" {
t.Errorf("Expected 'add' command, got %v", cmd.Tag)
}
if cmd.Token != "add" {
t.Errorf("Expected command name 'add', got %s",
cmd.Token)
}
if len(args) != 2 {
t.Fatalf("Expected 2 parsed items, got %d", len(args))
}
if args[0].Tag != "force" {
t.Errorf("Expected force option, got %v", args[0].Tag)
}
if args[1].Tag != "path" || args[1].Value != "file.txt" {
t.Errorf("Expected file arg, got %v = %s",
args[1].Tag, args[1].Value)
}
})
}
func TestOptionParsing(t *testing.T) {
parser := NewParser(&CLI{
ProgramName: "test",
Options: []*Option{
{
Name: "v|verbose",
Description: "Verbose",
Tag: "verbose",
},
{
Name: "o|output",
Param: "FILE",
Description: "Output file",
Tag: "output",
},
},
})
tests := []struct {
name string
args []string
expected []string // tag=value pairs
}{
{
name: "short boolean",
args: []string{"test", "-v"},
expected: []string{"verbose=true"},
},
{
name: "long boolean",
args: []string{"test", "--verbose"},
expected: []string{"verbose=true"},
},
{
name: "short with param",
args: []string{"test", "-o", "out.txt"},
expected: []string{"output=out.txt"},
},
{
name: "short with param inline",
args: []string{"test", "-oout.txt"},
expected: []string{"output=out.txt"},
},
{
name: "long with param",
args: []string{"test", "--output", "out.txt"},
expected: []string{"output=out.txt"},
},
{
name: "long with param equals",
args: []string{"test", "--output=out.txt"},
expected: []string{"output=out.txt"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parsed := parser.Parse(tt.args).OptsAndArgs
if len(parsed) != len(tt.expected) {
t.Fatalf("Expected %d items, got %d",
len(tt.expected), len(parsed))
}
for i, exp := range tt.expected {
parts := strings.Split(exp, "=")
if parsed[i].Tag != parts[0] {
t.Errorf("Item %d: expected "+
"tag %s, got %v", i,
parts[0], parsed[i].Tag)
}
if parsed[i].Value != parts[1] {
t.Errorf("Item %d: expected "+
"value %s, got %s", i,
parts[1], parsed[i].Value)
}
}
})
}
}
func TestIdenticalOptions(t *testing.T) {
cmd2VerboseOption := &Option{
Name: "v|verbose",
Description: "Cmd2 verbose",
Tag: "verbose",
}
cli := &CLI{
ProgramName: "test",
Commands: []*Command{
{Name: "cmd1", Options: []*Option{{
Name: "v|verbose",
Description: "Cmd1 verbose",
Tag: "verbose",
}}},
{Name: "cmd2", Options: []*Option{
cmd2VerboseOption,
}},
},
}
t.Run("identical options in different commands", func(t *testing.T) {
NewParser(cli)
})
t.Run("namesakes with different tags", func(t *testing.T) {
// Introduce a conflict by changing the tag of the second option
cmd2VerboseOption.Tag = "verbose2"
defer expectPanic(t, "cmd2: the -v option "+
"conflicts with a previous definition")
NewParser(cli)
})
}
func TestPositionalArgs(t *testing.T) {
tests := []struct {
name string
args []*Arg
input []string
expectError bool
expected int
}{
{
name: "required",
args: []*Arg{{
Name: "FILE",
Occurrence: Required,
Tag: "file",
}},
input: []string{"test", "file.txt"},
expectError: false,
expected: 1,
},
{
name: "required missing",
args: []*Arg{{
Name: "FILE",
Occurrence: Required,
Tag: "file",
}},
input: []string{"test"},
expectError: true,
},
{
name: "optional",
args: []*Arg{{
Name: "FILE",
Occurrence: Optional,
Tag: "file",
}},
input: []string{"test"},
expectError: false,
expected: 0,
},
{
name: "one or more",
args: []*Arg{{
Name: "FILE",
Occurrence: OneOrMore,
Tag: "file",
}},
input: []string{"test", "f1", "f2", "f3"},
expectError: false,
expected: 3,
},
{
name: "one or more empty",
args: []*Arg{{
Name: "FILE",
Occurrence: OneOrMore,
Tag: "file",
}},
input: []string{"test"},
expectError: true,
},
{
name: "zero or more",
args: []*Arg{{
Name: "FILE",
Occurrence: ZeroOrMore,
Tag: "file",
}},
input: []string{"test"},
expectError: false,
expected: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var gotError bool
cli := &CLI{
ProgramName: "test",
Args: tt.args,
OnError: func(err error) {
gotError = true
},
}
parsed := NewParser(cli).Parse(tt.input).OptsAndArgs
if tt.expectError {
if !gotError && len(parsed) == 0 {
t.Error("Expected error but " +
"didn't get one")
}
} else {
if gotError {
t.Error("Unexpected error")
}
if len(parsed) != tt.expected {
t.Errorf("Expected %d parsed "+
"items, got %d",
tt.expected, len(parsed))
}
}
})
}
}
func TestNamespaceParsing(t *testing.T) {
cli := setupGitCLI()
args := strings.Split("git remote add origin https://example.com", " ")
result := NewParser(cli).Parse(args)
cmd, parsed := result.Command, result.OptsAndArgs
if cmd == nil {
t.Fatal("Expected a command, got nil")
}
if cmd.Tag != "remote-add" {
t.Errorf("Expected 'remote-add' command, got %v", cmd.Tag)
}
if cmd.Token != "add" {
t.Errorf("Expected command name 'add', got %s", cmd.Token)
}
if len(parsed) != 2 {
t.Fatalf("Expected 2 parsed items, got %d", len(parsed))
}
if parsed[0].Tag != "name" || parsed[0].Value != "origin" {
t.Errorf("Expected name=origin, got %v=%s",
parsed[0].Tag, parsed[0].Value)
}
if parsed[1].Tag != "url" || parsed[1].Value != "https://example.com" {
t.Errorf("Expected url=https://example.com, got %v=%s",
parsed[1].Tag, parsed[1].Value)
}
}
func TestTagDefaults(t *testing.T) {
result := NewParser(&CLI{
ProgramName: "test",
Commands: []*Command{{
Name: "add|append",
Options: []*Option{
{Name: "f|force"},
{Name: "from", Param: "FILE"},
},
Args: []*Arg{
{Name: "FILE", Occurrence: OneOrMore},
},
}},
}).Parse(strings.Split("test add -f "+
"--from=config.txt file1.txt file2.txt", " "))
if result.Command.Tag != "add|append" {
t.Errorf("Expected command tag 'add|append', got %v",
result.Command.Tag)
}
expectTags(t, result.OptsAndArgs,
[]any{"f|force", "from", "FILE", "FILE"})
}
func TestErrorHandling(t *testing.T) {
cli := &CLI{
ProgramName: "test",
Commands: []*Command{
{Name: "cmd", Summary: "A command", Tag: "cmd"},
},
}
errorMessage := interceptErrors(cli)
parser := NewParser(cli)
tests := []struct {
name string
args []string
expectedError string
}{
{
"missing command",
[]string{"test"},
"missing command",
},
{
"unknown command",
[]string{"test", "unknown"},
"unrecognized name 'unknown'",
},
{
"unknown option",
[]string{"test", "cmd", "--unknown"},
"unknown option '--unknown'",
},
{
"unexpected positional argument",
[]string{"test", "cmd", "unexpected"},
"too many positional arguments",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parser.Parse(tt.args)
expectError(t, *errorMessage, tt.expectedError)
})
}
}