-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd.go
1085 lines (998 loc) · 30.8 KB
/
cmd.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
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 ox
import (
"context"
"fmt"
"io"
"iter"
"os"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/xo/ox/text"
)
// Command is a command.
type Command struct {
// Parent is the command's parent.
Parent *Command
// Exec is the command's exec func.
Exec ExecFunc
// Name is the command's name.
Name string
// Usage is the command's usage.
Usage string
// Aliases are the command's aliases.
Aliases []string
// Suggested are the command's suggested names.
Suggested []string
// Flags are the command's flags.
Flags *FlagSet
// Commands are the command's sub commands.
Commands []*Command
// Args are the command's argument validation func's.
Args []func([]string) error
// OnErr indicates whether to continue, panic, or to error when
// flag/argument parsing fails.
OnErr OnErr
// Help is the command's help emitter.
Help io.WriterTo
// Comp enables completion for the command.
Comp bool
// Section is the help section.
Section int
// Hidden indicates the command is hidden from help output.
Hidden bool
// Deprecated indicates the command is deprecated.
Deprecated bool
// Special is the special value.
Special string
}
// NewCommand creates a new command.
func NewCommand(opts ...Option) (*Command, error) {
cmd := &Command{
Section: -1,
}
if err := Apply(cmd, opts...); err != nil {
return nil, err
}
switch noName := cmd.Name == ""; {
case noName && cmd.Parent == nil:
cmd.Name = filepath.Base(os.Args[0])
case noName:
return nil, fmt.Errorf("command: %w", ErrUsageNotSet)
}
if err := ApplyPost(cmd, opts...); err != nil {
return nil, err
}
return cmd, nil
}
// Sub creates a sub command.
func (cmd *Command) Sub(opts ...Option) error {
sub, err := NewCommand(prepend(opts, Parent(cmd))...)
if err != nil {
return err
}
cmd.Commands = append(cmd.Commands, sub)
return nil
}
// Tree returns the parents for the command.
func (cmd *Command) Tree() []string {
var v []string
for c := cmd; c != nil; c = c.Parent {
v = append(v, c.Name)
}
slices.Reverse(v)
return v
}
// Path returns the execution path for the command.
func (cmd *Command) Path() []string {
return cmd.Tree()[1:]
}
// RootName returns the root name for the command.
func (cmd *Command) RootName() string {
return cmd.Tree()[0]
}
// Suggest returns a [SuggestionError] if there is a matching sub command
// within the command's help distance.
func (cmd *Command) Suggest(args ...string) error {
if len(args) == 0 {
return nil
}
r, maxDist := []rune(strings.ToLower(args[0])), maxDist(cmd)
type suggest struct {
cmd *Command
dist int
}
var suggested []suggest
for _, c := range cmd.Commands {
for _, name := range append(prepend(c.Aliases, c.Name), c.Suggested...) {
if dist := Ldist(r, []rune(strings.ToLower(name))); dist <= maxDist {
suggested = append(suggested, suggest{
cmd: c,
dist: dist,
})
}
}
}
if len(suggested) != 0 {
sort.Slice(suggested, func(i, j int) bool {
return suggested[i].dist < suggested[j].dist
})
return NewSuggestionError(cmd, args[0], suggested[0].cmd)
}
return fmt.Errorf(text.SuggestionErrorMessage, ErrUnknownCommand, args[0], cmd.Name)
}
// Lookup returns the furthest matching command in the command tree.
func (cmd *Command) Lookup(args ...string) *Command {
c := cmd
for _, arg := range args {
if next := c.Command(arg); next != nil {
c = next
continue
}
break
}
return c
}
// Command returns the sub command with the name.
func (cmd *Command) Command(name string) *Command {
for _, c := range cmd.Commands {
if c.Name == name || slices.Contains(c.Aliases, name) {
return c
}
}
return nil
}
// CommandSpecial returns the sub command with the special value.
func (cmd *Command) CommandSpecial(special string) *Command {
for _, c := range cmd.Commands {
if c.Special == special {
return c
}
}
return nil
}
// Flag finds a flag from the command or the command's parents.
func (cmd *Command) Flag(name string, parents, short bool) *Flag {
if cmd.Flags != nil {
if i := slices.IndexFunc(cmd.Flags.Flags, func(g *Flag) bool {
return g.Name == name && !short ||
g.Short == name && short ||
slices.ContainsFunc(g.Aliases, func(s string) bool {
return s == name && len(s) == 1 == short
})
}); i != -1 {
return cmd.Flags.Flags[i]
}
}
if parents && cmd.Parent != nil {
return cmd.Parent.Flag(name, parents, short)
}
return nil
}
// FlagSpecial returns the flag with a special value.
func (cmd *Command) FlagSpecial(special string) *Flag {
if cmd.Flags != nil && len(cmd.Flags.Flags) != 0 {
for _, g := range cmd.Flags.Flags {
if g.Special == special {
return g
}
}
}
return nil
}
// Validate validates the passed args.
func (cmd *Command) Validate(args []string) error {
// validate args
for _, f := range cmd.Args {
if err := f(args); err != nil {
return newCommandError(cmd.Name, err)
}
}
return nil
}
// HelpContext adds the context to the command's help.
func (cmd *Command) HelpContext(ctx *Context) io.WriterTo {
help := cmd.Help
if help == nil {
help, _ = NewCommandHelp(cmd)
}
if v, ok := help.(interface{ SetContext(*Context) }); ok {
v.SetContext(ctx)
}
return help
}
// WriteTo satisfies the [io.WriterTo] interface.
func (cmd *Command) WriteTo(w io.Writer) (int64, error) {
help := cmd.Help
if help == nil {
var err error
if help, err = NewCommandHelp(cmd); err != nil {
return 0, err
}
}
return help.WriteTo(w)
}
// WalkFlags returns an iterator for all flags on the command and its parents.
func (cmd *Command) WalkFlags(hidden, deprecated bool) iter.Seq[*Flag] {
return func(yield func(*Flag) bool) {
for c := cmd; c != nil; c = c.Parent {
if c.Flags == nil {
continue
}
for _, g := range c.Flags.Flags {
switch {
case !hidden && g.Hidden, !deprecated && g.Deprecated:
continue
}
if !yield(g) {
return
}
}
}
}
}
// CompCommands returns command completions for the command.
func (cmd *Command) CompCommands(name string, hidden, deprecated bool) ([]Completion, CompDirective) {
// TODO: settings for toggling case sensitivity / disabling ldist matching
lower, m := strings.ToLower(name), make(map[string]bool)
var comps []Completion
loop:
for _, c := range cmd.Commands {
switch {
case m[c.Name], !hidden && c.Hidden, !deprecated && c.Deprecated:
continue
}
for _, s := range prepend(c.Aliases, c.Name) {
if strings.HasPrefix(strings.ToLower(s), lower) {
comps = append(comps, NewCompletion(c.Name, c.Usage, 0))
m[c.Name] = true
continue loop
}
}
}
if maxDist := maxDist(cmd); 0 < maxDist && len(comps) == 0 {
r := []rune(lower)
loop2:
for _, c := range cmd.Commands {
switch {
case m[c.Name], !hidden && c.Hidden, !deprecated && c.Deprecated:
continue
}
for _, s := range prepend(c.Aliases, c.Name) {
if dist := Ldist([]rune(strings.ToLower(s)), r); dist <= maxDist {
comps = append(comps, NewCompletion(c.Name, c.Usage, dist))
m[c.Name] = true
continue loop2
}
}
}
sort.Slice(comps, func(i, j int) bool {
return comps[i].Dist < comps[j].Dist
})
if len(comps) != 0 {
d := comps[0].Dist
comps = slices.DeleteFunc(comps, func(c Completion) bool {
return d < c.Dist
})
}
}
if len(comps) != 0 {
return comps, CompNoFileComp | CompKeepOrder
}
return nil, CompDefault
}
// CompFlags returns flag completions for the command.
func (cmd *Command) CompFlags(name string, hidden, deprecated, short bool) ([]Completion, CompDirective) {
var comps []Completion
lower, m := strings.ToLower(name), make(map[string]bool)
for g := range cmd.WalkFlags(hidden, deprecated) {
if !short || len(name) == 0 {
for _, s := range prepend(g.Aliases, g.Name) {
switch long := "--" + g.Name; {
case m[long]:
continue
case strings.HasPrefix(strings.ToLower(s), lower):
comps = append(comps, NewCompletion(long, g.Usage, 0))
m[long] = true
}
}
}
if short {
for _, s := range prepend(g.Aliases, g.Short) {
switch shortstr := "-" + s; {
case m[shortstr]:
continue
case len(s) == 1 && strings.HasPrefix(s, name):
comps = append(comps, NewCompletion(shortstr, g.Usage, 0))
m[shortstr] = true
}
}
}
}
// distance match
if maxDist := maxDist(cmd); 0 < maxDist && len(comps) == 0 && len(name) != 1 {
r := []rune(lower)
for g := range cmd.WalkFlags(hidden, deprecated) {
long := "--" + g.Name
if m[long] {
continue
}
for _, s := range prepend(g.Aliases, g.Name) {
long := "--" + g.Name
if m[long] {
continue
}
if dist := Ldist([]rune(strings.ToLower(s)), r); dist <= maxDist {
comps = append(comps, NewCompletion(long, g.Usage, dist))
m[long] = true
}
}
}
sort.Slice(comps, func(i, j int) bool {
return comps[i].Dist < comps[j].Dist
})
if len(comps) != 0 {
d := comps[0].Dist
comps = slices.DeleteFunc(comps, func(c Completion) bool {
return d < c.Dist
})
}
}
if len(comps) != 0 {
return comps, CompNoFileComp | CompKeepOrder
}
return nil, CompDefault
}
// FlagSet is a set of command-line flag definitions.
type FlagSet struct {
Flags []*Flag
}
// Flags creates a new flag set from the options.
func Flags() *FlagSet {
return new(FlagSet)
}
// Option returns a [CommandOption] for the flag set.
func (fs *FlagSet) Option() option {
return option{
name: "FlagSet",
cmd: func(cmd *Command) error {
cmd.Flags = fs
return nil
},
}
}
// Var adds a variable to the flag set.
func (fs *FlagSet) Var(name, usage string, opts ...Option) *FlagSet {
if fs == nil {
fs = Flags()
}
g, err := NewFlag(name, usage, opts...)
if err != nil {
panic(err)
}
fs.Flags = append(fs.Flags, g)
return fs
}
// String adds a string variable to the flag set.
func (fs *FlagSet) String(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(StringT))...)
}
// Bytes adds a []byte variable to the flag set.
func (fs *FlagSet) Bytes(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(BytesT))...)
}
// Base64 adds a base64 encoded []byte variable to the flag set.
func (fs *FlagSet) Base64(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Base64T))...)
}
// Hex adds a hex encoded []byte variable to the flag set.
func (fs *FlagSet) Hex(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(HexT))...)
}
// Bool adds a bool variable to the flag set.
func (fs *FlagSet) Bool(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(BoolT))...)
}
// Byte adds a byte variable to the flag set.
func (fs *FlagSet) Byte(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(ByteT))...)
}
// Rune adds a rune variable to the flag set.
func (fs *FlagSet) Rune(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(RuneT))...)
}
// Int64 adds a int64 variable to the flag set.
func (fs *FlagSet) Int64(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Int64T))...)
}
// Int32 adds a int32 variable to the flag set.
func (fs *FlagSet) Int32(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Int32T))...)
}
// Int16 adds a int16 variable to the flag set.
func (fs *FlagSet) Int16(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Int16T))...)
}
// Int8 adds a int8 variable to the flag set.
func (fs *FlagSet) Int8(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Int8T))...)
}
// Int adds a int variable to the flag set.
func (fs *FlagSet) Int(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(IntT))...)
}
// Uint64 adds a uint64 variable to the flag set.
func (fs *FlagSet) Uint64(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Uint64T))...)
}
// Uint32 adds a uint32 variable to the flag set.
func (fs *FlagSet) Uint32(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Uint32T))...)
}
// Uint16 adds a uint16 variable to the flag set.
func (fs *FlagSet) Uint16(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Uint16T))...)
}
// Uint8 adds a uint8 variable to the flag set.
func (fs *FlagSet) Uint8(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Uint8T))...)
}
// Uint adds a uint variable to the flag set.
func (fs *FlagSet) Uint(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(UintT))...)
}
// Float64 adds a float64 variable to the flag set.
func (fs *FlagSet) Float64(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Float64T))...)
}
// Float32 adds a float32 variable to the flag set.
func (fs *FlagSet) Float32(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Float32T))...)
}
// Complex128 adds a complex128 variable to the flag set.
func (fs *FlagSet) Complex128(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Complex128T))...)
}
// Complex64 adds a complex64 variable to the flag set.
func (fs *FlagSet) Complex64(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(Complex64T))...)
}
// Timestamp adds a [time.Time] variable to the flag set in the expected format
// of [time.RFC3339].
func (fs *FlagSet) Timestamp(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(TimestampT))...)
}
// DateTime adds a [time.Time] variable to the flag set in the expected format
// of [time.DateTime].
func (fs *FlagSet) DateTime(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(DateTimeT))...)
}
// Date adds a [time.Time] variable to the flag set in the expected format of
// [time.DateOnly].
func (fs *FlagSet) Date(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(DateT))...)
}
// Duration adds a [time.Duration] variable to the flag set.
func (fs *FlagSet) Duration(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(DurationT))...)
}
// Size adds a [Size] variable to the flag set.
func (fs *FlagSet) Size(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(SizeT))...)
}
// Rate adds a [Rate] variable to the flag set.
func (fs *FlagSet) Rate(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(RateT))...)
}
// Path adds a path variable to the flag set.
func (fs *FlagSet) Path(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(PathT))...)
}
// Count adds a count variable to the flag set.
func (fs *FlagSet) Count(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(CountT))...)
}
// BigInt adds a [math/big.Int] variable to the flag set.
func (fs *FlagSet) BigInt(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(BigIntT))...)
}
// BigFloat adds a [math/big.Float] variable to the flag set.
func (fs *FlagSet) BigFloat(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(BigFloatT))...)
}
// BigRat adds a [math/big.Rat] variable to the flag set.
func (fs *FlagSet) BigRat(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(BigRatT))...)
}
// Addr adds a [netip.Addr] variable to the flag set.
func (fs *FlagSet) Addr(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(AddrT))...)
}
// AddrPort adds a [netip.AddrPort] variable to the flag set.
func (fs *FlagSet) AddrPort(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(AddrPortT))...)
}
// CIDR adds a [netip.Prefix] variable to the flag set.
func (fs *FlagSet) CIDR(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(CIDRT))...)
}
// Regexp adds a [regexp.Regexp] variable to the flag set.
func (fs *FlagSet) Regexp(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(RegexpT))...)
}
// URL adds a [url.URL] variable to the flag set.
func (fs *FlagSet) URL(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(URLT))...)
}
// UUID adds a uuid variable to the flag set.
func (fs *FlagSet) UUID(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(UUIDT))...)
}
// Color adds a color variable to the flag set.
func (fs *FlagSet) Color(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(ColorT))...)
}
// Glob adds a glob variable to the flag set.
func (fs *FlagSet) Glob(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(GlobT))...)
}
// Slice adds a slice variable to the flag set.
func (fs *FlagSet) Slice(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(SliceT))...)
}
// Array adds a array variable to the flag set.
func (fs *FlagSet) Array(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(ArrayT))...)
}
// Map adds a map variable to the flag set.
func (fs *FlagSet) Map(name, usage string, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(MapT))...)
}
// Hook adds a hook to the flag set.
func (fs *FlagSet) Hook(name, usage string, f any, opts ...Option) *FlagSet {
return fs.Var(name, usage, prepend(opts, Option(HookT), NoArg(true, ""), Default(f))...)
}
// Flag is a command-line flag variable definition.
type Flag struct {
// Type is the flag's [Type].
Type Type
// MapKey is the flag's map key type when the flag is a [MapT].
MapKey Type
// Elem is the flag's element type when the flag is a [SliceT], [ArrayT] or [MapT].
Elem Type
// Name is the flag's long name (`--arg`).
Name string
// Usage is the flag's usage.
Usage string
// Short is the flag's short, single letter name (`-a`).
Short string
// Aliases are the flag's long and short aliases.
Aliases []string
// Spec is the flag's help spec.
Spec string
// Def is the flag's default value.
Def any
// NoArg when true, indicates that the flag does not require an argument.
NoArg bool
// NoArgDef is the flag's default value when no argument was passed for the
// flag.
NoArgDef any
// Binds are the bound variables that will be additionally set when the
// flag is encountered on the command-line.
Binds []Binder
// Keys are the flag's config look up keys.
Keys map[string]string
// Section is the flag's help section.
Section int
// Hidden indicates the flag is hidden from help output.
Hidden bool
// Deprecated indicates the flag is deprecated.
Deprecated bool
// Split is a split separator, to split values for slices/arrays/maps.
Split string
// Special is the flag's special value.
Special string
}
// NewFlag creates a new command-line flag.
func NewFlag(name, usage string, opts ...Option) (*Flag, error) {
g := &Flag{
Type: StringT,
MapKey: StringT,
Elem: StringT,
Name: name,
Usage: usage,
Section: -1,
}
if err := Apply(g, opts...); err != nil {
return nil, err
}
if extra, ok := typeFlagOpts[g.Type]; ok {
if err := Apply(g, extra...); err != nil {
return nil, err
}
}
switch {
case g.Name == "":
return nil, ErrInvalidFlagName
case g.NoArg && g.NoArgDef == nil:
return nil, fmt.Errorf("flag %s: %w: NoArgDef cannot be nil", g.Name, ErrInvalidValue)
case g.Type == HookT && g.Def == nil:
return nil, fmt.Errorf("flag %s: %w: Def cannot be nil", g.Name, ErrInvalidValue)
}
return g, nil
}
// FlagsFrom creates flags for a value of type *struct using reflection. Builds
// flags for all exported fields with a `ox` tag, and a non-empty description.
//
// A `ox` tag starts with the flag's description, followed by one or more
// options separated by `,`. If a flag description must contain a comma (`,`)
// it can be escaped with a double backslash (`\\`). The flag's name is
// determined by the result of calling [DefaultFlagNameMapper], or it can be
// set with the `name:` option (see below).
//
// Use the [CommandOption] [From] to add flags when creating a command with
// [Run]/[RunContext]/[Sub]/[NewCommand].
//
// Example:
//
// args := struct{
// MyFlag string `ox:"my flag,short:f,default:$USER"`
// MyVerbosity int `ox:"my verbosity,type:count,short:v"`
// MyURL *url.URL `ox:"my url,set:MyURLSet"`
// MyURLSet bool
// MyOtherFlag string `ox:"a long\\, long description,short:F"`
// MyFloat float64 `ox:"my float,hidden,name:MYF"`
// }{}
//
// ox.FlagsFrom(&args)
//
// Recognized options:
//
// type - sets the flag's field type
// mapkey - sets the flag's map key type
// elem - sets the flag's slice/array/map element type
// name - sets the flag's name
// short - sets the flag's short (single character) name
// alias - adds a alias to the flag
// aliases - adds multiple aliases, separated by `|` to the flag
// spec - sets the flag's use spec
// default - sets the flag's default value
// noarg - sets the flag as requiring no argument, and the default value for the flag when toggled
// key - sets the flag's lookup config key
// hook - sets the flag's special value to `hook:<type>`, and can be used to hook [Defaults]'s flags
// section - sets the flag's section
// hidden - marks the flag as hidden
// deprecated - marks the flag as deprecated
// split - set a split separator for slice/array/map values
// set - binds the flag's set value to a bool field in the *struct of the name
//
// The `default:` option will be expanded by [Context.Expand] when the
// command's flags are populated.
//
// The tag name (`ox`) can be changed by setting the [DefaultStructTagName] variable
// if necessary.
func FlagsFrom[T *E, E any](val T) ([]*Flag, error) {
return appendFlags(nil, reflect.ValueOf(val), nil)
}
// New creates a new value for the flag's type.
func (g *Flag) New(ctx *Context) (Value, error) {
switch g.Type {
case SliceT:
return NewSlice(g.Elem), nil
case ArrayT:
return NewArray(g.Elem), nil
case MapT:
return NewMap(g.MapKey, g.Elem)
case HookT:
return newHook(ctx, g.Def)
}
return g.Type.New()
}
// SpecString returns the spec string for the flag.
func (g *Flag) SpecString() string {
switch {
case g.NoArg || g.Type == HookT:
return g.Name
case g.Spec != "":
return g.Name + text.FlagSpecSpacer + g.Spec
case g.Type == SliceT, g.Type == ArrayT:
return g.Name + text.FlagSpecSpacer + g.Elem.String()
case g.Type == MapT:
return g.Name + text.FlagSpecSpacer + g.MapKey.String() + "=" + g.Elem.String()
}
return g.Name + text.FlagSpecSpacer + g.Type.String()
}
// ExecType is the interface for func's that can be used with [Run],
// [NewCommand], and [Exec].
type ExecType interface {
func(context.Context, []string) error |
func(context.Context, []string) |
func(context.Context) error |
func(context.Context) |
func([]string) error |
func([]string) |
func() error |
func()
}
// ExecFunc wraps a exec func.
type ExecFunc func(context.Context, []string) error
// NewExec creates a [ExecFunc] func.
func NewExec[T ExecType](f T) (ExecFunc, error) {
var v any = f
switch f := v.(type) {
case func(context.Context, []string) error:
return f, nil
case func(context.Context, []string):
return func(ctx context.Context, args []string) error {
f(ctx, args)
return nil
}, nil
case func(context.Context) error:
return func(ctx context.Context, _ []string) error {
return f(ctx)
}, nil
case func(context.Context):
return func(ctx context.Context, _ []string) error {
f(ctx)
return nil
}, nil
case func([]string) error:
return func(_ context.Context, args []string) error {
return f(args)
}, nil
case func([]string):
return func(_ context.Context, args []string) error {
f(args)
return nil
}, nil
case func() error:
return func(context.Context, []string) error {
return f()
}, nil
case func():
return func(context.Context, []string) error {
f()
return nil
}, nil
}
return nil, fmt.Errorf("%w: invalid exec func %T", ErrInvalidType, f)
}
// appendFlags builds and appends flags for value v to flags.
func appendFlags(flags []*Flag, v reflect.Value, parents []string) ([]*Flag, error) {
if v.Kind() != reflect.Pointer || v.Elem().Kind() != reflect.Struct {
return nil, fmt.Errorf("%w: %s is not a *struct", ErrInvalidType, v.Type())
}
v = v.Elem()
typ := v.Type()
for i := range typ.NumField() {
// check field is exported
f := typ.Field(i)
tag, ok := f.Tag.Lookup(DefaultStructTagName)
if !ok {
continue
}
if r := []rune(f.Name); !unicode.IsUpper(r[0]) {
return nil, fmt.Errorf("%w: unexported field `%s` has tag `%s`", ErrInvalidType, f.Name, DefaultStructTagName)
}
field := v.Field(i)
tags := SplitBy(tag, ',')
isField := isField(field)
switch name, kind := tags[0], f.Type.Kind(); {
case !isField && kind == reflect.Pointer && f.Type.Elem().Kind() == reflect.Struct: // *struct
switch {
case name == "-":
continue
case name == "":
name = f.Name
}
if field.IsNil() {
field.Set(reflect.New(f.Type.Elem()))
}
var err error
if flags, err = appendFlags(flags, field, append(parents, name)); err != nil {
return nil, err
}
case !isField && kind == reflect.Struct: // struct
switch {
case name == "-":
continue
case name == "":
name = f.Name
}
var err error
if flags, err = appendFlags(flags, field.Addr(), append(parents, name)); err != nil {
return nil, err
}
default:
if name == "" || name == "-" {
continue
}
g, err := buildFlag(v, i, tags, parents)
if err != nil {
return nil, err
}
flags = append(flags, g)
}
}
return flags, nil
}
// buildFlags builds a flag for v.
func buildFlag(v reflect.Value, i int, tag []string, parents []string) (*Flag, error) {
f := v.Type().Field(i)
// flag name
name := f.Name
if len(parents) != 0 {
name = strings.Join(parents, "_") + "_" + name
}
// flag opts
opts, err := buildFlagOpts(v, v.Field(i).Addr(), tag[1:])
if err != nil {
return nil, fmt.Errorf("field %s: %w", f.Name, err)
}
// create flag
g, err := NewFlag(DefaultFlagNameMapper(name), tag[0], opts...)
if err != nil {
return nil, fmt.Errorf("field %s: cannot create flag: %w", f.Name, err)
}
return g, nil
}
// buildFlagOpts builds flag options for value from the passed struct tags.
func buildFlagOpts(parent, value reflect.Value, tags []string) ([]Option, error) {
var set *bool
typ, mapKey, elem, err := defaultType(value.Elem().Type())
if err != nil {
return nil, fmt.Errorf("%s: %w", value.Type().String(), err)
}
opts := []Option{typ, MapKey(mapKey), Elem(elem)}
if typ == SliceT || typ == MapT {
opts = append(opts, Split(","))
}
for _, opt := range tags {
key, val, _ := strings.Cut(opt, ":")
switch key {
case "type":
opts = append(opts, Type(val))
case "mapkey":
opts = append(opts, MapKey(Type(val)))
case "elem":
opts = append(opts, Elem(Type(val)))
case "name":
opts = append(opts, Name(val))
case "short":
opts = append(opts, Short(val))
case "alias":
opts = append(opts, Aliases(val))
case "aliases":
opts = append(opts, Aliases(strings.Split(val, "|")...))
case "spec":
opts = append(opts, Spec(val))
case "default":
opts = append(opts, Default(val))
case "noarg":
opts = append(opts, NoArg(true, val))
case "key":
typ, key, _ := strings.Cut(val, "|")
if key == "" {
typ, key = key, typ
}
opts = append(opts, Key(typ, key))
case "hook":
opts = append(opts, Special("hook:"+val))
case "section":
section, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("%w: section %s: %w", ErrInvalidConversion, val, err)
}
opts = append(opts, Section(section))
case "hidden":
opts = append(opts, Hidden(true))
case "deprecated":
opts = append(opts, Deprecated(true))
case "split":
opts = append(opts, Split(val))
case "set":
if set, err = setField(parent, val); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("%w: %q", ErrUnknownTagOption, key)
}
}
// prepend bind to options
return prepend(opts, BindRef(value, set)), nil
}
// isField returns true if v is not a struct or the struct contains at least
// one `ox` tag.
func isField(v reflect.Value) bool {
typ := v.Type()
kind := typ.Kind()
if kind == reflect.Pointer {
typ = typ.Elem()
kind = typ.Kind()
}
if kind != reflect.Struct {
return false
}