Allow commands to explicitly state if they do, or do not take arbitrary arguments
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Check that arguments are in ValidArgs If a command defined cmd.ValidArgs check that the argument is actually in ValidArgs and fail if it is not.
authored by Eric Paris · committed by Albert Nigmatzianov · parent 715f41b · Browse files · 4 files·+156 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+156 added−21 removed
- other:+156 added−21 removed
Provenance
- Commit
d89c499- Tree
15ae69d- Author
Eric Paris <eparis@redhat.com>- Committer
Albert Nigmatzianov <albertnigma@gmail.com>- Parent
715f41b
4 files changed+156 added−21 removed
modified:bash_completions_test.go+2 added
115 unmodified lines116 checkOmit(t, str, `must_have_one_noun+=("pods")`)117 // check for filename extension flags118 check(t, str, `flags_completion+=("_filedir")`)119 // check for filename extension flags120+ check(t, str, `must_have_one_noun+=("three")`)121+ // check for filename extention flags122 check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)123 // check for custom flags124 check(t, str, `flags_completion+=("__complete_custom")`)125 // check for subdirs_in_dir flags69 unmodified linesmodified:cobra_test.go+64 added-5 removed
73 unmodified lines74 Long: `an absolutely utterly useless command for testing deprecation!.`,75 Deprecated: "Please use echo instead",76 Run: func(cmd *Command, args []string) {77 },78+ TakesArgs: None,79 }80 81 var cmdTimes = &Command{82 Use: "times [# times] [string to echo]",5 unmodified lines88 },89 Run: func(cmd *Command, args []string) {90 tt = args91 },92+ TakesArgs: ValidOnly,93+ ValidArgs: []string{"one", "two", "three", "four"},94 }95 96 var cmdRootNoRun = &Command{97 Use: "cobra-test",4 unmodified lines102 },103 }104 105 var cmdRootSameName = &Command{103- Use: "print",104- Short: "Root with the same name as a subcommand",105- Long: "The root description for help",106+ Use: "print",107+ Short: "Root with the same name as a subcommand",108+ Long: "The root description for help",109+ TakesArgs: None,110 }111 112+var cmdRootTakesArgs = &Command{113+ Use: "root-with-args [random args]",114+ Short: "The root can run it's own function and takes args!",115+ Long: "The root description for help, and some args",116+ Run: func(cmd *Command, args []string) {117+ tr = args118+ },119+ TakesArgs: Arbitrary,120+}121+122 var cmdRootWithRun = &Command{123 Use: "cobra-test",124 Short: "The root can run its own function",125 Long: "The root description for help",345 unmodified lines471 checkResultContains(t, x, cmdCustomFlags.Use)472 checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")473 }474 475+func TestRootTakesNoArgs(t *testing.T) {476+ c := initializeWithSameName()477+ c.AddCommand(cmdPrint, cmdEcho)478+ result := simpleTester(c, "illegal")479+480+ expectedError := `unknown command "illegal" for "print"`481+ if !strings.Contains(result.Error.Error(), expectedError) {482+ t.Errorf("exptected %v, got %v", expectedError, result.Error.Error())483+ }484+}485+486+func TestRootTakesArgs(t *testing.T) {487+ c := cmdRootTakesArgs488+ result := simpleTester(c, "legal")489+490+ if result.Error != nil {491+ t.Errorf("expected no error, but got %v", result.Error)492+ }493+}494+495+func TestSubCmdTakesNoArgs(t *testing.T) {496+ result := fullSetupTest("deprecated illegal")497+498+ expectedError := `unknown command "illegal" for "cobra-test deprecated"`499+ if !strings.Contains(result.Error.Error(), expectedError) {500+ t.Errorf("expected %v, got %v", expectedError, result.Error.Error())501+ }502+}503+504+func TestSubCmdTakesArgs(t *testing.T) {505+ noRRSetupTest("echo times one two")506+ if strings.Join(tt, " ") != "one two" {507+ t.Error("Command didn't parse correctly")508+ }509+}510+511+func TestCmdOnlyValidArgs(t *testing.T) {512+ result := noRRSetupTest("echo times one two five")513+514+ expectedError := `invalid argument "five"`515+ if !strings.Contains(result.Error.Error(), expectedError) {516+ t.Errorf("expected %v, got %v", expectedError, result.Error.Error())517+ }518+}519+520 func TestFlagLong(t *testing.T) {521 noRRSetupTest("echo", "--intone=13", "something", "--", "here")522 523 if cmdEcho.ArgsLenAtDash() != 1 {206 unmodified lines730 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)731 }732 733 // persistentFlag should act like normal flag on its own command675- fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "test", "here")734+ fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "one", "two")735 677- if strings.Join(tt, " ") != "test here" {736+ if strings.Join(tt, " ") != "one two" {737 t.Errorf("flags didn't leave proper args remaining. %s given", tt)738 }739 740 if flags1 != "again" {492 unmodified linesmodified:command.go+58 added-16 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+39 // Command is just that, a command for your application.40 // E.g. 'go run ...' - 'run' is the command. Cobra requires41 // you to define the usage and description as part of your command42 // definition to ensure usability.24 unmodified lines67 // These are not suggested to the user in the bash completion,68 // but accepted if entered manually.69 ArgAliases []string70 71+ // Does this command take arbitrary arguments72+ TakesArgs Args73 // BashCompletionFunction is custom functions used by the bash autocompletion generator.74 BashCompletionFunction string75 76 // Deprecated defines, if this command is deprecated and should print this string when used.405 unmodified lines482 }483 return args484 }485 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+495 // Find the target command given the args and command tree496 // Meant to be run on the highest node. Only searches down.497 func (c *Command) Find(args []string) (*Command, []string, error) {498 if c == nil {35 unmodified lines534 535 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 {518- // no subcommand, always take args519- if !commandFound.HasSubCommands() {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, nil552 }553 523- // root command with subcommands, do subcommand checking524- if commandFound == c && len(argsWOflags) > 0 {525- suggestionsString := ""526- if !c.DisableSuggestions {527- if c.SuggestionsMinimumDistance <= 0 {528- c.SuggestionsMinimumDistance = 2554+ 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 }530- if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {531- suggestionsString += "\n\nDid you mean this?\n"532- for _, s := range suggestions {533- suggestionsString += fmt.Sprintf("\t%v\n", s)534- }535- }563 }537- return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)564 }539-565 return commandFound, a, nil566 }567 568+func (c *Command) findSuggestions(argsWOflags []string) string {569+ if c.DisableSuggestions {570+ return ""571+ }572+ if c.SuggestionsMinimumDistance <= 0 {573+ c.SuggestionsMinimumDistance = 2574+ }575+ suggestionsString := ""576+ if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {577+ suggestionsString += "\n\nDid you mean this?\n"578+ for _, s := range suggestions {579+ suggestionsString += fmt.Sprintf("\t%v\n", s)580+ }581+ }582+ return suggestionsString583+}584+585 // SuggestionsFor provides suggestions for the typedName.586 func (c *Command) SuggestionsFor(typedName string) []string {587 suggestions := []string{}588 for _, cmd := range c.commands {750 unmodified linesmodified:README.md+32 added
465 unmodified lines466 ```go467 RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")468 ```469 470+### Specify if you command takes 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`477+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 checking482+483+`None` the command will be rejected if there are any left over arguments after parsing flags.484+485+`Arbitrary` any additional values left after parsing flags will be passed in to your `Run` function.486+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+489+```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+ }500+```501+502 ### Bind Flags with Config503 504 You can also bind your flags with [viper](https://github.com/spf13/viper):505 ```go467 unmodified lines