Debian Codegraph @

spec.go

raw symbols SCIP
1 package opt
2
3 import (
4 "errors"
5 "fmt"
6 "reflect"
7 "regexp"
8 "strconv"
9 "strings"
10 )
11
12 // Command line options specifier
13 type CmdSpec struct {
14 // first argument, for Usage() generation
15 name string
16 // if true, all arguments will be ignored
17 passthrough bool
18 // if true, positional arguments may start with "-"
19 minusPositionals bool
20 // list of option specs extracted from struct tags
21 opts []optSpec
22 // list of option specs in the order in which they were seen
23 seen []*seenArg
24 // indexes of short options in the list for quick access
25 shortOpts map[string]int
26 // indexes of long options in the list for quick access
27 longOpts map[string]int
28 // indexes of positional arguments
29 positionals []int
30 }
31
32 type seenArg struct {
33 spec *optSpec
34 indexes []int
35 }
36
37 type optKind int
38
39 const (
40 unset optKind = iota
41 // dummy value to cause the whole command to be passthrough
42 passthrough
43 // flag without a value: "-f" or "--foo-baz"
44 flag
45 // flag with a value: "-f bar", "--foo-baz bar" or "--foo-baz=bar"
46 option
47 // positional argument after interpreting shell quotes
48 positional
49 // remaining positional arguments after interpreting shell quotes
50 remainderSplit
51 // remaining positional arguments without interpreting shell quotes
52 remainder
53 // nested subcommand
54 subcommand
55 )
56
57 // Option or argument specifier
58 type optSpec struct {
59 // kind of option/argument
60 kind optKind
61 // argument is required
62 required bool
63 // if true, positional may start with "-"
64 minusPositional bool
65 // option/argument description
66 description string
67 // argument was seen on the command line
68 seen bool
69 // argument value was seen on the command line (only applies to options)
70 seenValue bool
71 // "f", "foo-baz" (only when kind is flag or option)
72 short, long string
73 // name of option/argument value in usage help
74 metavar string
75 // default string value before interpretation
76 defval string
77 // only applies to the specified command aliases
78 aliases []string
79 // custom action method
80 action reflect.Value
81 // custom complete method
82 complete reflect.Value
83 // destination struct field
84 dest reflect.Value
85 // raw argument value
86 arg string
87 }
88
89 var (
90 shortOptRe = regexp.MustCompile(`^(-[a-zA-Z0-9])$`)
91 longOptRe = regexp.MustCompile(`^(--[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])$`)
92 positionalRe = regexp.MustCompile(`^([a-zA-Z][\w-]*)$`)
93 subcommandRe = regexp.MustCompile(`^:([a-zA-Z][\w-]*):$`)
94 )
95
96 // Interpret all struct fields to a list of option specs
97 func NewCmdSpec(name string, v any) *CmdSpec {
98 typ := reflect.TypeOf(v)
99 val := reflect.ValueOf(v)
100 if typ.Kind() == reflect.Pointer {
101 typ = typ.Elem()
102 val = val.Elem()
103 } else {
104 panic("NewCmdSpec requires a pointer")
105 }
106 if typ.Kind() != reflect.Struct {
107 panic("NewCmdSpec requires a pointer to a struct")
108 }
109
110 cmd := &CmdSpec{
111 name: name,
112 opts: make([]optSpec, 0, typ.NumField()),
113 shortOpts: make(map[string]int),
114 longOpts: make(map[string]int),
115 }
116
117 allPositionals := false
118 for i := 0; i < typ.NumField(); i++ {
119 var spec optSpec
120 spec.parseField(reflect.ValueOf(v), typ.Field(i))
121 switch spec.kind {
122 case unset:
123 // ignored field
124 continue
125 case passthrough:
126 cmd.passthrough = true
127 continue
128 }
129 spec.dest = val.Field(i)
130
131 if allPositionals {
132 panic(`opt:"..." or opt:":cmd:" must be last`)
133 }
134
135 switch spec.kind {
136 case flag, option:
137 if spec.short != "" {
138 cmd.shortOpts[spec.short] = len(cmd.opts)
139 }
140 if spec.long != "" {
141 cmd.longOpts[spec.long] = len(cmd.opts)
142 }
143 case remainder, remainderSplit:
144 allPositionals = true
145 fallthrough
146 default:
147 cmd.positionals = append(cmd.positionals, len(cmd.opts))
148 if spec.minusPositional {
149 cmd.minusPositionals = true
150 }
151 }
152 cmd.opts = append(cmd.opts, spec)
153 }
154
155 return cmd
156 }
157
158 func (spec *optSpec) parseField(struc reflect.Value, t reflect.StructField) {
159 opt := t.Tag.Get("opt")
160
161 switch opt {
162 case "-":
163 // ignore all arguments (passthrough) for this command
164 spec.kind = passthrough
165 fallthrough
166 case "":
167 // ignored field
168 return
169 }
170
171 abort := func(msg string, args ...any) {
172 msg = fmt.Sprintf(msg, args...)
173 panic(fmt.Sprintf("%s.%s: %s", struc.Type(), t.Name, msg))
174 }
175
176 if methodName, found := t.Tag.Lookup("action"); found {
177 method := struc.MethodByName(methodName)
178 if !method.IsValid() {
179 abort("action method not found: (*%s).%s", struc, methodName)
180 }
181
182 ok := method.Type().NumIn() == 1
183 ok = ok && method.Type().In(0).Kind() == reflect.String
184 ok = ok && method.Type().NumOut() == 1
185 ok = ok && method.Type().Out(0).Kind() == reflect.Interface
186 ok = ok && method.Type().Out(0).Name() == "error"
187 if !ok {
188 abort("(*%s).%s: invalid signature, expected func(string) error",
189 struc.Elem().Type().Name(), methodName,
190 t.Type.Kind())
191 }
192 spec.action = method
193 }
194
195 if !spec.action.IsValid() {
196 switch t.Type.Kind() {
197 case reflect.String:
198 fallthrough
199 case reflect.Bool:
200 fallthrough
201 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
202 fallthrough
203 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
204 fallthrough
205 case reflect.Float32, reflect.Float64:
206 fallthrough
207 case reflect.Slice:
208 break
209 default:
210 abort("unsupported field type: %s", t.Type.Kind())
211 }
212 }
213
214 // check what kind of argument this field maps to
215 switch {
216 case opt == "...":
217 // remainder
218 switch t.Type.Kind() {
219 case reflect.Slice:
220 if !spec.action.IsValid() {
221 if t.Type.Elem().Kind() != reflect.String {
222 abort("'...' requires []string if action is unset")
223 }
224 }
225 spec.kind = remainderSplit
226 case reflect.String:
227 spec.kind = remainder
228 default:
229 if !spec.action.IsValid() {
230 abort("'...' requires string or []string if action is unset")
231 }
232 }
233 spec.metavar = "<" + strings.ToLower(t.Name) + ">..."
234 spec.required = true
235
236 case strings.HasPrefix(opt, "-"):
237 // flag or option
238 for _, flag := range strings.Split(opt, ",") {
239 m := longOptRe.FindStringSubmatch(flag)
240 if m != nil {
241 spec.long = m[1]
242 continue
243 }
244 m = shortOptRe.FindStringSubmatch(flag)
245 if m != nil {
246 spec.short = m[1]
247 continue
248 }
249 abort("invalid opt tag: %q", opt)
250 }
251 if t.Type.Kind() == reflect.Bool {
252 spec.kind = flag
253 } else {
254 spec.kind = option
255 spec.metavar = "<" + strings.ToLower(t.Name) + ">"
256 }
257 if spec.short == "" && spec.long == "" {
258 abort("invalid opt tag: %q", opt)
259 }
260
261 case positionalRe.MatchString(opt):
262 // named positional
263 spec.kind = positional
264 spec.metavar = "<" + strings.ToLower(opt) + ">"
265 spec.required = true
266
267 case subcommandRe.MatchString(opt):
268 // subcommand
269 match := subcommandRe.FindStringSubmatch(opt)
270 if t.Type.Kind() != reflect.Interface {
271 abort("':" + match[1] + ":' requires an interface")
272 }
273 if !spec.action.IsValid() {
274 abort("':" + match[1] + ":' requires action to be set")
275 }
276 spec.kind = subcommand
277 spec.metavar = "<" + match[1] + ">"
278 spec.required = true
279
280 default:
281 abort("invalid opt tag: %q", opt)
282 }
283
284 if metavar, hasMetavar := t.Tag.Lookup("metavar"); hasMetavar {
285 // explicit metavar for the generated usage
286 spec.metavar = metavar
287 }
288
289 spec.description = t.Tag.Get("description")
290 if spec.description == "" {
291 spec.description = t.Tag.Get("desc")
292 }
293
294 spec.defval = t.Tag.Get("default")
295
296 switch t.Tag.Get("required") {
297 case "true":
298 spec.required = true
299 case "false":
300 spec.required = false
301 case "":
302 if spec.defval != "" {
303 spec.required = false
304 }
305 default:
306 abort("invalid required value")
307 }
308
309 switch t.Tag.Get("minus") {
310 case "true":
311 spec.minusPositional = true
312 case "false", "":
313 spec.minusPositional = false
314 default:
315 abort("invalid minus value")
316 }
317
318 if aliases := t.Tag.Get("aliases"); aliases != "" {
319 spec.aliases = strings.Split(aliases, ",")
320 }
321
322 if methodName, found := t.Tag.Lookup("complete"); found {
323 method := struc.MethodByName(methodName)
324 if !method.IsValid() {
325 abort("complete method not found: (*%s).%s", struc, methodName)
326 }
327 if !(method.Type().NumIn() == 1 &&
328 method.Type().In(0).Kind() == reflect.String &&
329 method.Type().NumOut() == 1 &&
330 method.Type().Out(0).Kind() == reflect.Slice &&
331 method.Type().Out(0).Elem().Kind() == reflect.String) {
332 abort("(*%s).%s: invalid signature, expected func(string) []string",
333 struc.Elem().Type().Name(), methodName,
334 t.Type.Kind())
335 }
336 spec.complete = method
337 }
338 }
339
340 func (s *optSpec) Usage() string {
341 var usage string
342
343 switch s.kind {
344 case flag:
345 if s.short != "" {
346 usage = s.short
347 } else {
348 usage = s.long
349 }
350
351 case option:
352 if s.short != "" {
353 usage = s.short
354 } else {
355 usage = s.long
356 }
357 usage += " " + s.metavar
358
359 case subcommand:
360 usage = s.metavar + " ..."
361
362 default:
363 usage = s.metavar
364 }
365
366 if s.required {
367 return usage
368 }
369 return "[" + usage + "]"
370 }
371
372 func (s *optSpec) Flag() string {
373 var usage string
374
375 switch s.kind {
376 case flag, option:
377 if s.short != "" {
378 usage = s.short
379 } else {
380 usage = s.long
381 }
382 default:
383 usage = s.metavar
384 }
385
386 return usage
387 }
388
389 func (c *CmdSpec) Usage() string {
390 if c.passthrough {
391 return c.name + " ..."
392 }
393 args := []string{c.name}
394 for _, spec := range c.opts {
395 if spec.appliesToAlias(c.name) {
396 if spec.kind == subcommand && !spec.dest.IsNil() {
397 cc := NewCmdSpec(spec.arg, spec.dest.Elem().Interface())
398 args = append(args, cc.Usage())
399 } else {
400 args = append(args, spec.Usage())
401 }
402 }
403 }
404 return strings.Join(args, " ")
405 }
406
407 type errKind int
408
409 const (
410 unknownErr errKind = iota
411 missingValue
412 takesNoValue
413 unknownFlag
414 unexpectedArg
415 badValue
416 requiredArg
417 )
418
419 type ArgError struct {
420 kind errKind
421 spec *optSpec
422 err error
423 }
424
425 func (e *ArgError) Error() string {
426 switch e.kind {
427 case missingValue:
428 return fmt.Sprintf("%s takes a value", e.spec.Flag())
429 case takesNoValue:
430 return fmt.Sprintf("%s does not take a value", e.spec.Flag())
431 case unknownFlag:
432 return fmt.Sprintf("%s unknown flag", e.err)
433 case unexpectedArg:
434 return fmt.Sprintf("%q unexpected argument", e.err.Error())
435 case badValue:
436 return fmt.Sprintf("%s: %s", e.spec.Flag(), e.err)
437 case requiredArg:
438 return fmt.Sprintf("%s is required", e.spec.Flag())
439 default:
440 return fmt.Sprintf("unknown error: %#v", e)
441 }
442 }
443
444 func (c *CmdSpec) ParseArgs(args *Args) error {
445 if c.passthrough {
446 return nil
447 }
448 if _, errors := c.parseArgs(args); len(errors) > 0 {
449 return errors[0]
450 }
451 return nil
452 }
453
454 func (c *CmdSpec) markSeen(spec *optSpec, index int) *seenArg {
455 spec.seen = true
456 arg := &seenArg{spec: spec, indexes: []int{index}}
457 c.seen = append(c.seen, arg)
458 return arg
459 }
460
461 func (c *CmdSpec) parseArgs(args *Args) (*CmdSpec, []*ArgError) {
462 var cur *seenArg
463 var argErrors []*ArgError
464
465 fail := func(kind errKind, s *optSpec, detail error) {
466 argErrors = append(argErrors, &ArgError{kind, s, detail})
467 }
468 positionals := c.positionals
469 ignoreFlags := false
470 c.seen = nil
471 args.Shift(1) // skip command name
472 i := 1
473
474 for args.Count() > 0 {
475 arg := args.Arg(0)
476
477 switch {
478 case !ignoreFlags && arg == "--":
479 ignoreFlags = true
480
481 case !ignoreFlags && c.hasLongFlag(arg):
482 if cur != nil {
483 fail(missingValue, cur.spec, nil)
484 }
485 f, val, hasValue := strings.Cut(arg, "=")
486 spec := c.getLongFlag(f)
487 if spec == nil {
488 fail(unknownFlag, nil, errors.New(f))
489 goto next
490 }
491 cur = c.markSeen(spec, i)
492 if cur.spec.kind == flag {
493 if hasValue {
494 fail(takesNoValue, cur.spec, nil)
495 cur = nil
496 goto next
497 }
498 if err := cur.spec.parseValue("true"); err != nil {
499 fail(badValue, cur.spec, err)
500 }
501 cur = nil
502 } else if hasValue {
503 if err := cur.spec.parseValue(val); err != nil {
504 fail(badValue, cur.spec, err)
505 }
506 cur = nil
507 }
508
509 case !ignoreFlags && c.hasShortFlag(arg):
510 if cur != nil {
511 fail(missingValue, cur.spec, nil)
512 }
513 arg = arg[1:]
514 for len(arg) > 0 {
515 f := arg[:1]
516 arg = arg[1:]
517 var spec *optSpec
518
519 if o, ok := c.shortOpts["-"+f]; ok {
520 spec = &c.opts[o]
521 }
522 if spec == nil || !spec.appliesToAlias(c.name) {
523 fail(unknownFlag, spec, errors.New("-"+f))
524 goto next
525 }
526 cur = c.markSeen(spec, i)
527 if spec.kind == flag {
528 if err := spec.parseValue("true"); err != nil {
529 fail(badValue, spec, err)
530 }
531 cur = nil
532 } else if len(arg) > 0 {
533 if err := spec.parseValue(arg); err != nil {
534 fail(badValue, spec, err)
535 }
536 cur = nil
537 arg = ""
538 }
539 }
540
541 default:
542 // positional
543 if cur != nil {
544 // separate value for a short/long flag
545 cur.indexes = append(cur.indexes, i)
546 if err := cur.spec.parseValue(arg); err != nil {
547 fail(badValue, cur.spec, err)
548 }
549 cur = nil
550 goto next
551 }
552
553 for len(positionals) > 0 {
554 spec := &c.opts[positionals[0]]
555 positionals = positionals[1:]
556 if spec.appliesToAlias(c.name) {
557 cur = c.markSeen(spec, i)
558 break
559 }
560 }
561
562 if cur == nil {
563 fail(unexpectedArg, nil, errors.New(arg))
564 goto next
565 }
566
567 switch cur.spec.kind {
568 case remainder:
569 if err := cur.spec.parseValue(args.String()); err != nil {
570 fail(badValue, cur.spec, err)
571 }
572 for args.Count() > 0 {
573 i += 1
574 cur.indexes = append(cur.indexes, i)
575 args.Shift(1)
576 }
577
578 case remainderSplit:
579 if cur.spec.action.IsValid() {
580 for _, a := range args.Args() {
581 if err := cur.spec.parseValue(a); err != nil {
582 fail(badValue, cur.spec, err)
583 }
584 }
585 } else {
586 cur.spec.dest.Set(reflect.ValueOf(args.Args()))
587 cur.spec.seenValue = true
588 cur.spec.arg = args.String()
589 }
590 for args.Count() > 0 {
591 i += 1
592 cur.indexes = append(cur.indexes, i)
593 args.Shift(1)
594 }
595
596 case subcommand:
597 if err := cur.spec.parseValue(arg); err != nil {
598 fail(badValue, cur.spec, err)
599 } else {
600 cc := NewCmdSpec(arg, cur.spec.dest.Elem().Interface())
601 positionals = cc.positionals
602 cc.seen = c.seen
603 c = cc
604 }
605
606 default:
607 if err := cur.spec.parseValue(arg); err != nil {
608 fail(badValue, cur.spec, err)
609 }
610 }
611
612 cur = nil
613 }
614 next:
615 args.Shift(1)
616 i += 1
617 }
618
619 if cur != nil {
620 fail(missingValue, cur.spec, nil)
621 }
622
623 for i := 0; i < len(c.opts); i++ {
624 spec := &c.opts[i]
625 if !spec.appliesToAlias(c.name) {
626 continue
627 }
628 if !spec.seen && spec.defval != "" {
629 if err := spec.parseValue(spec.defval); err != nil {
630 fail(missingValue, spec, nil)
631 }
632 } else if spec.required && !spec.seen {
633 fail(requiredArg, spec, nil)
634 }
635 }
636
637 return c, argErrors
638 }
639
640 func (c *CmdSpec) hasShortFlag(arg string) bool {
641 if len(arg) <= 1 || !strings.HasPrefix(arg, "-") {
642 return false
643 }
644 if o, ok := c.shortOpts[arg[:2]]; ok {
645 spec := &c.opts[o]
646 if spec.appliesToAlias(c.name) {
647 return true
648 }
649 }
650 return !c.minusPositionals
651 }
652
653 func (c *CmdSpec) hasLongFlag(arg string) bool {
654 if len(arg) <= 2 || !strings.HasPrefix(arg, "--") {
655 return false
656 }
657 if c.getLongFlag(arg) != nil {
658 return true
659 }
660 return !c.minusPositionals
661 }
662
663 func (c *CmdSpec) getLongFlag(arg string) *optSpec {
664 arg, _, _ = strings.Cut(arg, "=")
665 if o, ok := c.longOpts[arg]; ok {
666 spec := &c.opts[o]
667 if spec.appliesToAlias(c.name) {
668 return spec
669 }
670 }
671 return nil
672 }
673
674 func (s *optSpec) parseValue(arg string) error {
675 s.seenValue = true
676 s.arg = arg
677 if s.action.IsValid() {
678 in := []reflect.Value{reflect.ValueOf(arg)}
679 out := s.action.Call(in)
680 err, _ := out[0].Interface().(error)
681 return err
682 }
683
684 switch s.dest.Type().Kind() {
685 case reflect.String:
686 s.dest.SetString(arg)
687 case reflect.Bool:
688 if b, err := strconv.ParseBool(arg); err == nil {
689 s.dest.SetBool(b)
690 } else {
691 return err
692 }
693 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
694 if i, err := strconv.ParseInt(arg, 10, 64); err == nil {
695 s.dest.SetInt(i)
696 } else {
697 return err
698 }
699 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
700 if u, err := strconv.ParseUint(arg, 10, 64); err == nil {
701 s.dest.SetUint(u)
702 } else {
703 return err
704 }
705 case reflect.Float32, reflect.Float64:
706 if f, err := strconv.ParseFloat(arg, 64); err == nil {
707 s.dest.SetFloat(f)
708 } else {
709 return err
710 }
711 default:
712 return fmt.Errorf("unsupported type: %s", s.dest)
713 }
714
715 return nil
716 }
717
718 func (s *optSpec) appliesToAlias(alias string) bool {
719 if s.aliases == nil {
720 return true
721 }
722 for _, a := range s.aliases {
723 if a == alias {
724 return true
725 }
726 }
727 return false
728 }