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
|
package opt
import (
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
// Command line options specifier
type CmdSpec struct {
// first argument, for Usage() generation
name string
// if true, all arguments will be ignored
passthrough bool
// list of option specs extracted from struct tags
opts []optSpec
// list of option specs in the order in which they were seen
seen []*seenArg
// indexes of short options in the list for quick access
shortOpts map[string]int
// indexes of long options in the list for quick access
longOpts map[string]int
// indexes of positional arguments
positionals []int
}
type seenArg struct {
spec *optSpec
indexes []int
}
type optKind int
const (
unset optKind = iota
// dummy value to cause the whole command to be passthrough
passthrough
// flag without a value: "-f" or "--foo-baz"
flag
// flag with a value: "-f bar", "--foo-baz bar" or "--foo-baz=bar"
option
// positional argument after interpreting shell quotes
positional
// remaining positional arguments after interpreting shell quotes
remainderSplit
// remaining positional arguments without interpreting shell quotes
remainder
)
// Option or argument specifier
type optSpec struct {
// kind of option/argument
kind optKind
// argument is required
required bool
// option/argument description
description string
// argument was seen on the command line
seen bool
// argument value was seen on the command line (only applies to options)
seenValue bool
// "f", "foo-baz" (only when kind is flag or option)
short, long string
// name of option/argument value in usage help
metavar string
// default string value before interpretation
defval string
// only applies to the specified command aliases
aliases []string
// custom action method
action reflect.Value
// custom complete method
complete reflect.Value
// destination struct field
dest reflect.Value
}
var (
shortOptRe = regexp.MustCompile(`^(-[a-zA-Z0-9])$`)
longOptRe = regexp.MustCompile(`^(--[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])$`)
positionalRe = regexp.MustCompile(`^([a-zA-Z][\w-]*)$`)
)
const optionDelim = "--"
// Interpret all struct fields to a list of option specs
func NewCmdSpec(name string, v any) *CmdSpec {
typ := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
} else {
panic("NewCmdSpec requires a pointer")
}
if typ.Kind() != reflect.Struct {
panic("NewCmdSpec requires a pointer to a struct")
}
cmd := &CmdSpec{
name: name,
opts: make([]optSpec, 0, typ.NumField()),
shortOpts: make(map[string]int),
longOpts: make(map[string]int),
}
allPositionals := false
for i := 0; i < typ.NumField(); i++ {
var spec optSpec
spec.parseField(reflect.ValueOf(v), typ.Field(i))
switch spec.kind {
case unset:
// ignored field
continue
case passthrough:
cmd.passthrough = true
continue
}
spec.dest = val.Field(i)
if allPositionals {
panic(`opt:"..." must be last`)
}
switch spec.kind {
case flag, option:
if spec.short != "" {
cmd.shortOpts[spec.short] = len(cmd.opts)
}
if spec.long != "" {
cmd.longOpts[spec.long] = len(cmd.opts)
}
case remainder, remainderSplit:
allPositionals = true
fallthrough
default:
cmd.positionals = append(cmd.positionals, len(cmd.opts))
}
cmd.opts = append(cmd.opts, spec)
}
return cmd
}
func (spec *optSpec) parseField(struc reflect.Value, t reflect.StructField) {
abort := func(msg string, args ...any) {
msg = fmt.Sprintf(msg, args...)
panic(fmt.Sprintf("%s.%s: %s", struc.Type(), t.Name, msg))
}
// check what kind of argument this field maps to
opt := t.Tag.Get("opt")
switch {
case opt == "-":
// ignore all arguments (passthrough) for this command
spec.kind = passthrough
fallthrough
case opt == "":
// ignored field
return
case opt == "...":
// remainder
switch t.Type.Kind() {
case reflect.Slice:
if t.Type.Elem().Kind() != reflect.String {
abort("'...' only works with []string")
}
spec.kind = remainderSplit
case reflect.String:
spec.kind = remainder
default:
abort("'...' only works with string or []string")
}
spec.metavar = "<" + strings.ToLower(t.Name) + ">..."
spec.required = true
case strings.Contains(opt, "-"):
// flag or option
for _, flag := range strings.Split(opt, ",") {
m := longOptRe.FindStringSubmatch(flag)
if m != nil {
spec.long = m[1]
continue
}
m = shortOptRe.FindStringSubmatch(flag)
if m != nil {
spec.short = m[1]
continue
}
abort("invalid opt tag: %q", opt)
}
if t.Type.Kind() == reflect.Bool {
spec.kind = flag
} else {
spec.kind = option
spec.metavar = "<" + strings.ToLower(t.Name) + ">"
}
if spec.short == "" && spec.long == "" {
abort("invalid opt tag: %q", opt)
}
case positionalRe.MatchString(opt):
// named positional
spec.kind = positional
spec.metavar = "<" + strings.ToLower(opt) + ">"
spec.required = true
default:
abort("invalid opt tag: %q", opt)
}
if metavar, hasMetavar := t.Tag.Lookup("metavar"); hasMetavar {
// explicit metavar for the generated usage
spec.metavar = metavar
}
spec.description = t.Tag.Get("description")
if spec.description == "" {
spec.description = t.Tag.Get("desc")
}
spec.defval = t.Tag.Get("default")
switch t.Tag.Get("required") {
case "true":
spec.required = true
case "false":
spec.required = false
case "":
if spec.defval != "" {
spec.required = false
}
default:
abort("invalid required value")
}
if aliases := t.Tag.Get("aliases"); aliases != "" {
spec.aliases = strings.Split(aliases, ",")
}
if methodName, found := t.Tag.Lookup("action"); found {
method := struc.MethodByName(methodName)
if !method.IsValid() {
abort("action method not found: (*%s).%s", struc, methodName)
}
ok := method.Type().NumIn() == 1
ok = ok && method.Type().In(0).Kind() == reflect.String
ok = ok && method.Type().NumOut() == 1
ok = ok && method.Type().Out(0).Kind() == reflect.Interface
ok = ok && method.Type().Out(0).Name() == "error"
if !ok {
abort("(*%s).%s: invalid signature, expected func(string) error",
struc.Elem().Type().Name(), methodName,
t.Type.Kind())
}
spec.action = method
}
if !spec.action.IsValid() {
switch t.Type.Kind() {
case reflect.String:
fallthrough
case reflect.Bool:
fallthrough
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fallthrough
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
fallthrough
case reflect.Float32, reflect.Float64:
fallthrough
case reflect.Slice:
break
default:
abort("unsupported field type: %s", t.Type.Kind())
}
}
if methodName, found := t.Tag.Lookup("complete"); found {
method := struc.MethodByName(methodName)
if !method.IsValid() {
abort("complete method not found: (*%s).%s", struc, methodName)
}
if !(method.Type().NumIn() == 1 &&
method.Type().In(0).Kind() == reflect.String &&
method.Type().NumOut() == 1 &&
method.Type().Out(0).Kind() == reflect.Slice &&
method.Type().Out(0).Elem().Kind() == reflect.String) {
abort("(*%s).%s: invalid signature, expected func(string) []string",
struc.Elem().Type().Name(), methodName,
t.Type.Kind())
}
spec.complete = method
}
}
func (s *optSpec) Usage() string {
var usage string
switch s.kind {
case flag:
if s.short != "" {
usage = s.short
} else {
usage = s.long
}
case option:
if s.short != "" {
usage = s.short
} else {
usage = s.long
}
usage += " " + s.metavar
default:
usage = s.metavar
}
if s.required {
return usage
}
return "[" + usage + "]"
}
func (s *optSpec) Flag() string {
var usage string
switch s.kind {
case flag, option:
if s.short != "" {
usage = s.short
} else {
usage = s.long
}
default:
usage = s.metavar
}
return usage
}
func (c *CmdSpec) Usage() string {
if c.passthrough {
return c.name + " ..."
}
args := []string{c.name}
for _, spec := range c.opts {
if spec.appliesToAlias(c.name) {
args = append(args, spec.Usage())
}
}
return strings.Join(args, " ")
}
type errKind int
const (
unknownErr errKind = iota
missingValue
takesNoValue
unknownFlag
unexpectedArg
badValue
requiredArg
)
type ArgError struct {
kind errKind
spec *optSpec
err error
}
func (e *ArgError) Error() string {
switch e.kind {
case missingValue:
return fmt.Sprintf("%s takes a value", e.spec.Flag())
case takesNoValue:
return fmt.Sprintf("%s does not take a value", e.spec.Flag())
case unknownFlag:
return fmt.Sprintf("%s unknown flag", e.err)
case unexpectedArg:
return fmt.Sprintf("%q unexpected argument", e.err.Error())
case badValue:
return fmt.Sprintf("%s: %s", e.spec.Flag(), e.err)
case requiredArg:
return fmt.Sprintf("%s is required", e.spec.Flag())
default:
return fmt.Sprintf("unknown error: %#v", e)
}
}
func (c *CmdSpec) ParseArgs(args *Args) error {
if c.passthrough {
return nil
}
if errors := c.parseArgs(args); len(errors) > 0 {
return errors[0]
}
return nil
}
func (c *CmdSpec) markSeen(spec *optSpec, index int) *seenArg {
spec.seen = true
arg := &seenArg{spec: spec, indexes: []int{index}}
c.seen = append(c.seen, arg)
return arg
}
func (c *CmdSpec) parseArgs(args *Args) []*ArgError {
var cur *seenArg
var argErrors []*ArgError
fail := func(kind errKind, s *optSpec, detail error) {
argErrors = append(argErrors, &ArgError{kind, s, detail})
}
positionals := c.positionals
ignoreFlags := false
c.seen = nil
args.Shift(1) // skip command name
i := 1
for args.Count() > 0 {
arg := args.Arg(0)
switch {
case c.getLongFlag(arg) != nil && !ignoreFlags:
if cur != nil {
fail(missingValue, cur.spec, nil)
}
arg, val, hasValue := strings.Cut(arg, "=")
cur = c.markSeen(&c.opts[c.longOpts[arg]], i)
if cur.spec.kind == flag {
if hasValue {
fail(takesNoValue, cur.spec, nil)
cur = nil
goto next
}
if err := cur.spec.parseValue("true"); err != nil {
fail(badValue, cur.spec, err)
}
cur = nil
} else if hasValue {
if err := cur.spec.parseValue(val); err != nil {
fail(badValue, cur.spec, err)
}
cur = nil
}
case c.getShortFlag(arg) != nil && !ignoreFlags:
if cur != nil {
fail(missingValue, cur.spec, nil)
}
arg = arg[1:]
for len(arg) > 0 {
f := arg[:1]
arg = arg[1:]
var spec *optSpec
if o, ok := c.shortOpts["-"+f]; ok {
spec = &c.opts[o]
}
if spec == nil || !spec.appliesToAlias(c.name) {
fail(unknownFlag, spec, errors.New(f))
goto next
}
cur = c.markSeen(spec, i)
if spec.kind == flag {
if err := spec.parseValue("true"); err != nil {
fail(badValue, spec, err)
}
cur = nil
} else if len(arg) > 0 {
if err := spec.parseValue(arg); err != nil {
fail(badValue, spec, err)
}
cur = nil
arg = ""
}
}
default:
// positional
if cur != nil {
// separate value for a short/long flag
cur.indexes = append(cur.indexes, i)
if err := cur.spec.parseValue(arg); err != nil {
fail(badValue, cur.spec, err)
}
cur = nil
goto next
}
for len(positionals) > 0 {
spec := &c.opts[positionals[0]]
positionals = positionals[1:]
if spec.appliesToAlias(c.name) {
cur = c.markSeen(spec, i)
break
}
}
if arg == optionDelim {
ignoreFlags = true
goto next
}
if cur == nil {
fail(unexpectedArg, nil, errors.New(arg))
goto next
}
switch cur.spec.kind {
case remainder:
cur.spec.dest.SetString(args.String())
for args.Count() > 0 {
i += 1
cur.indexes = append(cur.indexes, i)
args.Shift(1)
}
cur.spec.seenValue = true
case remainderSplit:
cur.spec.dest.Set(reflect.ValueOf(args.Args()))
for args.Count() > 0 {
i += 1
cur.indexes = append(cur.indexes, i)
args.Shift(1)
}
cur.spec.seenValue = true
default:
if err := cur.spec.parseValue(arg); err != nil {
fail(badValue, cur.spec, err)
}
}
cur = nil
}
next:
args.Shift(1)
i += 1
}
if cur != nil {
fail(missingValue, cur.spec, nil)
}
for i := 0; i < len(c.opts); i++ {
spec := &c.opts[i]
if !spec.appliesToAlias(c.name) {
continue
}
if !spec.seen && spec.defval != "" {
if err := spec.parseValue(spec.defval); err != nil {
fail(missingValue, spec, nil)
}
} else if spec.required && !spec.seen {
fail(requiredArg, spec, nil)
}
}
return argErrors
}
func (c *CmdSpec) getShortFlag(arg string) *optSpec {
if len(arg) <= 1 || !strings.HasPrefix(arg, "-") {
return nil
}
if o, ok := c.shortOpts[arg[:2]]; ok {
spec := &c.opts[o]
if spec.appliesToAlias(c.name) {
return spec
}
}
return nil
}
func (c *CmdSpec) getLongFlag(arg string) *optSpec {
if len(arg) <= 2 || !strings.HasPrefix(arg, "--") {
return nil
}
arg, _, _ = strings.Cut(arg, "=")
if o, ok := c.longOpts[arg]; ok {
spec := &c.opts[o]
if spec.appliesToAlias(c.name) {
return spec
}
}
return nil
}
func (s *optSpec) parseValue(arg string) error {
s.seenValue = true
if s.action.IsValid() {
in := []reflect.Value{reflect.ValueOf(arg)}
out := s.action.Call(in)
err, _ := out[0].Interface().(error)
return err
}
switch s.dest.Type().Kind() {
case reflect.String:
s.dest.SetString(arg)
case reflect.Bool:
if b, err := strconv.ParseBool(arg); err == nil {
s.dest.SetBool(b)
} else {
return err
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if i, err := strconv.ParseInt(arg, 10, 64); err == nil {
s.dest.SetInt(i)
} else {
return err
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if u, err := strconv.ParseUint(arg, 10, 64); err == nil {
s.dest.SetUint(u)
} else {
return err
}
case reflect.Float32, reflect.Float64:
if f, err := strconv.ParseFloat(arg, 64); err == nil {
s.dest.SetFloat(f)
} else {
return err
}
default:
return fmt.Errorf("unsupported type: %s", s.dest)
}
return nil
}
func (s *optSpec) appliesToAlias(alias string) bool {
if s.aliases == nil {
return true
}
for _, a := range s.aliases {
if a == alias {
return true
}
}
return false
}
|