Skip to content
Myr

Deprecate ExactValidArgs() and test combinations of args validators (#1643)

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

* deprecate ExactValidArgs in favour of MatchAll(OnlyValidArgs, ...) * test combinations of args validators * adjust docs

authored by Unai Martinez-Corral · committed by GitHub · parent 2e8ba6f · Browse files · 3 files+270 added−52 removed
This commit

State

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

Diff stats

3 files+270 added−52 removed

  • other:+270 added−52 removed

3 files+270 added−52 removed

modified:args_test.go+226 added-22 removed
25 unmodified lines
26 t.Fatalf("Unexpected error: %v", err)27 }28}2930func validWithInvalidArgs(err error, t *testing.T) {30func validOnlyWithInvalidArgs(err error, t *testing.T) {31 if err == nil {32 t.Fatal("Expected an error")33 }34 got := err.Error()
2 unmodified lines
37 t.Errorf("Expected: %q, got: %q", expected, got)38 }39}4041func noArgsWithArgs(err error, t *testing.T) {41func noArgsWithArgs(err error, t *testing.T, arg string) {42 if err == nil {43 t.Fatal("Expected an error")44 }45 got := err.Error()46 expected := `unknown command "illegal" for "c"`46 expected := `unknown command "` + arg + `" for "c"`47 if got != expected {48 t.Errorf("Expected: %q, got: %q", expected, got)49 }50}
41 unmodified lines
92 t.Fatalf("Expected %q, got %q", expected, got)93 }94}9596// NoArgs9798func TestNoArgs(t *testing.T) {99 c := getCommand(NoArgs, false)100 output, err := executeCommand(c)101 expectSuccess(output, err, t)102}103102func TestNoArgsWithArgs(t *testing.T) {104func TestNoArgs_WithArgs(t *testing.T) {105 c := getCommand(NoArgs, false)104 _, err := executeCommand(c, "illegal")105 noArgsWithArgs(err, t)106 _, err := executeCommand(c, "one")107 noArgsWithArgs(err, t, "one")108}109110func TestNoArgs_WithValid_WithArgs(t *testing.T) {111 c := getCommand(NoArgs, true)112 _, err := executeCommand(c, "one")113 noArgsWithArgs(err, t, "one")114}115116func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {117 c := getCommand(NoArgs, true)118 _, err := executeCommand(c, "a")119 noArgsWithArgs(err, t, "a")120}121122func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {123 c := getCommand(MatchAll(OnlyValidArgs, NoArgs), true)124 _, err := executeCommand(c, "a")125 validOnlyWithInvalidArgs(err, t)126}127128// OnlyValidArgs129130func TestOnlyValidArgs(t *testing.T) {131 c := getCommand(OnlyValidArgs, true)132 output, err := executeCommand(c, "one", "two")133 expectSuccess(output, err, t)134}135114func TestOnlyValidArgsWithInvalidArgs(t *testing.T) {136func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {137 c := getCommand(OnlyValidArgs, true)138 _, err := executeCommand(c, "a")117 validWithInvalidArgs(err, t)139 validOnlyWithInvalidArgs(err, t)140}141142// ArbitraryArgs143144func TestArbitraryArgs(t *testing.T) {145 c := getCommand(ArbitraryArgs, false)146 output, err := executeCommand(c, "a", "b")147 expectSuccess(output, err, t)148}149150func TestArbitraryArgs_WithValid(t *testing.T) {151 c := getCommand(ArbitraryArgs, true)152 output, err := executeCommand(c, "one", "two")153 expectSuccess(output, err, t)154}155156func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {157 c := getCommand(ArbitraryArgs, true)158 output, err := executeCommand(c, "a")159 expectSuccess(output, err, t)160}161162func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {163 c := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true)164 _, err := executeCommand(c, "a")165 validOnlyWithInvalidArgs(err, t)166}167168// MinimumNArgs169170func TestMinimumNArgs(t *testing.T) {171 c := getCommand(MinimumNArgs(2), false)172 output, err := executeCommand(c, "a", "b", "c")173 expectSuccess(output, err, t)174}175132func TestMinimumNArgsWithLessArgs(t *testing.T) {176func TestMinimumNArgs_WithValid(t *testing.T) {177 c := getCommand(MinimumNArgs(2), true)178 output, err := executeCommand(c, "one", "three")179 expectSuccess(output, err, t)180}181182func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {183 c := getCommand(MinimumNArgs(2), true)184 output, err := executeCommand(c, "a", "b")185 expectSuccess(output, err, t)186}187188func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {189 c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)190 _, err := executeCommand(c, "a", "b")191 validOnlyWithInvalidArgs(err, t)192}193194func TestMinimumNArgs_WithLessArgs(t *testing.T) {195 c := getCommand(MinimumNArgs(2), false)196 _, err := executeCommand(c, "a")197 minimumNArgsWithLessArgs(err, t)198}199200func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {201 c := getCommand(MinimumNArgs(2), true)202 _, err := executeCommand(c, "one")203 minimumNArgsWithLessArgs(err, t)204}205206func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) {207 c := getCommand(MinimumNArgs(2), true)208 _, err := executeCommand(c, "a")209 minimumNArgsWithLessArgs(err, t)210}211212func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {213 c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)214 _, err := executeCommand(c, "a")215 validOnlyWithInvalidArgs(err, t)216}217218// MaximumNArgs219220func TestMaximumNArgs(t *testing.T) {221 c := getCommand(MaximumNArgs(3), false)222 output, err := executeCommand(c, "a", "b")223 expectSuccess(output, err, t)224}225144func TestMaximumNArgsWithMoreArgs(t *testing.T) {226func TestMaximumNArgs_WithValid(t *testing.T) {227 c := getCommand(MaximumNArgs(2), true)228 output, err := executeCommand(c, "one", "three")229 expectSuccess(output, err, t)230}231232func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {233 c := getCommand(MaximumNArgs(2), true)234 output, err := executeCommand(c, "a", "b")235 expectSuccess(output, err, t)236}237238func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {239 c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)240 _, err := executeCommand(c, "a", "b")241 validOnlyWithInvalidArgs(err, t)242}243244func TestMaximumNArgs_WithMoreArgs(t *testing.T) {245 c := getCommand(MaximumNArgs(2), false)246 _, err := executeCommand(c, "a", "b", "c")247 maximumNArgsWithMoreArgs(err, t)248}249250func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {251 c := getCommand(MaximumNArgs(2), true)252 _, err := executeCommand(c, "one", "three", "two")253 maximumNArgsWithMoreArgs(err, t)254}255256func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) {257 c := getCommand(MaximumNArgs(2), true)258 _, err := executeCommand(c, "a", "b", "c")259 maximumNArgsWithMoreArgs(err, t)260}261262func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {263 c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)264 _, err := executeCommand(c, "a", "b", "c")265 validOnlyWithInvalidArgs(err, t)266}267268// ExactArgs269270func TestExactArgs(t *testing.T) {271 c := getCommand(ExactArgs(3), false)272 output, err := executeCommand(c, "a", "b", "c")273 expectSuccess(output, err, t)274}275156func TestExactArgsWithInvalidCount(t *testing.T) {276func TestExactArgs_WithValid(t *testing.T) {277 c := getCommand(ExactArgs(3), true)278 output, err := executeCommand(c, "three", "one", "two")279 expectSuccess(output, err, t)280}281282func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {283 c := getCommand(ExactArgs(3), true)284 output, err := executeCommand(c, "three", "a", "two")285 expectSuccess(output, err, t)286}287288func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {289 c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true)290 _, err := executeCommand(c, "three", "a", "two")291 validOnlyWithInvalidArgs(err, t)292}293294func TestExactArgs_WithInvalidCount(t *testing.T) {295 c := getCommand(ExactArgs(2), false)296 _, err := executeCommand(c, "a", "b", "c")297 exactArgsWithInvalidCount(err, t)298}299162func TestExactValidArgs(t *testing.T) {163 c := getCommand(ExactValidArgs(3), true)164 output, err := executeCommand(c, "three", "one", "two")165 expectSuccess(output, err, t)300func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {301 c := getCommand(ExactArgs(2), true)302 _, err := executeCommand(c, "three", "one", "two")303 exactArgsWithInvalidCount(err, t)304}305168func TestExactValidArgsWithInvalidCount(t *testing.T) {169 c := getCommand(ExactValidArgs(2), false)170 _, err := executeCommand(c, "three", "one", "two")306func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {307 c := getCommand(ExactArgs(2), true)308 _, err := executeCommand(c, "three", "a", "two")309 exactArgsWithInvalidCount(err, t)310}311174func TestExactValidArgsWithInvalidArgs(t *testing.T) {175 c := getCommand(ExactValidArgs(3), true)312func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {313 c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true)314 _, err := executeCommand(c, "three", "a", "two")177 validWithInvalidArgs(err, t)315 validOnlyWithInvalidArgs(err, t)316}317318// RangeArgs319320func TestRangeArgs(t *testing.T) {321 c := getCommand(RangeArgs(2, 4), false)322 output, err := executeCommand(c, "a", "b", "c")323 expectSuccess(output, err, t)324}325186func TestRangeArgsWithInvalidCount(t *testing.T) {326func TestRangeArgs_WithValid(t *testing.T) {327 c := getCommand(RangeArgs(2, 4), true)328 output, err := executeCommand(c, "three", "one", "two")329 expectSuccess(output, err, t)330}331332func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {333 c := getCommand(RangeArgs(2, 4), true)334 output, err := executeCommand(c, "three", "a", "two")335 expectSuccess(output, err, t)336}337338func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {339 c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)340 _, err := executeCommand(c, "three", "a", "two")341 validOnlyWithInvalidArgs(err, t)342}343344func TestRangeArgs_WithInvalidCount(t *testing.T) {345 c := getCommand(RangeArgs(2, 4), false)346 _, err := executeCommand(c, "a")347 rangeArgsWithInvalidCount(err, t)348}349350func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {351 c := getCommand(RangeArgs(2, 4), true)352 _, err := executeCommand(c, "two")353 rangeArgsWithInvalidCount(err, t)354}355356func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {357 c := getCommand(RangeArgs(2, 4), true)358 _, err := executeCommand(c, "a")359 rangeArgsWithInvalidCount(err, t)360}361362func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {363 c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)364 _, err := executeCommand(c, "a")365 validOnlyWithInvalidArgs(err, t)366}367368// Takes(No)Args369370func TestRootTakesNoArgs(t *testing.T) {371 rootCmd := &Command{Use: "root", Run: emptyRun}372 childCmd := &Command{Use: "child", Run: emptyRun}373 rootCmd.AddCommand(childCmd)
96 unmodified lines
470 })471 }472}473474// DEPRECATED475476func TestExactValidArgs(t *testing.T) {477 c := getCommand(ExactValidArgs(3), true)478 output, err := executeCommand(c, "three", "one", "two")479 expectSuccess(output, err, t)480}481482func TestExactValidArgs_WithInvalidCount(t *testing.T) {483 c := getCommand(ExactValidArgs(2), false)484 _, err := executeCommand(c, "three", "one", "two")485 exactArgsWithInvalidCount(err, t)486}487488func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {489 c := getCommand(ExactValidArgs(2), true)490 _, err := executeCommand(c, "three", "a", "two")491 exactArgsWithInvalidCount(err, t)492}493494func TestExactValidArgs_WithInvalidArgs(t *testing.T) {495 c := getCommand(ExactValidArgs(2), true)496 _, err := executeCommand(c, "three", "a")497 validOnlyWithInvalidArgs(err, t)498}499500// This test make sure we keep backwards-compatibility with respect501// to the legacyArgs() function.502// It makes sure the root command accepts arguments if it does not have503// sub-commands.
24 unmodified lines
modified:args.go+10 added-14 removed
30 unmodified lines
31 }32 return nil33}3435// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.35// OnlyValidArgs returns an error if there are any positional args that are not in36// the `ValidArgs` field of `Command`37func OnlyValidArgs(cmd *Command, args []string) error {38 if len(cmd.ValidArgs) > 0 {39 // Remove any description that may be included in ValidArgs.40 // A description is following a tab character.41 var validArgs []string42 for _, v := range cmd.ValidArgs {43 validArgs = append(validArgs, strings.Split(v, "\t")[0])44 }4445 for _, v := range args {46 if !stringInSlice(v, validArgs) {47 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))48 }
36 unmodified lines
85 return nil86 }87}8889// ExactValidArgs returns an error if90// there are not exactly N positional args OR91// there are any positional args that are not in the `ValidArgs` field of `Command`92func ExactValidArgs(n int) PositionalArgs {93 return func(cmd *Command, args []string) error {94 if err := ExactArgs(n)(cmd, args); err != nil {95 return err96 }97 return OnlyValidArgs(cmd, args)98 }99}10089// RangeArgs returns an error if the number of args is not within the expected range.90func RangeArgs(min int, max int) PositionalArgs {91 return func(cmd *Command, args []string) error {92 if len(args) < min || len(args) > max {
13 unmodified lines
106 }107 return nil108 }109}110111// ExactValidArgs returns an error if there are not exactly N positional args OR112// there are any positional args that are not in the `ValidArgs` field of `Command`113//114// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead115func ExactValidArgs(n int) PositionalArgs {116 return MatchAll(ExactArgs(n), OnlyValidArgs)117}
modified:user_guide.md+34 added-16 removed
300 unmodified lines
301```302303### Flag Groups304305If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then 305If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then306Cobra can enforce that requirement:307```go308rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")309rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")310rootCmd.MarkFlagsRequiredTogether("username", "password")311``` 311```312313You can also prevent different flags from being provided together if they represent mutually 313You can also prevent different flags from being provided together if they represent mutually314exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:315```go316rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")317rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
8 unmodified lines
326327## Positional and Custom Arguments328329Validation of positional arguments can be specified using the `Args` field of `Command`.330The following validators are built in:331332- Number of arguments:333 - `NoArgs` - report an error if there are any positional args.334 - `ArbitraryArgs` - accept any number of args.335 - `MinimumNArgs(int)` - report an error if less than N positional args are provided.336 - `MaximumNArgs(int)` - report an error if more than N positional args are provided.337 - `ExactArgs(int)` - report an error if there are not exactly N positional args.338 - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.339- Content of the arguments:340 - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.341342If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.343332The following validators are built in:344Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.345For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional346args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as347shown below:348334- `NoArgs` - the command will report an error if there are any positional args.335- `ArbitraryArgs` - the command will accept any args.336- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.337- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.338- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.339- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.340- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`341- `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.342- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities).349```go350var cmd = &cobra.Command{351 Short: "hello",352 Args: MatchAll(ExactArgs(2), OnlyValidArgs),353 Run: func(cmd *cobra.Command, args []string) {354 fmt.Println("Hello, World!")355 },356}357```358344An example of setting the custom validator:359It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.360For example:361362```go363var cmd = &cobra.Command{364 Short: "hello",365 Args: func(cmd *cobra.Command, args []string) error {350 if len(args) < 1 {351 return errors.New("requires a color argument")366 // Optionally run one of the validators provided by cobra367 if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {368 return err369 }370 // Run the custom validation logic371 if myapp.IsValidColor(args[0]) {372 return nil373 }374 return fmt.Errorf("invalid color specified: %s", args[0])
310 unmodified lines