cbeust/jcommander — pull request #116 by kurmasz (2012-05-22 17:29:02+00:00)
Title: Allow parameters to be abbreviated

This code allows users to enter the shortest unambiguous prefix of a parameter name. For example, given parameters --alpha --beta, and --barium, users need only type --a, --bet, and --bar on the command line.

Last November, we discussed implementing this as a "wrapper" to JCommander. However, that solution does not work well when commands are used. For example, JCommander allows the parameters for different commands to have different prefixes. It would be very difficult to implement the abbreviations as a wrapper and support similar behavior.

Instead, I made a few small changes right in JCommander. In particular I added an AbbreviationMap instance variable. This object maps abbreviated parameters to the appropriate ParameterDescription (if the abbreviation is unambiguous).

I then added this code at JCommander line 642 in parseValues:

ParameterDescription pd;
if (allowAbbreviations) {
pd = m_abbrevMap.get(a);
} else {
pd = m_descriptions.get(a);
}

I got AbbreviationMap from Paul Hosler's JOptSimple package. It uses the MIT license.

I added these two methods:

/**
* Parse and validate the command line parameters allowing abbreviated parameters.
*/
public void parseWithAbbreviations(String... args) {
parseWithAbbreviations(true, args);
}

/**
* Parse the command line parameters allowing abbreviated parameters.
*/
public void parseWithAbbreviations(boolean validate, String... args) {
parse(validate, true /* allow abbreviations */, args);
}

Perhaps instead of parse, parseWithoutValidation, and two versions of parseWithAbbreviations, we want to simply make this method public:

private void parse(boolean validate, boolean allowAbbreviations, String... args) {

Let me know what you think.