Edouard Batot
Edouard Batot

Reputation: 93

Apache Commons CLI Optional and positional argument

here's the deal : I want a flag "-pre" that if not filled will create a timestamp prefix ; and if filled, use the specified prefix.

Option prefixOption = OptionBuilder.create(O_PREFIX);
prefixOption.setLongOpt(O_PREFIX_LONG);
prefixOption.setArgName("prefix");
prefixOption.setDescription("Put a prefix (default is timestamp) to output directory.");
prefixOption.setType(String.class);
prefixOption.setOptionalArg(true);

And later..

System.out.println(commandLine.hasOption(O_PREFIX));
System.out.println(commandLine.getOptionValue(O_PREFIX));

Executions :

\> mon_execution -pre
true
null


\> mon_execution -pre Hahaha
true
null

and if I force the use of arg pre

prefixOption.setArgs(1); (in first snipet)

the command line take the next parameter as a parameter for -pre and breaks the parsing.

Any idea ?

Upvotes: 2

Views: 1338

Answers (1)

Edouard Batot
Edouard Batot

Reputation: 93

Change in option declaration

Option prefixOption = new Option("pre", "prefix", true, "Put a prefix (default is timestamp) to output directory.");
prefixOption.setOptionalArg(true);

AND, most important, respect the order and put the positional optional argument at the end of the list.

Question following, as food for thought : how to use more than one of these positional optional option ? An other question for an other post - an other day.

Thanks.

Upvotes: 2

Related Questions