Skip to content
Myr

Fix subcommand locations with NoOptDefValue flags (#391)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

If one ran a command like ./root --boolFlag subcmd1 subcmd2 Thing worked fine. The code recognized that --boolFlag followed by a space meant the next word was not the argument to --boolFlag. But other flag types with a NoOptDefValue (like a Count flag) would not ignore the "argument". On a command like: ./root --countflag subcmd1 subcmd2 The processor, when looking for a subcommand, would first throw out the `--countflag subcmd1` and then look for subcmd2 under root. The fix is to ignore the next word after any NoOptDefVal flag, not just boolean flags.

authored by Eric Paris · committed by GitHub · parent ee40558 · Browse files · 1 file+7 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+7 added−9 removed

  • other:+7 added−9 removed

1 file+7 added−9 removed

modified:command.go+7 added-9 removed
382 unmodified lines
383 x.parent = c384 }385}386387// Test if the named flag is a boolean flag.388func isBooleanFlag(name string, f *flag.FlagSet) bool {387func hasNoOptDefVal(name string, f *flag.FlagSet) bool {388 flag := f.Lookup(name)389 if flag == nil {390 return false391 }393 return flag.Value.Type() == "bool"392 return len(flag.NoOptDefVal) > 0393}394396// Test if the named flag is a boolean flag.397func isBooleanShortFlag(name string, f *flag.FlagSet) bool {395func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {396 result := false399 f.VisitAll(func(f *flag.Flag) {400 if f.Shorthand == name && f.Value.Type() == "bool" {397 fs.VisitAll(func(flag *flag.Flag) {398 if flag.Shorthand == name && len(flag.NoOptDefVal) > 0 {399 result = true400 }401 })402 return result
17 unmodified lines
420 case strings.Contains(y, "=\""):421 inQuote = true422 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):423 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'426 inFlag = !isBooleanFlag(y[2:], c.Flags())427 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):424 inFlag = !hasNoOptDefVal(y[2:], c.Flags())425 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !shortHasNoOptDefVal(y[1:], c.Flags()):426 inFlag = true427 case inFlag:428 inFlag = false429 case y == "":
878 unmodified lines