javaapache-commons-cli

Required argument without option name in Commons CLI


I'm trying to parse the command line arguments in Java to the following usage:

Usage: gibl FILE
 -h,  --help      Displays this help message.
 -v,  --version   Displays the program version.
 FILE             Source file.

With the Apache Commons CLI library, I know I can use Option's to parse the -h and -v commands optionally, and then use CommandLine.getArgs() to get the leftover argument FILE and then parse it as I like, but I actually want to specify it as an Option within CLI.

Currently, I do the following:

if (cmd.getArgs().length < 1) {
    System.out.println("Missing argument: FILE");
    help(1); // Prints the help file and closes the program with an exit code of 1.
}
String file = cmd.getArgs()[0];

But then when I call HelpFormatter.printHelp(String, Options) my extra argument does not get included in the automatically generated help text.

What I'm after, is something like this:

Option file = new Option("Source file.");
file.setRequired(true);
options.addOption(file);

Where I have an argument, but no corresponding option identifier attached to it, and can then therefore pass it to the HelpFormatter. Any ideas?


Solution

  • To the best of my knowledge, Commons CLI does not support defining an option without an associated flag. I think you will need to do something along these lines:

    new HelpFormatter().printHelp("commandName [OPTIONS] <FILE>", Options);
    

    In case you didn't see it, this question is pretty similar, and my answer is very similar to the answer there.