I am currently trying to come up with a way to build a command-line option that when provided can either take one required argument or a second optional argument (in addition to the required one). I am trying to achieve this using apache commons cli.
i.e. myProgram -a [integer]
myProgram -a "test" --> isValid
myProgram -a "test" 2 --> also isValid
I have tried:
Option.builder("a").hasArg().numberOfArgs(2).optionalArg(true).build();
&
Option.builder("a").hasArg().numberOfArgs(2).build();
Neither of which is working as desired. The first example makes both arguments optional and it allows for passing empty arguments which is against the requirements.
The second example makes both parameters required and fails when only the string type arg is provided.
I have looked at the documentation for commons cli but the usage cases they provided didnt touch complex cases like this one, and similarly did not get much details from the api docs.
I expect the program to fail when -a is provided with no value, but to succeed when provided with 1 or 2 arguments as shown previously.
According to my understanding of the documentation for appache-commons-cli (and I might be wrong), there doesn't seem to be a way to set "optionalArg" on a per-argument basis.
Also the way I see it used in the examples, it seems to take in arguments with separators in between, as in
-D<property>=<value>instead of spaces? I'm unsure about this though.But yeah, for what you want, you could do it dirty and allow optional arguments, then reject it when the option doesn't have the required argument (defeating the purpose of using commons-cli I know).
EDIT: Did you try using PatternOptionBuilder ? This example intrigues me:
It says the exclamation mark can be used before mandatory options, but I'm not sure if it can be used with mandatory arguments? I didn't try it though.