-
Notifications
You must be signed in to change notification settings - Fork 8
/
parser.go
904 lines (730 loc) · 16.4 KB
/
parser.go
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
package cli
import (
"errors"
"fmt"
"strconv"
"time"
)
var (
ErrDuplicate = errors.New("duplicate")
ErrMissingName = errors.New("missing name")
ErrInvalidName = errors.New("invalid name")
ErrNotProvided = errors.New("not provided")
ErrRequiredAfterOptional = errors.New("required after optional")
ErrArgAfterRest = errors.New("arg after rest")
ErrUnknown = errors.New("unknown")
)
type ParseArgError struct {
Arg string
Index int
Err error
}
func (e *ParseArgError) Error() string {
msg := "unknown error"
if e.Err != nil {
msg = e.Err.Error()
}
return fmt.Sprintf("cli: parse arg error: %s arg '%s': %s", nthNumber(e.Index), e.Arg, msg)
}
func (e *ParseArgError) Unwrap() error { return e.Err }
func (e *ParseArgError) Is(err error) bool {
pe, ok := err.(*ParseArgError)
return ok && pe.Arg == e.Arg && pe.Index == e.Index && errors.Is(pe.Err, e.Err)
}
func nthNumber(n int) string {
if n < 0 {
return ""
}
n += 1
switch n {
case 1:
return "1st"
case 2:
return "2nd"
case 3:
return "3rd"
default:
return strconv.Itoa(n) + "th"
}
}
type ParseFlagError struct {
Name string
Err error
}
func (e *ParseFlagError) Error() string {
msg := "unknown error"
if e.Err != nil {
msg = e.Err.Error()
}
return fmt.Sprintf("cli: parse flag error: '%s': %s", e.Name, msg)
}
func (e *ParseFlagError) Unwrap() error { return e.Err }
func (e *ParseFlagError) Is(err error) bool {
pe, ok := err.(*ParseFlagError)
return ok && pe.Name == e.Name && errors.Is(pe.Err, e.Err)
}
type FlagError struct {
Short string
Long string
Err error
}
func (e *FlagError) Error() string {
name := e.Short
if e.Long != "" {
if name != "" {
name += "' '"
}
name += e.Long
}
msg := "unknown error"
if e.Err != nil {
msg = e.Err.Error()
}
if name == "" {
return fmt.Sprintf("cli: flag error: %s", msg)
}
return fmt.Sprintf("cli: flag error: '%s': %s", name, msg)
}
func (e *FlagError) Is(err error) bool {
pe, ok := err.(*FlagError)
return ok && pe.Short == e.Short && pe.Long == e.Long && errors.Is(pe.Err, e.Err)
}
type ArgError struct {
Name string
Index int
Err error
}
func (e *ArgError) Error() string {
msg := "unknown error"
if e.Err != nil {
msg = e.Err.Error()
}
if e.Name == "" {
return fmt.Sprintf("cli: arg error: %s arg: %s", nthNumber(e.Index), msg)
}
return fmt.Sprintf("cli: arg error: %s arg '%s': %s", nthNumber(e.Index), e.Name, msg)
}
func (e *ArgError) Is(err error) bool {
pe, ok := err.(*ArgError)
return ok && pe.Name == e.Name && pe.Index == e.Index && errors.Is(pe.Err, e.Err)
}
type RestArgsError struct {
Name string
Err error
}
func (e *RestArgsError) Error() string {
msg := "unknown error"
if e.Err != nil {
msg = e.Err.Error()
}
if e.Name == "" {
return fmt.Sprintf("cli: rest args error: %s", msg)
}
return fmt.Sprintf("cli: rest args error: '%s': %s", e.Name, msg)
}
func (e *RestArgsError) Is(err error) bool {
pe, ok := err.(*RestArgsError)
return ok && pe.Name == e.Name && errors.Is(pe.Err, e.Err)
}
type Register interface {
RegisterFlag(flag Flag) error
RegisterArg(arg Arg) error
RegisterRestArgs(rest RestArgs) error
Arg(i int) (*Arg, bool)
ShortFlag(name string) (*Flag, bool)
LongFlag(name string) (*Flag, bool)
Args() []Arg
Rest() *RestArgs
Flags() []Flag
Err() error
}
var _ Register = (*DefaultRegister)(nil)
type DefaultRegister struct {
flags flags
args args
rest RestArgs // Other arguments (without named args).
lastArgOptional bool // Is last arg optional.
registerFlagErr error // RegisterFlag first error.
registerArgErr error // RegisterArg first error.
registerRestArgsErr error // RegisterRestArgs first error.
}
func (r *DefaultRegister) RegisterFlag(flag Flag) (err error) {
defer func() {
if err != nil && r.registerFlagErr == nil {
r.registerFlagErr = err
}
}()
// Check if short of long net is set.
if flag.Short == "" && flag.Long == "" {
return &FlagError{Err: ErrMissingName}
}
// Validate short flag.
if flag.Short != "" {
if !validShortFlag(flag.Short) {
return &FlagError{
Short: flag.Short,
Long: flag.Long,
Err: ErrInvalidName,
}
}
}
// Validate long flag.
if flag.Long != "" {
if !validLongFlag(flag.Long) {
return &FlagError{
Short: flag.Short,
Long: flag.Long,
Err: ErrInvalidName,
}
}
}
if _, _, ok := r.flags.Find(flag.Long, flag.Short); ok {
return &FlagError{
Long: flag.Long,
Short: flag.Short,
Err: ErrDuplicate,
}
}
r.flags.Add(flag)
return nil
}
func validShortFlag(name string) bool {
if len(name) != 1 {
return false
}
if name[0] == '-' || name[0] == '=' || name[0] == ' ' || name[0] == ',' {
return false
}
return true
}
func validLongFlag(name string) bool {
if len(name) < 1 {
return false
}
if name[0] == '-' || name[0] == '=' || name[0] == ' ' || name[0] == ',' {
return false
}
// We need to iterate by bytes not by runes.
var foundValid bool
for i := 1; i < len(name); i++ {
c := name[i]
if !foundValid && c == '-' {
return false
}
if c == '=' || c == ' ' || c == ',' {
return false
}
foundValid = true
}
return true
}
func (r *DefaultRegister) RegisterArg(arg Arg) (err error) {
defer func() {
if err != nil && r.registerArgErr == nil {
r.registerArgErr = err
}
}()
if arg.Required() {
if r.lastArgOptional {
return &ArgError{
Name: arg.Name,
Err: ErrRequiredAfterOptional,
}
}
} else {
r.lastArgOptional = true
}
if !r.rest.IsZero() {
return &ArgError{
Name: arg.Name,
Err: ErrArgAfterRest,
}
}
if arg.Name == "" {
return &ArgError{Err: ErrMissingName}
}
if !validArg(arg.Name) {
return &ArgError{
Name: arg.Name,
Err: ErrInvalidName,
}
}
if _, _, ok := r.args.Get(arg.Name); ok {
return &ArgError{
Name: arg.Name,
Err: ErrDuplicate,
}
}
r.args.Add(arg)
return nil
}
func validArg(name string) bool {
if len(name) < 1 {
return false
}
if name[0] == '-' || name[0] == '=' || name[0] == ' ' || name[0] == ',' {
return false
}
// We need to iterate by bytes not by runes.
var foundValid bool
for i := 1; i < len(name); i++ {
c := name[i]
if !foundValid && c == '-' {
return false
}
if c == '=' || c == ' ' || c == ',' {
return false
}
foundValid = true
}
return true
}
func (r *DefaultRegister) RegisterRestArgs(rest RestArgs) (err error) {
defer func() {
if err != nil && r.registerRestArgsErr == nil {
r.registerRestArgsErr = err
}
}()
if rest.Name == "" {
return &RestArgsError{Err: ErrMissingName}
}
if !validRestArgs(rest.Name) {
return &RestArgsError{
Name: rest.Name,
Err: ErrInvalidName,
}
}
if !r.rest.IsZero() {
return &RestArgsError{
Name: rest.Name,
Err: ErrDuplicate,
}
}
r.rest = rest
return nil
}
func validRestArgs(name string) bool {
return validArg(name)
}
func (r *DefaultRegister) Arg(i int) (*Arg, bool) {
a, ok := r.args.Nth(i)
return a, ok
}
func (r *DefaultRegister) ShortFlag(name string) (*Flag, bool) {
_, f, ok := r.flags.ShortFlag(name)
return f, ok
}
func (r *DefaultRegister) LongFlag(name string) (*Flag, bool) {
_, f, ok := r.flags.LongFlag(name)
return f, ok
}
func (r *DefaultRegister) Args() []Arg {
return r.args.data
}
func (r *DefaultRegister) Rest() *RestArgs {
if r.rest.IsZero() {
return nil
}
return &r.rest
}
func (r *DefaultRegister) Flags() []Flag {
return r.flags.data
}
func (r *DefaultRegister) Err() error {
if r.registerFlagErr != nil {
return r.registerFlagErr
}
if r.registerArgErr != nil {
return r.registerArgErr
}
if r.registerRestArgsErr != nil {
return r.registerRestArgsErr
}
return nil
}
type Commander interface {
IsCommand(name string) bool
SetCommand(name string) (Register, error)
}
type flags struct {
data []Flag
set []bool // Markers if flags were set.
long map[string]int // Indexes of flags in the data. It contains all long names.
short map[string]int // Indexes of flags in the data. It contains all short names.
}
func (f *flags) LongFlag(name string) (idx int, flag *Flag, ok bool) {
idx, ok = f.long[name]
if ok {
flag = &f.data[idx]
}
return
}
func (f *flags) ShortFlag(name string) (idx int, flag *Flag, ok bool) {
idx, ok = f.short[name]
if ok {
flag = &f.data[idx]
}
return
}
func (f *flags) Find(long, short string) (idx int, flag *Flag, ok bool) {
if long != "" {
if idx, ok = f.long[long]; ok {
flag = &f.data[idx]
return
}
}
if short != "" {
if idx, ok = f.short[short]; ok {
flag = &f.data[idx]
return
}
}
return
}
func (f *flags) Add(flag Flag) {
// NOTE(SuperPaintman):
// The first version of "Add" could override the previous flags
// but it makes API more complex and confusing when we override only
// short or long form.
//
// Especially when we override short form of one flag and long form of
// another.
// Append a new flag.
f.data = append(f.data, flag)
f.set = append(f.set, false)
idx := len(f.data) - 1
if flag.Long != "" {
if f.long == nil {
f.long = make(map[string]int)
}
f.long[flag.Long] = idx
}
if flag.Short != "" {
if f.short == nil {
f.short = make(map[string]int)
}
f.short[flag.Short] = idx
}
}
func (f *flags) Reset() {
f.data = f.data[:0]
f.set = f.set[:0]
f.long = nil
f.short = nil
}
type args struct {
data []Arg
set []bool // Markers if args were set.
index map[string]int // Indexes of named arg in the data.
}
func (a *args) Get(name string) (idx int, arg *Arg, ok bool) {
idx, ok = a.index[name]
if ok {
arg = &a.data[idx]
}
return
}
func (a *args) Nth(i int) (arg *Arg, ok bool) {
if i >= len(a.data) {
return
}
return &a.data[i], true
}
func (a *args) Add(arg Arg) {
// NOTE(SuperPaintman): see flags.Add for information about overriding.
// Append a new arg.
a.data = append(a.data, arg)
a.set = append(a.set, false)
idx := len(a.data) - 1
if a.index == nil {
a.index = make(map[string]int)
}
a.index[arg.Name] = idx
}
func (a *args) Reset() {
a.data = a.data[:0]
a.set = a.set[:0]
a.index = nil
}
type Parser interface {
Parse(commander Commander, r Register, arguments []string) error
FormatLongFlag(name string) string
FormatShortFlag(name string) string
}
var _ Parser = (*DefaultParser)(nil)
type DefaultParser struct {
Universal bool
IgnoreUnknownFlags bool
IgnoreUnknownArgs bool
DisablePosixStyle bool
DisableInlineValue bool
// TODO(SuperPaitnamn): allow access to the unknown flags.
// unknown []string // Unknown flags (without named flags).
}
func (p *DefaultParser) Parse(commander Commander, r Register, arguments []string) error {
// If user has ignored errors return them here.
if err := r.Err(); err != nil {
return err
}
var (
argMode bool
argIdx int
flagsTerminated bool
foundCommandFlag bool
)
for {
if len(arguments) == 0 {
break
}
arg := arguments[0]
arguments = arguments[1:]
// Commands or Args.
if len(arg) == 0 || flagsTerminated || arg[0] != '-' || arg == "-" || isNumber(arg) || isDuration(arg) {
// Check if the arg is a command.
if !argMode && commander != nil && commander.IsCommand(arg) {
register, err := commander.SetCommand(arg)
if err != nil {
return err
}
r = register
continue
}
// Parse rest as args.
argMode = true
a, ok := r.Arg(argIdx)
if ok {
if err := a.Value.Set(arg); err != nil {
return &ArgError{
Name: a.Name,
Index: argIdx,
Err: err,
}
}
a.MarkSet()
} else {
rest := r.Rest()
if rest == nil {
if p.IgnoreUnknownArgs {
argIdx++
continue
}
return &ParseArgError{
Arg: arg,
Index: argIdx,
Err: ErrUnknown,
}
}
if err := rest.Add(arg); err != nil {
return &ArgError{
Name: rest.Name,
Index: argIdx,
Err: err,
}
}
}
argIdx++
continue
}
// Flags.
numMinuses := 1
if arg[1] == '-' {
numMinuses++
// "--" terminates the flags.
if len(arg) == 2 {
flagsTerminated = true
continue
}
}
shortFlag := numMinuses == 1 && !p.Universal
name := arg[numMinuses:]
if len(name) == 0 || name[0] == '-' || name[0] == '=' || name[0] == ' ' || name[0] == ',' {
return &ParseFlagError{
Name: name,
Err: ErrSyntax,
}
}
// Find a value.
var (
value string
hasValue bool
)
// Equals cannot be first.
for i := 1; i < len(name); i++ {
if name[i] == '=' {
value = name[i+1:]
hasValue = true
name = name[0:i]
break
}
}
// Find a known flag.
restName := name
prevHasValue := hasValue
prevValue := value
for len(restName) > 0 {
var (
flag *Flag
knownflag bool
lastShortFlag bool
)
if shortFlag {
originalName := name
name = restName[:1]
restName = restName[1:]
if len(restName) == 0 {
hasValue = prevHasValue
value = prevValue
lastShortFlag = true
} else {
hasValue = false
value = ""
}
flag, knownflag = r.ShortFlag(name)
if knownflag {
// Parse Short-flag+parameter combining (-a parm -> -aparm).
if _, ok := flag.Value.(boolFlag); !ok && !p.DisableInlineValue && len(restName) > 0 {
hasValue = true
value = restName
restName = ""
// Flag had value after "=".
if prevHasValue {
value += "=" + prevValue
}
}
// Parse POSIX-style short flag combining (-a -b -> -ab).
if p.DisablePosixStyle && len(restName) != 0 {
knownflag = false
name = originalName
}
}
} else {
restName = ""
flag, knownflag = r.LongFlag(name)
if !knownflag && p.Universal {
flag, knownflag = r.ShortFlag(name)
}
}
if !knownflag {
if p.IgnoreUnknownFlags {
continue
}
var fullName string
if shortFlag {
fullName = p.FormatShortFlag(name)
} else {
fullName = p.FormatLongFlag(name)
}
return &ParseFlagError{
Name: fullName,
Err: ErrUnknown,
}
}
if (!shortFlag || lastShortFlag) && !hasValue && len(arguments) > 0 {
next := arguments[0]
var setValue bool
if len(next) == 0 {
// Special case for empty string flags.
if fv, ok := flag.Value.(stringFlag); ok && fv.IsStringFlag() {
setValue = true
}
} else if len(next) > 0 && (next[0] != '-' || next == "-" || isNumber(next) || isDuration(next)) {
// Special case for bool flags. Allow only bool-like values.
if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() {
setValue = isBoolValue(next)
} else {
setValue = true
}
}
if setValue {
value = next
hasValue = true
arguments = arguments[1:]
}
}
// Set Value.
// Special case for bool flags which doesn't need a value.
if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() {
if !hasValue {
value = "true"
} else if value == "" {
value = "false"
}
}
if err := flag.Value.Set(value); err != nil {
return &FlagError{
Short: flag.Short,
Long: flag.Long,
Err: err,
}
}
if flag.commandFlag {
foundCommandFlag = true
}
// Mark the flag as set.
flag.MarkSet()
}
}
// Don't chec required flags and args if we in "command flag" mode.
if foundCommandFlag {
return nil
}
// Check required flags.
flags := r.Flags()
for i := range flags {
flag := &flags[i]
if !flag.Set() && flag.Required() {
return &FlagError{
Short: flag.Short,
Long: flag.Long,
Err: ErrNotProvided,
}
}
}
// Check required args.
args := r.Args()
for i := range args {
arg := &args[i]
if !arg.Set() && arg.Required() {
return &ArgError{
Name: arg.Name,
Err: ErrNotProvided,
}
}
}
return nil
}
func (p *DefaultParser) FormatLongFlag(name string) string {
if name == "" {
return ""
}
if p.Universal {
return "-" + name
}
return "--" + name
}
func (p *DefaultParser) FormatShortFlag(name string) string {
if name == "" {
return ""
}
return "-" + name
}
func isNumber(s string) bool {
// TODO(SuperPaintman): optimize it.
if _, err := strconv.ParseInt(s, 0, 0); err == nil {
return true
}
if _, err := strconv.ParseFloat(s, 64); err == nil {
return true
}
if _, err := strconv.ParseUint(s, 0, 0); err == nil {
return true
}
return false
}
func isDuration(s string) bool {
// TODO(SuperPaintman): optimize it.
if _, err := time.ParseDuration(s); err == nil {
return true
}
return false
}