Apache Commons CLI Handling of –help

An odd thing about Commons CLI is that it has no built-in concept of a “–help” option. Other libraries, like JCommander do (which had other problems, or I would not have bothered with Commons CLI). As a result, you have to build it on your own. It is not enough to include it with all the other application options, especially if you use required arguments. Then it is impossible to only set the Help option.

You must implement a two-step process. See this demo application on GitHub that I created for another blog post. It shows this in action.

First, only parse for the Help option, and if it is present, print the help text and exit the application. To print the complete help text, you must add the other parameters first, though. Otherwise there would be only “–help”.

final var applicationOptions = example_2_Options();

final var options = example_2_Help();
final var cli = parser.parse(options, args, true);

if (cli.hasOption(help)) {
    // Append the actual options for printing to the command-line.
    applicationOptions.getOptions().forEach(options::addOption);
    new HelpFormatter().printHelp("external-config-commons-cli", options);
    return;
}

Second, if no help is requested, parse for the application options.

final var cli = parser.parse(applicationOptions, args, true);

applicationOptions.getOptions().forEach(opt -> {
    if (cli.hasOption(opt)) {
        System.out.printf("Found option %s with value %s%n",
                opt.getOpt(), cli.getOptionValue(opt));
    }
});

Thank you very much for reading. I hope this was helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.