Search code examples
javacommand-linecommand-line-argumentsapache-commons-cli

Synonyms when parsing command line using commons-cli


I'm trying out apache commons-cli to parse the command line arguments that were passed to the java command line utility.

Is there a way for both '-r' and '-R' to mean "Recurse subdirectories" without adding 2 options to the parser (which would mess up the usage printout).

some code:

Options options = new Options();
options.addOption("r", "recurse", false,"recurse subdirectories");
CommandLineParser parser = new BasicParser();
CommandLine cmd = null;

try {
    cmd = parser.parse( options, args);

} catch (ParseException e) {
    e.printStackTrace();
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("readfiles", options);
}

Solution

  • This option does not exist at the moment as part of the commons-cli.
    For now this will have to do:

    public static void main( String[] args )
    {
        Options options = new Options();
        options.addOption("v", "version", false, "Run with verbosity set to high")
               .addOption("h", "help", false, "Print usage")
               .addOption("r", "recurse", false, "Recurse subdirectories")
               .addOption("R", false, "Same as --recurse");
    
        CommandLine cmd = null;
        CommandLineParser parser = new PosixParser();
        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("cmdline-parser [OPTIONS] [FILES]", options);
    
    }
    

    The resulting usage info being:

    usage: cmdline-parser [OPTIONS] [FILES]
     -h,--help      Print usage
     -r,--recurse   Recurse subdirectories
     -R             Same as --recurse
     -v,--version   Run with verbosity set to high