cbeust/jcommander — pull request #91 by rodionmoiseev (2011-11-26 15:02:36+00:00)
Title: Added support for option groups in usage output and some other fixes.

I'd be interested to know what you think of this feature: option groups. Of course, the idea comes from an actual demand for it from the piece of software I am working on.

The idea is to minimise and simplify usage output in cases when several commands share a common set of parameters, by extracting such set into its own usage section (=option group), and adding a pointer that option group from each command that uses it. Option group usage is then printed at the end of usage output.

Just to provide a simple example, say you have a package management system like `yum` or `apt-get` with two commands: `list` and `install`, to list and install remote packages to local machine. Both commands share a set of parameters for filtering packages by several criteria, such as: name, description, version, etc. So we end up with usage like:

Command: list
Usage: pkgmng list [options]
Options:
-n NAME filter by name
-v VER filter by version
-d DESC filter by description
-x some list specific option

Command: install
Usage: pkgmng install [options]
Options:
-n NAME filter by name
-v VER filter by version
-d DESC filter by description
-y some install specific option

With option groups feature this can be *refactored* into simply:

Usage: pkgmng list [options] [filter options]
Options:
-x some list specific option

Command: install
Usage: pkgmng install [options] [filter options]
Options:
-y some install specific option

Filter Options:
-n NAME filter by name
-v VER filter by version
-d DESC filter by description

To create such output the user simply declares which parameter set he/she wishes to be printed separately by declaring an option group name:

@Parameters(optionGroupName = "Filter Options")
public class FilterOptions{
//-n, -v, -d options declared here
}

public class InstallCommand{
@ParametersDelegate
public FilterOptions filterOptions = new FilterOptions();
}

//...

and then uses inheritance or parameter delegates to reference it as usual. Option groups also take a description parameter similar to commands.

I've added couple of scenario tests which should give you a good idea of the usage. However, the tests are fairly brittle and will probably break every time output formatting is modified.

Note: commit also includes couple of fixes (see CHANGELOG). If you don't accept this request I'll make a new patch for them.

Looking forward to your feedback.

Regards