Apache Commons CLI 1.3.1: How to ignore unknown arguments?

I used to work with Apache Commons Cli 1.2. I wanted the analyzer to ignore the arguments if they are unknown (not added to the Options-Object).

Example (pseudo code):

Options specialOptions; specialOptions.addOption(null, "help", false, "shows help"); specialOptions.addOption(null, "version", false, "show version"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); //no third argument, since i dont want the program to stop parsing. // run program with args: --help --unknown --version // program shall parse --help AND --version, but ignore --unknown 

I used this solution by Pascal Schaefer: can the Apache Commons command line parameter analyzer ignore unknown command line parameters?

This worked well for me on 1.2, and it works great on 1.3.1 as well. But its not recommended. The parser that I used has been replaced with DefaultParser . I looked at the functionality, but there is no such processOptions method.

I really would like to use code that will not be removed in later releases. Anyone have any ideas how to solve this problem?

+11
source share
2 answers

This should work for your use case:

 Options options = new Options(); CommandLine commandLine = new DefaultParser().parse(options, args, true); 

The important part for you is stopAtNonOption: true :

A flag indicating how unrecognized tokens are processed. True to stop the analysis and add the remaining tokens to the argument list. false to throw an exception.

Docs at https://commons.apache.org/proper/commons-cli/javadocs/api-1.3.1/org/apache/commons/cli/DefaultParser.html#stopAtNonOption

0
source

Here you can use the same approach as in Pascal's solution.

 public class RelaxedParser extends DefaultParser { @Override public CommandLine parse(Options options, String[] arguments) throws ParseException { List<String> knownArguments = new ArrayList<>(); for (String arg : arguments) { if (options.hasOption(arg)) { knownArguments.add(arg); } } return super.parse(options, knownArguments.toArray(new String[knownArguments.size()])); } } 

Or, as an alternative, remove the unknown parameters from the arguments as above, and use DefaultParser.

0
source

All Articles