-
Notifications
You must be signed in to change notification settings - Fork 2
/
flag.go
962 lines (891 loc) · 22.7 KB
/
flag.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
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
package mcli
import (
"encoding"
"encoding/json"
"flag"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// Modifier represents an option to a flag, it sets the flag to be
// deprecated, hidden, or required. In a `cli` tag, modifiers appears as
// the first segment, starting with a `#` character.
//
// Fow now the following modifiers are available:
//
// D - marks a flag or argument as deprecated, "DEPRECATED" will be showed in help.
// R - marks a flag or argument as required, "REQUIRED" will be showed in help.
// H - marks a flag as hidden, see below for more about hidden flags.
// E - marks an argument read from environment variables, but not command line,
// environment variables will be showed in a separate section in help.
//
// Hidden flags won't be showed in help, except that when a special flag
// "--mcli-show-hidden" is provided.
//
// Modifier `H` shall not be used for an argument, else it panics.
// An argument must be showed in help to tell user how to use the program
// correctly.
//
// Modifier `E` is useful when you want to read an environment variable,
// but don't want user to provide from command line (e.g. password or other secrets).
// Using together with `R` also ensures that the env variable must exist.
//
// Some modifiers cannot be used together, else it panics, e.g.
//
// H & R - a required flag must appear in help to tell user to set it
// D & R - a required flag must not be deprecated, it does not make sense,
// but makes user confused
type Modifier byte
func (m Modifier) apply(f *_flag) {
switch byte(m) {
case 'D':
f.deprecated = true
case 'E':
f.isEnvVar = true
case 'H':
f.hidden = true
case 'R':
f.required = true
}
}
type textValue interface {
encoding.TextMarshaler
encoding.TextUnmarshaler
}
var (
flagGetterTyp = reflect.TypeOf((*flag.Getter)(nil)).Elem()
flagValueTyp = reflect.TypeOf((*flag.Value)(nil)).Elem()
textValueTyp = reflect.TypeOf((*textValue)(nil)).Elem()
)
// _flag implements flag.Value.
type _flag struct {
name string
short string
description string
defValue string
envNames []string
_tags
_value
isEnvVar bool
isGlobal bool
hasDefault bool
deprecated bool
hidden bool
required bool
nonflag bool
}
type _tags struct {
cliTag string
defaultValueTag string
envTag string
}
type _value struct {
rv reflect.Value
}
func (f *_flag) Get() any {
if f.rv.Type().Implements(flagGetterTyp) {
return f.rv.Interface().(flag.Getter).Get()
}
if f.rv.CanAddr() && f.rv.Addr().Type().Implements(flagGetterTyp) {
return f.rv.Addr().Interface().(flag.Getter).Get()
}
if f.rv.Kind() == reflect.Pointer {
if f.rv.Elem().IsValid() {
return f.rv.Elem().Interface()
}
zero := reflect.New(f.rv.Type().Elem()).Elem()
return zero.Interface()
}
return f.rv.Interface()
}
func (f *_flag) String() string {
return formatValue(f.rv)
}
func formatValue(rv reflect.Value) string {
if rv.Kind() == reflect.Ptr && rv.IsNil() {
rv = reflect.New(rv.Type().Elem())
}
if rv.Type().Implements(flagValueTyp) {
return rv.Interface().(flag.Value).String()
}
if rv.CanAddr() && rv.Addr().Type().Implements(flagValueTyp) {
return rv.Addr().Interface().(flag.Value).String()
}
if rv.Type().Implements(textValueTyp) {
b, _ := rv.Interface().(textValue).MarshalText()
return string(b)
}
if rv.CanAddr() && rv.Addr().Type().Implements(textValueTyp) {
b, _ := rv.Addr().Interface().(textValue).MarshalText()
return string(b)
}
if rv.Kind() == reflect.Pointer {
return formatValueOfBasicTypePtr(rv)
}
return formatValueOfBasicType(rv)
}
func formatValueOfBasicTypePtr(rv reflect.Value) string {
if rv.Elem().IsValid() {
return formatValueOfBasicType(rv.Elem())
}
zero := reflect.New(rv.Type().Elem()).Elem()
return formatValueOfBasicType(zero)
}
func formatValueOfBasicType(rv reflect.Value) string {
switch rv.Kind() {
case reflect.Bool:
return strconv.FormatBool(rv.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if rv.Type() == reflect.TypeOf(time.Duration(0)) {
return rv.Interface().(time.Duration).String()
}
return strconv.FormatInt(rv.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(rv.Uint(), 10)
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
case reflect.String:
return rv.String()
case reflect.Slice, reflect.Map:
if rv.Len() == 0 {
return ""
}
b, _ := json.Marshal(rv.Interface())
return string(b)
default:
panic(fmt.Sprintf("mcli: unsupported value type: %v", rv.Type()))
}
}
func (f *_flag) Set(s string) error {
return applyValue(f.rv, s)
}
func applyValue(rv reflect.Value, s string) error {
if s == "" {
return nil
}
if rv.Kind() == reflect.Ptr && rv.IsNil() {
rv.Set(reflect.New(rv.Type().Elem()))
}
if rv.Type().Implements(flagValueTyp) {
return rv.Interface().(flag.Value).Set(s)
}
if rv.CanAddr() && rv.Addr().Type().Implements(flagValueTyp) {
return rv.Addr().Interface().(flag.Value).Set(s)
}
if rv.Type().Implements(textValueTyp) {
return rv.Interface().(textValue).UnmarshalText([]byte(s))
}
if rv.CanAddr() && rv.Addr().Type().Implements(textValueTyp) {
return rv.Addr().Interface().(textValue).UnmarshalText([]byte(s))
}
return applyValueOfBasicType(rv, s)
}
func applyValueOfBasicType(rv reflect.Value, s string) error {
if isSupportedBasicTypePtr(rv.Type()) {
rv.Set(reflect.New(rv.Type().Elem()))
return applyValueOfBasicType(rv.Elem(), s)
}
if isIntegerValue(rv) {
return applyIntegerValue(rv, s)
}
switch rv.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(s)
if err != nil {
return err
}
rv.SetBool(b)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
rv.SetFloat(f)
case reflect.String:
rv.SetString(s)
case reflect.Slice: // []basicType
e := reflect.New(rv.Type().Elem()).Elem()
if err := applyValue(e, s); err != nil {
return err
}
rv.Set(reflect.Append(rv, e))
case reflect.Map: // map[string]basicType
if rv.IsNil() {
rv.Set(reflect.MakeMap(rv.Type()))
}
parts := append(strings.SplitN(s, "=", 2), "")
k := parts[0]
val := reflect.New(rv.Type().Elem()).Elem()
if err := applyValue(val, parts[1]); err != nil {
return err
}
rv.SetMapIndex(reflect.ValueOf(k), val)
default:
panic(fmt.Sprintf("mcli: unsupported value type: %v", rv.Type()))
}
return nil
}
func isIntegerValue(rv reflect.Value) bool {
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return true
}
return false
}
func applyIntegerValue(rv reflect.Value, s string) error {
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var i int64
var d time.Duration
var err error
if rv.Type() == reflect.TypeOf(time.Duration(0)) {
d, err = time.ParseDuration(s)
i = int64(d)
} else {
i, err = strconv.ParseInt(s, 10, 64)
}
if err != nil {
return err
}
rv.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return err
}
rv.SetUint(u)
}
return nil
}
func (f *_flag) isBooleanPtr() bool {
return f.rv.Kind() == reflect.Pointer &&
f.rv.Type().Elem().Kind() == reflect.Bool
}
func (f *_flag) isBoolean() bool {
return f.rv.Kind() == reflect.Bool
}
func (f *_flag) isSlice() bool {
return f.rv.Kind() == reflect.Slice
}
func (f *_flag) isMap() bool {
return f.rv.Kind() == reflect.Map
}
func (f *_flag) isCompositeType() bool {
kind := f.rv.Kind()
return kind == reflect.Slice || kind == reflect.Map
}
func (f *_flag) isString() bool {
return f.rv.Kind() == reflect.String
}
func (f *_flag) isStringPtr() bool {
return f.rv.Kind() == reflect.Pointer &&
f.rv.Type().Elem().Kind() == reflect.String
}
func (f *_flag) isZero() bool {
typ := f.rv.Type()
if isFlagValueImpl(f.rv) {
zero := zeroFlagValueStr(f.rv)
return f.String() == zero
}
if isTextValueImpl(f.rv) {
zero := zeroTextValueStr(f.rv)
return f.String() == zero
}
// Check comparable values.
if typ.Comparable() {
return reflect.Zero(typ).Interface() == f.rv.Interface()
}
// Else it must be a slice or a map.
return f.rv.Len() == 0
}
func (f *_flag) helpName() string {
if f.nonflag {
return fmt.Sprintf("argument '%s'", f.name)
}
return fmt.Sprintf("flag '-%s'", f.name)
}
func (f *_flag) usageName() string {
if f.isBoolean() || f.isBooleanPtr() {
return ""
}
if isFlagValueImpl(f.rv) {
return "value"
}
return usageName(f.rv.Type())
}
func usageName(typ reflect.Type) string {
if isSupportedBasicTypePtr(typ) {
return usageName(typ.Elem())
}
switch typ.Kind() {
case reflect.Bool:
return "bool"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if typ == reflect.TypeOf(time.Duration(0)) {
return "duration"
}
return "int"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "uint"
case reflect.Float32, reflect.Float64:
return "float"
case reflect.String:
return "string"
case reflect.Slice:
elemName := usageName(typ.Elem())
return "[]" + elemName
case reflect.Map:
elemName := usageName(typ.Elem())
return "map[string]" + elemName
default:
return "value"
}
}
func (f *_flag) formatDefaultValueForHelp() string {
str := ""
if f.hasDefault {
if f.isString() || f.isStringPtr() {
str = fmt.Sprintf("[default: %q]", f.defValue)
} else {
str = fmt.Sprintf("[default: %v]", f.defValue)
}
}
return str
}
func (f *_flag) getUsage(hasShortFlag bool) usageItem {
if f.isEnvVar {
return f.getEnvVarUsage()
}
var prefix, description string
var appendixes []string
if f.nonflag {
prefix += " " + f.name
} else if f.short != "" && f.name != "" {
prefix += fmt.Sprintf(" -%s, --%s", f.short, f.name)
} else if len(f.name) == 1 || !hasShortFlag {
prefix += fmt.Sprintf(" -%s", f.name)
} else {
prefix += fmt.Sprintf(" --%s", f.name)
}
name, description := unquoteUsage(f)
if name != "" {
prefix += " " + name
}
var modifiers []string
if f.required {
modifiers = append(modifiers, "REQUIRED")
}
if f.deprecated {
modifiers = append(modifiers, "DEPRECATED")
}
if f.hidden {
modifiers = append(modifiers, "HIDDEN")
}
if len(modifiers) > 0 {
prefix += fmt.Sprintf(" [%s]", strings.Join(modifiers, ", "))
}
if len(f.envNames) > 0 {
envStr := fmt.Sprintf(`[env: "%s"]`, strings.Join(f.envNames, `", "`))
appendixes = append(appendixes, envStr)
}
if dftStr := f.formatDefaultValueForHelp(); dftStr != "" {
appendixes = append(appendixes, dftStr)
}
return usageItem{
prefix: prefix,
description: description,
appendixes: appendixes,
}
}
func (f *_flag) getEnvVarUsage() usageItem {
var prefix, description string
var appendixes []string
envStr := strings.Join(f.envNames, ", ")
prefix += " - " + envStr
name, description := unquoteUsage(f)
if name != "" {
prefix += " " + name
}
if f.required {
prefix += " [REQUIRED]"
}
if dftStr := f.formatDefaultValueForHelp(); dftStr != "" {
appendixes = append(appendixes, dftStr)
}
return usageItem{
prefix: prefix,
description: description,
appendixes: appendixes,
}
}
func unquoteUsage(f *_flag) (name, usage string) {
_markName := func(s string) string {
if s != "" && !strings.HasPrefix(s, "<") {
s = "<" + s + ">"
}
return s
}
usage = f.description
runes := []rune(f.description)
const backQuote = '`'
searchBackQuote:
for i := 0; i < len(runes); i++ {
if runes[i] == backQuote {
for j := i + 1; j < len(runes); j++ {
if runes[j] == backQuote {
name = string(runes[i+1 : j])
usage = string(runes[:i]) + name + string(runes[j+1:])
break searchBackQuote
}
}
break // Only one back quote; use type name.
}
}
if name != "" {
name = _markName(name)
return
}
// Try single quote.
const backSlash = '\\'
const singleQuote = '\''
builder := strings.Builder{}
nextChar:
for i := 0; i < len(runes); i++ {
if name == "" && runes[i] == singleQuote && i > 0 && runes[i-1] != backSlash {
for j := i + 1; j < len(runes); j++ {
if runes[j] == singleQuote {
name = string(runes[i+1 : j])
builder.WriteString(name)
i = j
continue nextChar
}
}
}
if runes[i] == backSlash && i < len(runes)-1 && runes[i+1] == singleQuote {
builder.WriteRune(singleQuote)
i++
continue
}
builder.WriteRune(runes[i])
}
usage = builder.String()
if name == "" {
name = f.usageName()
}
name = _markName(name)
return
}
func (f *_flag) validate() error {
if f.name == "" {
return newProgramingError("cannot parse name from cli tag %q", f.cliTag)
}
if f.hidden && f.nonflag {
return newProgramingError("shall not set an argument to be hidden, %s", f.name)
}
if f.hidden && f.required {
return newProgramingError("modifiers H & R shall not be used together, %s", f.helpName())
}
if f.deprecated && f.required {
return newProgramingError("modifiers D & R shall not be used together, %s", f.helpName())
}
if !isSupportedType(f.rv) {
return newProgramingError("unsupported value type %v for %s", f.rv.Type(), f.helpName())
}
if f.defaultValueTag != "" && !isFlagValueImpl(f.rv) && !isTextValueImpl(f.rv) {
if f.isSlice() {
return newProgramingError("default value is unsupported for slice type, %s", f.helpName())
}
if f.isMap() {
return newProgramingError("default value is unsupported for map type, %s", f.helpName())
}
}
if f.envTag != "" {
if f.isSlice() {
return newProgramingError("env is unsupported for slice type, %s", f.helpName())
}
if f.isMap() {
return newProgramingError("env is unsupported for map type, %s", f.helpName())
}
}
if f.isEnvVar {
if len(f.envNames) == 0 {
return newProgramingError("env name is required for environment variable: %q", f.description)
}
if len(f.envNames) > 1 {
return newProgramingError("environment variable requires exactly one env name, got %d: %v",
len(f.envNames), strings.Join(f.envNames, ", "))
}
}
return nil
}
func parseFlags(isGlobal bool, fs *flag.FlagSet, rv reflect.Value, flagMap map[string]*_flag) (
flags, nonflags, envVars []*_flag, err error,
) {
p := &flagParser{
fs: fs,
flagMap: flagMap,
}
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
ft := rt.Field(i)
fv := rv.Field(i)
cliTag := strings.TrimSpace(ft.Tag.Get("cli"))
if cliTag == "" {
cliTag = strings.TrimSpace(ft.Tag.Get("mcli"))
}
defaultValue := strings.TrimSpace(ft.Tag.Get("default"))
envTag := strings.TrimSpace(ft.Tag.Get("env"))
isGlobalFlag := isGlobal
if ft.Name == "GlobalFlags" && rt == reflect.TypeOf(withGlobalFlagArgs{}) {
isGlobalFlag = true
}
err = p.parseField(ft, fv, isGlobalFlag, cliTag, defaultValue, envTag)
if err != nil {
return nil, nil, nil, err
}
}
if err = p.validateNonflags(); err != nil {
return nil, nil, nil, err
}
p.sortFlags()
return p.flags, p.nonflags, p.envVars, nil
}
type flagParser struct {
fs *flag.FlagSet
flagMap map[string]*_flag
flags []*_flag
nonflags []*_flag
envVars []*_flag
}
func (p *flagParser) appendFlag(f *_flag) {
if f.name != "" {
p.flagMap[f.name] = f
}
if f.short != "" {
p.flagMap[f.short] = f
}
p.flags = append(p.flags, f)
}
func (p *flagParser) addToFlagSet(f *_flag, fv reflect.Value) {
fs := p.fs
if f.isBoolean() {
ptr := fv.Addr().Interface().(*bool)
fs.BoolVar(ptr, f.name, f.rv.Bool(), f.description)
if f.short != "" {
fs.BoolVar(ptr, f.short, f.rv.Bool(), f.description)
}
return
}
if f.isBooleanPtr() {
ptr := new(bool)
fs.BoolVar(ptr, f.name, false, f.description)
if f.short != "" {
fs.BoolVar(ptr, f.short, false, f.description)
}
return
}
fs.Var(f, f.name, f.description)
if f.short != "" {
fs.Var(f, f.short, f.description)
}
}
func (p *flagParser) tidyFieldValue(ft reflect.StructField, fv reflect.Value, cliTag string) (reflect.Value, bool) {
if ft.PkgPath != "" || isIgnoreTag(cliTag) {
return fv, false
}
if fv.IsValid() && fv.Kind() == reflect.Interface {
fv = fv.Elem()
}
if fv.IsValid() && fv.Kind() == reflect.Ptr &&
!fv.IsNil() && fv.Elem().Kind() == reflect.Struct {
fv = fv.Elem()
}
if !fv.IsValid() {
return fv, false
}
return fv, true
}
func (p *flagParser) parseField(
ft reflect.StructField, fv reflect.Value,
isGlobalFlag bool,
cliTag, defaultValue, envTag string,
) error {
fv, ok := p.tidyFieldValue(ft, fv, cliTag)
if !ok {
return nil
}
// Got a struct field, parse it recursively.
if fv.Kind() == reflect.Struct && !isFlagValueImpl(fv) && !isTextValueImpl(fv) {
subFlags, subNonflags, subEnvVars, subErr := parseFlags(isGlobalFlag, p.fs, fv, p.flagMap)
if subErr != nil {
return subErr
}
for _, f := range subFlags {
p.appendFlag(f)
}
p.nonflags = append(p.nonflags, subNonflags...)
p.envVars = append(p.envVars, subEnvVars...)
return nil
}
if cliTag == "" {
return nil
}
// Parse the flag.
var f *_flag
f, err := p.parseFlag(isGlobalFlag, cliTag, defaultValue, envTag, fv)
if err != nil {
return err
}
if f == nil || f.name == "" {
return nil
}
if f.isEnvVar {
p.envVars = append(p.envVars, f)
return nil
}
if f.nonflag {
p.nonflags = append(p.nonflags, f)
return nil
}
p.appendFlag(f)
p.addToFlagSet(f, fv)
return nil
}
var spaceRE = regexp.MustCompile(`\s+`)
func (p *flagParser) parseFlag(isGlobal bool, cliTag, defaultValue, envTag string, rv reflect.Value) (*_flag, error) {
f := &_flag{
_tags: _tags{
cliTag: cliTag,
defaultValueTag: defaultValue,
envTag: envTag,
},
_value: _value{rv},
isGlobal: isGlobal,
}
parseCliTag(f, cliTag)
if f.name == "" {
f.name = f.short
}
if f.short == f.name {
f.short = ""
}
if envTag != "" {
f.envNames = splitByComma(envTag)
}
if err := f.validate(); err != nil {
return nil, err
}
if defaultValue != "" {
err := f.Set(defaultValue)
if err != nil {
return nil, newProgramingError("invalid default value %q for %s: %v", defaultValue, f.helpName(), err)
}
f.defValue = defaultValue
f.hasDefault = !f.isZero()
}
return f, nil
}
func parseCliTag(f *_flag, cliTag string) {
const (
modifier = iota
short
long
description
stop
)
parts := strings.SplitN(cliTag, ",", 4)
st := modifier
for i := 0; i < len(parts) && st < stop; i++ {
p := strings.TrimSpace(parts[i])
switch st {
case modifier:
st = short
if strings.HasPrefix(p, "#") {
for _, x := range p[1:] {
Modifier(x).apply(f)
}
if f.isEnvVar {
st = stop
f.name = "-"
f.description = strings.TrimSpace(strings.Join(parts[i+1:], ","))
}
continue
}
i--
case short:
if strings.HasPrefix(p, "-") {
st = long
p = strings.TrimLeft(p, "-")
if len(p) == 1 {
f.short = p
} else {
i--
}
} else {
st = description
f.nonflag = true
f.name = p
}
case long:
st = description
if strings.HasPrefix(p, "-") {
p = strings.TrimLeft(p, "-")
// Allow split flag name and description by spaces.
sParts := spaceRE.Split(p, 2)
f.name = sParts[0]
newParts := append(parts[:i:i], sParts...)
newParts = append(newParts, parts[i+1:]...)
parts = newParts
continue
}
f.name = f.short
i--
case description:
st = stop
p = strings.TrimSpace(strings.Join(parts[i:], ","))
f.description = p
}
}
}
func (p *flagParser) validateNonflags() error {
var compositeTypeArg *_flag
for _, f := range p.nonflags {
if compositeTypeArg != nil {
return newProgramingError("%s after composite type %s will never get a value, you may define it as a flag", f.helpName(), compositeTypeArg.helpName())
}
if f.isCompositeType() {
compositeTypeArg = f
}
}
return nil
}
func (p *flagParser) sortFlags() {
sort.Slice(p.flags, func(i, j int) bool {
return strings.ToLower(p.flags[i].name) < strings.ToLower(p.flags[j].name)
})
}
func isIgnoreTag(tag string) bool {
parts := strings.Split(tag, ",")
return strings.TrimSpace(parts[0]) == "-"
}
func isSupportedType(rv reflect.Value) bool {
if _, ok := rv.Interface().(bool); ok {
return true
}
if isFlagValueImpl(rv) || isTextValueImpl(rv) {
return true
}
if isSupportedBasicTypePtr(rv.Type()) {
return true
}
if isSupportedBasicType(rv.Kind()) {
return true
}
if rv.Kind() == reflect.Slice && isSupportedBasicType(rv.Type().Elem().Kind()) {
return true
}
if rv.Kind() == reflect.Map &&
rv.Type().Key().Kind() == reflect.String &&
isSupportedBasicType(rv.Type().Elem().Kind()) {
return true
}
return false
}
func isFlagValueImpl(rv reflect.Value) bool {
return rv.Type().Implements(flagValueTyp) ||
(rv.CanAddr() && rv.Addr().Type().Implements(flagValueTyp))
}
func zeroFlagValueStr(rv reflect.Value) string {
typ := rv.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
zero := reflect.New(typ)
zero.Elem().Set(reflect.Zero(typ))
return zero.Interface().(flag.Value).String()
}
func isTextValueImpl(rv reflect.Value) bool {
return rv.Type().Implements(textValueTyp) ||
(rv.CanAddr() && rv.Addr().Type().Implements(textValueTyp))
}
func zeroTextValueStr(rv reflect.Value) string {
typ := rv.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
zero := reflect.New(typ)
zero.Elem().Set(reflect.Zero(typ))
b, _ := zero.Interface().(textValue).MarshalText()
return string(b)
}
func isSupportedBasicTypePtr(typ reflect.Type) bool {
return typ.Kind() == reflect.Pointer && isSupportedBasicType(typ.Elem().Kind())
}
func isSupportedBasicType(kind reflect.Kind) bool {
switch kind {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String:
return true
}
return false
}
func splitByComma(value string) []string {
value = strings.TrimSpace(value)
parts := strings.Split(value, ",")
out := parts[:0]
for _, x := range parts {
x = strings.TrimSpace(x)
if x != "" {
out = append(out, x)
}
}
return out
}
func hasBoolFlag(name string, args []string) bool {
for _, a := range args {
if !strings.HasPrefix(a, "-") || !strings.Contains(a, name) {
continue
}
a = strings.TrimLeft(a, "-")
a = strings.SplitN(a, "=", 2)[0]
if a == name {
return true
}
}
return false
}
func spaceJoin(strList ...string) string {
result := ""
for _, s := range strList {
s = strings.TrimSpace(s)
if result == "" {
result = s
} else {
result += " " + s
}
}
return result
}
func findFlagIndex(cmdArgs []string) int {
flagIdx := len(cmdArgs)
for i, x := range cmdArgs {
if strings.HasPrefix(x, "-") {
flagIdx = i
break
}
}
return flagIdx
}
type usageItem struct {
prefix string
description string
appendixes []string
}