Skip to content
Myr

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

4 files+156 added−21 removed

modified:bash_completions_test.go+2 added
115 unmodified lines
116 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 flags
69 unmodified lines
modified:cobra_test.go+64 added-5 removed
73 unmodified lines
74 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}8081var cmdTimes = &Command{82 Use: "times [# times] [string to echo]",
5 unmodified lines
88 },89 Run: func(cmd *Command, args []string) {90 tt = args91 },92 TakesArgs: ValidOnly,93 ValidArgs: []string{"one", "two", "three", "four"},94}9596var cmdRootNoRun = &Command{97 Use: "cobra-test",
4 unmodified lines
102 },103}104105var 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}111112var 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}121122var cmdRootWithRun = &Command{123 Use: "cobra-test",124 Short: "The root can run its own function",125 Long: "The root description for help",
345 unmodified lines
471 checkResultContains(t, x, cmdCustomFlags.Use)472 checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")473}474475func TestRootTakesNoArgs(t *testing.T) {476 c := initializeWithSameName()477 c.AddCommand(cmdPrint, cmdEcho)478 result := simpleTester(c, "illegal")479480 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}485486func TestRootTakesArgs(t *testing.T) {487 c := cmdRootTakesArgs488 result := simpleTester(c, "legal")489490 if result.Error != nil {491 t.Errorf("expected no error, but got %v", result.Error)492 }493}494495func TestSubCmdTakesNoArgs(t *testing.T) {496 result := fullSetupTest("deprecated illegal")497498 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}503504func 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}510511func TestCmdOnlyValidArgs(t *testing.T) {512 result := noRRSetupTest("echo times one two five")513514 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}519520func TestFlagLong(t *testing.T) {521 noRRSetupTest("echo", "--intone=13", "something", "--", "here")522523 if cmdEcho.ArgsLenAtDash() != 1 {
206 unmodified lines
730 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)731 }732733 // 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")735677 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 }739740 if flags1 != "again" {
492 unmodified lines
modified:command.go+58 added-16 removed
25 unmodified lines
2627 flag "github.com/spf13/pflag"28)2930type Args int3132const (33 Legacy Args = iota34 Arbitrary35 ValidOnly36 None37)3839// 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 lines
67 // These are not suggested to the user in the bash completion,68 // but accepted if entered manually.69 ArgAliases []string7071 // Does this command take arbitrary arguments72 TakesArgs Args73 // BashCompletionFunction is custom functions used by the bash autocompletion generator.74 BashCompletionFunction string7576 // Deprecated defines, if this command is deprecated and should print this string when used.
405 unmodified lines
482 }483 return args484}485486func stringInSlice(a string, list []string) bool {487 for _, b := range list {488 if b == a {489 return true490 }491 }492 return false493}494495// Find the target command given the args and command tree496// Meant to be run on the highest node. Only searches down.497func (c *Command) Find(args []string) (*Command, []string, error) {498 if c == nil {
35 unmodified lines
534535 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 {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 }553523 // 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 }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 }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 }539565 return commandFound, a, nil566}567568func (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}584585// SuggestionsFor provides suggestions for the typedName.586func (c *Command) SuggestionsFor(typedName string) []string {587 suggestions := []string{}588 for _, cmd := range c.commands {
750 unmodified lines
modified:README.md+32 added
465 unmodified lines
466```go467RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")468```469470### Specify if you command takes 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`477478`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 checking482483`None` the command will be rejected if there are any left over arguments after parsing flags.484485`Arbitrary` any additional values left after parsing flags will be passed in to your `Run` function.486487`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:488489```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 }500```501502### Bind Flags with Config503504You can also bind your flags with [viper](https://github.com/spf13/viper):505```go
467 unmodified lines