I have a fairly straightforward use case …
$ myapp config set key some-arbitrary-value
Making subcommands for config
and set
is no problem. But I would like key
to be constrained to a list of valid config fields, and I would like some-arbitrary-value
to be completely unconstrained.
Command.ValidArgs
apparently applies to all arguments collectively. So in my case, if I set ValidArgs
to my list of valid keys, it’ll fail on my arbitrary value.
The best I could come up with is the following approach:
- Create a function that takes an arg position (int) and list of valid values ([]string), and returns a custom
PositionalArgs
function that validates a single command-line arg against the list. I can use this for thekey
arg. - Create a similar function that acts like
ArbitraryArgs
but only for a single arg. I can use this for thevalue
arg. I think I can skip this step but it’d clearly express my intent, which might be helpful for code readers as well as help/usage text generation. - Call
cobra.MatchAll()
with one each of the above PositionalArgs, and assign the result to my command’sArgs
. This will compose the two positional validations into what I want.
This seems like a fair bit of fussy work for my simple use case. Plus since PositionalArgs
functions require a Command
object, I’m not sure how I’d easily test my code. I’m happy to consider alternatives to my proposed approach. Otherwise, I’ll forge ahead. Thanks!