11

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?

2 Answers2

9

Apache Commons CLI 1.4:

You can get access to command-line arguments without an associated flag via:

org.apache.commons.cli.CommandLine#getArgList()

It returns a list of all NOT consumed/parsed arguments.

So you can get your defined options via:

  • org.apache.commons.cli.CommandLine#getOptionValue("option-name")
  • org.apache.commons.cli.CommandLine#hasOption("option-name")
  • (...)

or get a list of all unparsed / unrecognized options, via the above stated:

org.apache.commons.cli.CommandLine#getArgList()

sweisgerber.dev
  • 1,726
  • 17
  • 36
5

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.

Kirby
  • 704
  • 4
  • 7
  • Hmm alright. Thanks for that Kirby. Just quickly, is that String you posted the POSIX-standard way of defining options and the file? Just want to make it look as real as possible. –  Aug 13 '17 at 07:48
  • I am in no way a POSIX expert. But I do know that in the Unix world, it's customary in Unix usage messages to enclose optional items in square brackets and to represent mandatory items either with bare word or in angle brackets. I think the string I posted would withstand scrutiny by the Unix faithful. – Kirby Aug 13 '17 at 08:06
  • Alrighty, thankyou very much Kirby! I also took the liberty of adding in a `System.out.println(" FILE");` line after the print message to make it also appear inline with the options. Thanks for the answer! –  Aug 13 '17 at 08:24