Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Apache CLI to handle double-dash?

I've looked at the docs but can't see how to get the Apache Commons CLI to handle the double-hyphen "option" that normally terminates option processing.

Consider the following command-line which has an "-opt" option which can take an optional argument that is not specified:

MyProgram -opt -- param1 param2

I want the option to end up with no arguments in this case, but Apache returns "--" as an argument. If the option allowed for more than one argument, then some or all of the parameters would get returned as arguments.

Here is sample code illustrating the issue:

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[]) {
    // One required option with an optional argument:
    @SuppressWarnings("static-access")
    OptionBuilder builder = OptionBuilder.isRequired(true).
            withDescription("one optional arg").
            withArgName("optArg").hasOptionalArgs(1);
    options.addOption(builder.create("opt"));

    // Illustrate the issue:
    doCliTest(new String[] { "-opt"} );
    doCliTest(new String[] { "-opt", "optArg", "param"} );
    doCliTest(new String[] { "-opt", "--", "param"} );
    // What I want is for the double-dash to terminate option processing.
    // Note that if "opt" used hasOptionalArgs(2) then "param" would be a second
    // argument to that option (rather than an application parameter).
  }

  private static void doCliTest(String[] args) {
    System.out.println("\nTEST CASE -- command line items: " + Arrays.toString(args));

    // Parse the command line:
    CommandLine cmdline = null;
    try {
        CommandLineParser parser = new GnuParser();
        cmdline = parser.parse(options, args); // using stopAtNonOption does not help
    } catch (ParseException ex) {
        System.err.println("Command line parse error: " + ex);
        return;
    }

    // Observe the results for the option and argument:
    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));
    }

    // Observe the results for the command-line parameters:
    String tmp = Arrays.toString(cmdline.getArgList().toArray());
    System.out.println(cmdline.getArgList().size() +
            " command-line parameter(s): " + tmp);
  }
}
like image 754
MykennaC Avatar asked Jan 16 '12 17:01

MykennaC


1 Answers

In order to handle the special token -- as an option terminator, you must use the POSIX parser.

Use

CommandLineParser parser = new PosixParser();

instead of

CommandLineParser parser = new GnuParser();
like image 55
Unai Vivi Avatar answered Nov 19 '22 14:11

Unai Vivi