Skip to content
Myr

Refactor TakesArgs to use an interface for arg validation.

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

Fix some typos in README and comments. Move arg validation to after flag validation so that the help flag is run first. Pass the same args to ValidateArgs as the Run methods receive. Update README.

authored by Daniel Nephin · committed by Albert Nigmatzianov · parent d89c499 · Browse files · 4 files+160 added−84 removed
This commit

State

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

Trailers

  • Signed-off-by: Daniel Nephin <dnephin@gmail.com>

Diff stats

4 files+160 added−84 removed

  • other:+160 added−84 removed

4 files+160 added−84 removed

added:args.go+98 added
1package cobra23import (4 "fmt"5)67type PositionalArgs func(cmd *Command, args []string) error89// Legacy arg validation has the following behaviour:10// - root commands with no subcommands can take arbitrary arguments11// - root commands with subcommands will do subcommand validity checking12// - subcommands will always accept arbitrary arguments13func legacyArgs(cmd *Command, args []string) error {14 // no subcommand, always take args15 if !cmd.HasSubCommands() {16 return nil17 }1819 // root command with subcommands, do subcommand checking20 if !cmd.HasParent() && len(args) > 0 {21 return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))22 }23 return nil24}2526// NoArgs returns an error if any args are included27func NoArgs(cmd *Command, args []string) error {28 if len(args) > 0 {29 return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())30 }31 return nil32}3334// OnlyValidArgs returns an error if any args are not in the list of ValidArgs35func OnlyValidArgs(cmd *Command, args []string) error {36 if len(cmd.ValidArgs) > 0 {37 for _, v := range args {38 if !stringInSlice(v, cmd.ValidArgs) {39 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))40 }41 }42 }43 return nil44}4546func stringInSlice(a string, list []string) bool {47 for _, b := range list {48 if b == a {49 return true50 }51 }52 return false53}5455// ArbitraryArgs never returns an error56func ArbitraryArgs(cmd *Command, args []string) error {57 return nil58}5960// MinimumNArgs returns an error if there is not at least N args61func MinimumNArgs(n int) PositionalArgs {62 return func(cmd *Command, args []string) error {63 if len(args) < n {64 return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))65 }66 return nil67 }68}6970// MaximumNArgs returns an error if there are more than N args71func MaximumNArgs(n int) PositionalArgs {72 return func(cmd *Command, args []string) error {73 if len(args) > n {74 return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))75 }76 return nil77 }78}7980// ExactArgs returns an error if there are not exactly n args81func ExactArgs(n int) PositionalArgs {82 return func(cmd *Command, args []string) error {83 if len(args) != n {84 return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))85 }86 return nil87 }88}8990// RangeArgs returns an error if the number of args is not within the expected range91func RangeArgs(min int, max int) PositionalArgs {92 return func(cmd *Command, args []string) error {93 if len(args) < min || len(args) > max {94 return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))95 }96 return nil97 }98}
modified:cobra_test.go+22 added-10 removed
34 unmodified lines
35}3637var cmdPrint = &Command{38 Use: "print [string to print]",39 Args: MinimumNArgs(1),40 Short: "Print anything to the screen",41 Long: `an absolutely utterly useless command for testing.`,42 Run: func(cmd *Command, args []string) {43 tp = args
31 unmodified lines
75 Long: `an absolutely utterly useless command for testing deprecation!.`,76 Deprecated: "Please use echo instead",77 Run: func(cmd *Command, args []string) {78 },78 TakesArgs: None,79 Args: NoArgs,80}8182var cmdTimes = &Command{83 Use: "times [# times] [string to echo]",
5 unmodified lines
89 },90 Run: func(cmd *Command, args []string) {91 tt = args92 },92 TakesArgs: ValidOnly,93 Args: OnlyValidArgs,94 ValidArgs: []string{"one", "two", "three", "four"},95}9697var cmdRootNoRun = &Command{
5 unmodified lines
103 },104}105106var cmdRootSameName = &Command{106 Use: "print",107 Short: "Root with the same name as a subcommand",108 Long: "The root description for help",109 TakesArgs: None,107 Use: "print",108 Short: "Root with the same name as a subcommand",109 Long: "The root description for help",110}111112var cmdRootTakesArgs = &Command{113 Use: "root-with-args [random args]",
1 unmodified line
115 Long: "The root description for help, and some args",116 Run: func(cmd *Command, args []string) {117 tr = args118 },119 TakesArgs: Arbitrary,119 Args: ArbitraryArgs,120}121122var cmdRootWithRun = &Command{123 Use: "cobra-test",
352 unmodified lines
476 c := initializeWithSameName()477 c.AddCommand(cmdPrint, cmdEcho)478 result := simpleTester(c, "illegal")479480 if result.Error == nil {481 t.Fatal("Expected an error")482 }483484 expectedError := `unknown command "illegal" for "print"`485 if !strings.Contains(result.Error.Error(), expectedError) {486 t.Errorf("exptected %v, got %v", expectedError, result.Error.Error())487 }
8 unmodified lines
496 }497}498499func TestSubCmdTakesNoArgs(t *testing.T) {496 result := fullSetupTest("deprecated illegal")500 result := fullSetupTest("deprecated", "illegal")501502 if result.Error == nil {503 t.Fatal("Expected an error")504 }505506 expectedError := `unknown command "illegal" for "cobra-test deprecated"`507 if !strings.Contains(result.Error.Error(), expectedError) {508 t.Errorf("expected %v, got %v", expectedError, result.Error.Error())509 }510}511512func TestSubCmdTakesArgs(t *testing.T) {505 noRRSetupTest("echo times one two")513 noRRSetupTest("echo", "times", "one", "two")514 if strings.Join(tt, " ") != "one two" {515 t.Error("Command didn't parse correctly")516 }517}518519func TestCmdOnlyValidArgs(t *testing.T) {512 result := noRRSetupTest("echo times one two five")520 result := noRRSetupTest("echo", "times", "one", "two", "five")521522 if result.Error == nil {523 t.Fatal("Expected an error")524 }525526 expectedError := `invalid argument "five"`527 if !strings.Contains(result.Error.Error(), expectedError) {528 t.Errorf("expected %v, got %v", expectedError, result.Error.Error())529 }
715 unmodified lines
modified:command.go+17 added-50 removed
25 unmodified lines
2627 flag "github.com/spf13/pflag"28)2930type Args int3132const (33 Legacy Args = iota34 Arbitrary35 ValidOnly36 None37)3830// Command is just that, a command for your application.31// E.g. 'go run ...' - 'run' is the command. Cobra requires32// you to define the usage and description as part of your command33// definition to ensure usability.
24 unmodified lines
58 // These are not suggested to the user in the bash completion,59 // but accepted if entered manually.60 ArgAliases []string6171 // Does this command take arbitrary arguments72 TakesArgs Args62 // Expected arguments63 Args PositionalArgs64 // BashCompletionFunction is custom functions used by the bash autocompletion generator.65 BashCompletionFunction string6667 // Deprecated defines, if this command is deprecated and should print this string when used.
405 unmodified lines
473 }474 return args475}476486func stringInSlice(a string, list []string) bool {487 for _, b := range list {488 if b == a {489 return true490 }491 }492 return false493}494477// Find the target command given the args and command tree478// Meant to be run on the highest node. Only searches down.479func (c *Command) Find(args []string) (*Command, []string, error) {480 if c == nil {
33 unmodified lines
514 return c, innerArgs515 }516517 commandFound, a := innerfind(c, args)536 argsWOflags := stripFlags(a, commandFound)537538 // "Legacy" has some 'odd' characteristics.539 // - root commands with no subcommands can take arbitrary arguments540 // - root commands with subcommands will do subcommand validity checking541 // - subcommands will always accept arbitrary arguments542 if commandFound.TakesArgs == Legacy {543 // no subcommand, always take args544 if !commandFound.HasSubCommands() {545 return commandFound, a, nil546 }547 // root command with subcommands, do subcommand checking548 if commandFound == c && len(argsWOflags) > 0 {549 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), c.findSuggestions(argsWOflags))550 }551 return commandFound, a, nil518 if commandFound.Args == nil {519 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))520 }553554 if commandFound.TakesArgs == None && len(argsWOflags) > 0 {555 return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())556 }557558 if commandFound.TakesArgs == ValidOnly && len(commandFound.ValidArgs) > 0 {559 for _, v := range argsWOflags {560 if !stringInSlice(v, commandFound.ValidArgs) {561 return commandFound, a, fmt.Errorf("invalid argument %q for %q%s", v, commandFound.CommandPath(), c.findSuggestions(argsWOflags))562 }563 }564 }521 return commandFound, a, nil522}523568func (c *Command) findSuggestions(argsWOflags []string) string {524func (c *Command) findSuggestions(arg string) string {525 if c.DisableSuggestions {526 return ""527 }528 if c.SuggestionsMinimumDistance <= 0 {529 c.SuggestionsMinimumDistance = 2530 }531 suggestionsString := ""576 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {532 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {533 suggestionsString += "\n\nDid you mean this?\n"534 for _, s := range suggestions {535 suggestionsString += fmt.Sprintf("\t%v\n", s)536 }
84 unmodified lines
621 if c.DisableFlagParsing {622 argWoFlags = a623 }624625 if err := c.ValidateArgs(argWoFlags); err != nil {626 return err627 }628629 for p := c; p != nil; p = p.Parent() {630 if p.PersistentPreRunE != nil {631 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {632 return err
115 unmodified lines
748 }749 return cmd, err750}751752func (c *Command) ValidateArgs(args []string) error {753 if c.Args == nil {754 return nil755 }756 return c.Args(c, args)757}758759// InitDefaultHelpFlag adds default help flag to c.760// It is called automatically by executing the c or by calling help and usage.761// If c already has help flag, it will do nothing.762func (c *Command) InitDefaultHelpFlag() {
543 unmodified lines
modified:README.md+23 added-24 removed
465 unmodified lines
466```go467RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")468```469470### Specify if you command takes arguments470## Positional and Custom Arguments471472There are multiple options for how a command can handle unknown arguments which can be set in `TakesArgs`473- `Legacy`474- `None`475- `Arbitrary`476- `ValidOnly`472Validation of positional arguments can be specified using the `Args` field.473478`Legacy` (or default) the rules are as follows:479- root commands with no subcommands can take arbitrary arguments480- root commands with subcommands will do subcommand validity checking481- subcommands will always accept arbitrary arguments and do no subsubcommand validity checking474The follow validators are built in:475483`None` the command will be rejected if there are any left over arguments after parsing flags.476- `NoArgs` - the command will report an error if there are any positional args.477- `ArbitraryArgs` - the command will accept any args.478- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the ValidArgs list.479- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.480- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.481- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.482- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.483485`Arbitrary` any additional values left after parsing flags will be passed in to your `Run` function.484A custom validator can be provided like this:485487`ValidOnly` you must define all valid (non-subcommand) arguments to your command. These are defined in a slice name ValidArgs. For example a command which only takes the argument "one" or "two" would be defined as:488486```go490var HugoCmd = &cobra.Command{491 Use: "hugo",492 Short: "Hugo is a very fast static site generator",493 ValidArgs: []string{"one", "two", "three", "four"}494 TakesArgs: cobra.ValidOnly495 Run: func(cmd *cobra.Command, args []string) {496 // args will only have the values one, two, three, four497 // or the cmd.Execute() will fail.498 },499 }487488Args: func validColorArgs(cmd *cobra.Command, args []string) error {489 if err := cli.RequiresMinArgs(1)(cmd, args); err != nil {490 return err491 }492 if myapp.IsValidColor(args[0]) {493 return nil494 }495 return fmt.Errorf("Invalid color specified: %s", args[0])496}497498```499500### Bind Flags with Config501
12 unmodified lines
514when the `--author` flag is not provided by user.515516More in [viper documentation](https://github.com/spf13/viper#working-with-flags).517518519## Example520521In the example below, we have defined three commands. Two are at the top level522and one (cmdTimes) is a child of one of the top commands. In this case the root
449 unmodified lines