Apache Commons CLI: prevent repeated options & force exactly one argument?

121 views Asked by At

I am using commons-cli 1.5.0. Let's say my command line syntax is the following:

Process -src <input> -dst <output>

My program ("Process") should accept exactly one -src and exactly one -dst. However, DefaultParser allows such command lines as:

Process -src aaa.txt -src bbb.txt -src ccc.txt -dst result.txt

For the above line, getOptionValue("src") returns "aaa.txt", but getOptionValues("src") returns all 3 filenames.

Now, is there an option to disallow such syntax? To define that there can only be one -src, and if there are more, DefaultParser.parse() should throw an exception? I've tried .hasArgs().numberOfArgs(1) and .hasArg().numberOfArgs(1), but it did not seem to change anything...

1

There are 1 answers

0
centic On BEST ANSWER

You probably need to do this check yourself and fail the app yourself after parsing, e.g.

CommandLine cmd = parser.parse(options, args);
if (cmd.getOptionValues("src").length > 1) {
    throw new IllegalStateException("Cannot handle more than one 'src' argument");
}