I looked through the docs, but I can't figure out how to get the Apache CLI to handle a double hyphen option, which usually completes the parameter processing.
Consider the following command line with the -opt option, which can take an optional argument that is not specified:
MyProgram -opt -- param1 param2
I want the option to have no arguments in this case, but Apache returns a “-” as an argument. If an option allowed more than one argument, some or all parameters were returned as arguments.
Here is a sample code illustrating the problem:
package com.lifetouch.commons.cli;
import java.util.Arrays;
import org.apache.commons.cli.*;
public class DoubleHyphen {
private static Options options = new Options();
public static void main(String args[]) {
@SuppressWarnings("static-access")
OptionBuilder builder = OptionBuilder.isRequired(true).
withDescription("one optional arg").
withArgName("optArg").hasOptionalArgs(1);
options.addOption(builder.create("opt"));
doCliTest(new String[] { "-opt"} );
doCliTest(new String[] { "-opt", "optArg", "param"} );
doCliTest(new String[] { "-opt", "--", "param"} );
}
private static void doCliTest(String[] args) {
System.out.println("\nTEST CASE -- command line items: " + Arrays.toString(args));
CommandLine cmdline = null;
try {
CommandLineParser parser = new GnuParser();
cmdline = parser.parse(options, args);
} catch (ParseException ex) {
System.err.println("Command line parse error: " + ex);
return;
}
String optArgs[] = cmdline.getOptionValues("opt");
if (null == optArgs) {
System.out.println("No args specified for opt");
} else {
System.out.println(optArgs.length + " arg(s) for -opt option: " +
Arrays.toString(optArgs));
}
String tmp = Arrays.toString(cmdline.getArgList().toArray());
System.out.println(cmdline.getArgList().size() +
" command-line parameter(s): " + tmp);
}
}
source
share