gogo-cobra

GO cobra: space separated values in StringArray flags


In GO's Cobra, lib for making CLIs, there are two input flags accepting multiple values being passed. One of the options is StringArray, when used as follows:

--flag=value1 --flag=value2

it yields an array ["value1", "value2"]. I am working on a drop-in replacement for a tool that expects somewhat more complex input:

--flag=valueA1 valueB1 --flag=valueA2 valueB2

the array it should yield would be ["valueA1 valueB1", "valueA2 valueB2"]

is there a way in cobra to parse the entire string until the next flag and include it in StringArray value like above?


Solution

  • There isn't a built-in way in cobra to do this, as there will be ambiguity. For example, in the case when there is also a sub-command named valueB1 or valueB2, it's not clear whether those should be executed as subcommands or interpreted as additional argument to --flag.

    The standard way to support an input like this is to expect the the input values are quoted, and cobra supports that. E.g.:

    --flag="valueA1 valueB1" --flag="valueA2 valueB2"