Naftuli Kay
Naftuli Kay

Reputation: 91610

Creating subcommands with commons-cli

I'm trying to create a simple argument parser using commons-cli and I can't seem to figure out how to create the following options:

java ... com.my.path.to.MyClass producer 
java ... com.my.path.to.MyClass consumer -j 8

The first argument to my program should be either producer or consumer, defining the mode which my program will run in. If it's in consumer mode, I'd like to have a -j argument which defines how many threads to service with.

Here's what I've got so far:

Options options = new Options();
options.addOption("mode", false, "Things.");

HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("startup.sh", options);

When I print out these options, the mode parameter shows up as -mode.

In Python's argparse, I'd just do the following:

parser = argparse.ArgumentParser()
parser.add_argument('mode', choices=('producer', 'consumer'), required=True)
parser.print_help()

This does exactly what I'm looking for. How can I do this in commons-cli?

Upvotes: 3

Views: 4078

Answers (3)

Alessandro Scarlatti
Alessandro Scarlatti

Reputation: 734

picocli is now included in Groovy 2.5.x. It has built-in support for subcommands.

Upvotes: 2

Naftuli Kay
Naftuli Kay

Reputation: 91610

JCommander is the answer. commons-cli doesn't seem to support these options.

Upvotes: 3

Joe Casadonte
Joe Casadonte

Reputation: 16859

What I've done for things like this is to have separate Options for each class. In your main, check the first argument to decide which list to pass to the parser. FWIW, I don't consider it "hack" solution.

Upvotes: 4

Related Questions