user5549921
user5549921

Reputation:

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?

Upvotes: 12

Views: 8044

Answers (2)

sweisgerber.dev
sweisgerber.dev

Reputation: 1846

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()

Upvotes: 9

Kirby
Kirby

Reputation: 724

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.

Upvotes: 5

Related Questions