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
Provenance
- Commit
f20b4e9- Tree
63a9ac7- Author
Daniel Nephin <dnephin@gmail.com>- Committer
Albert Nigmatzianov <albertnigma@gmail.com>- Parent
d89c499
4 files changed+160 added−84 removed
added:args.go+98 added
1+package cobra2+3+import (4+ "fmt"5+)6+7+type PositionalArgs func(cmd *Command, args []string) error8+9+// 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 arguments13+func legacyArgs(cmd *Command, args []string) error {14+ // no subcommand, always take args15+ if !cmd.HasSubCommands() {16+ return nil17+ }18+19+ // 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+}25+26+// NoArgs returns an error if any args are included27+func 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+}33+34+// OnlyValidArgs returns an error if any args are not in the list of ValidArgs35+func 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+}45+46+func stringInSlice(a string, list []string) bool {47+ for _, b := range list {48+ if b == a {49+ return true50+ }51+ }52+ return false53+}54+55+// ArbitraryArgs never returns an error56+func ArbitraryArgs(cmd *Command, args []string) error {57+ return nil58+}59+60+// MinimumNArgs returns an error if there is not at least N args61+func 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+}69+70+// MaximumNArgs returns an error if there are more than N args71+func 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+}79+80+// ExactArgs returns an error if there are not exactly n args81+func 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+}89+90+// RangeArgs returns an error if the number of args is not within the expected range91+func 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 lines35 }36 37 var 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 = args31 unmodified lines75 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 }81 82 var cmdTimes = &Command{83 Use: "times [# times] [string to echo]",5 unmodified lines89 },90 Run: func(cmd *Command, args []string) {91 tt = args92 },92- TakesArgs: ValidOnly,93+ Args: OnlyValidArgs,94 ValidArgs: []string{"one", "two", "three", "four"},95 }96 97 var cmdRootNoRun = &Command{5 unmodified lines103 },104 }105 106 var 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 }111 112 var cmdRootTakesArgs = &Command{113 Use: "root-with-args [random args]",1 unmodified line115 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 }121 122 var cmdRootWithRun = &Command{123 Use: "cobra-test",352 unmodified lines476 c := initializeWithSameName()477 c.AddCommand(cmdPrint, cmdEcho)478 result := simpleTester(c, "illegal")479 480+ if result.Error == nil {481+ t.Fatal("Expected an error")482+ }483+484 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 lines496 }497 }498 499 func TestSubCmdTakesNoArgs(t *testing.T) {496- result := fullSetupTest("deprecated illegal")500+ result := fullSetupTest("deprecated", "illegal")501 502+ if result.Error == nil {503+ t.Fatal("Expected an error")504+ }505+506 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 }511 512 func 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 }518 519 func TestCmdOnlyValidArgs(t *testing.T) {512- result := noRRSetupTest("echo times one two five")520+ result := noRRSetupTest("echo", "times", "one", "two", "five")521 522+ if result.Error == nil {523+ t.Fatal("Expected an error")524+ }525+526 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 linesmodified:command.go+17 added-50 removed
25 unmodified lines26 27 flag "github.com/spf13/pflag"28 )29 30-type Args int31-32-const (33- Legacy Args = iota34- Arbitrary35- ValidOnly36- None37-)38-30 // 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 lines58 // These are not suggested to the user in the bash completion,59 // but accepted if entered manually.60 ArgAliases []string61 71- // Does this command take arbitrary arguments72- TakesArgs Args62+ // Expected arguments63+ Args PositionalArgs64 // BashCompletionFunction is custom functions used by the bash autocompletion generator.65 BashCompletionFunction string66 67 // Deprecated defines, if this command is deprecated and should print this string when used.405 unmodified lines473 }474 return args475 }476 486-func stringInSlice(a string, list []string) bool {487- for _, b := range list {488- if b == a {489- return true490- }491- }492- return false493-}494-477 // Find the target command given the args and command tree478 // Meant to be run on the highest node. Only searches down.479 func (c *Command) Find(args []string) (*Command, []string, error) {480 if c == nil {33 unmodified lines514 return c, innerArgs515 }516 517 commandFound, a := innerfind(c, args)536- argsWOflags := stripFlags(a, commandFound)537-538- // "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 }553-554- if commandFound.TakesArgs == None && len(argsWOflags) > 0 {555- return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())556- }557-558- 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 }523 568-func (c *Command) findSuggestions(argsWOflags []string) string {524+func (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 lines621 if c.DisableFlagParsing {622 argWoFlags = a623 }624 625+ if err := c.ValidateArgs(argWoFlags); err != nil {626+ return err627+ }628+629 for p := c; p != nil; p = p.Parent() {630 if p.PersistentPreRunE != nil {631 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {632 return err115 unmodified lines748 }749 return cmd, err750 }751 752+func (c *Command) ValidateArgs(args []string) error {753+ if c.Args == nil {754+ return nil755+ }756+ return c.Args(c, args)757+}758+759 // 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.762 func (c *Command) InitDefaultHelpFlag() {543 unmodified linesmodified:README.md+23 added-24 removed
465 unmodified lines466 ```go467 RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")468 ```469 470-### Specify if you command takes arguments470+## Positional and Custom Arguments471 472-There 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`472+Validation of positional arguments can be specified using the `Args` field.473 478-`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 checking474+The follow validators are built in:475 483-`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.483 485-`Arbitrary` any additional values left after parsing flags will be passed in to your `Run` function.484+A custom validator can be provided like this:485 487-`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:488-486 ```go490-var 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- }487+488+Args: 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+}497+498 ```499 500 ### Bind Flags with Config501 12 unmodified lines514 when the `--author` flag is not provided by user.515 516 More in [viper documentation](https://github.com/spf13/viper#working-with-flags).517 518+519 ## Example520 521 In the example below, we have defined three commands. Two are at the top level522 and one (cmdTimes) is a child of one of the top commands. In this case the root449 unmodified lines