Rory Rory - 1 month ago 11
Java Question

Apache Commons CLI - ordering help options?

I'm using the Apache Commons CLI. By default it orders help options on the command line alphabetically by key. So, what appears is:

-csv
-ip
-msisdn
-xml


But I want to order them as follows:

-csv
-xml
-ip
-msisdn


I know that there is a OptionFormatter class you can use and pass to the HelpFormatter, but can't see any examples on how to use it for my purposes above (http://www.marko.homeunix.org/programming/java/commons-cli/api/org/apache/commons/cli/HelpFormatter.OptionComparator.html).

Just wondering has anyone done anything similar?

Thanks

Answer

Currently it is not supported. But it is an open source so, you know what to do...

From the source code:

    private static class OptionComparator
    implements Comparator {

    /**
     * <p>Compares its two arguments for order. Returns a negative 
     * integer, zero, or a positive integer as the first argument 
     * is less than, equal to, or greater than the second.</p>
     *
     * @param o1 The first Option to be compared.
     * @param o2 The second Option to be compared.
     *
     * @return a negative integer, zero, or a positive integer as 
     * the first argument is less than, equal to, or greater than the 
     * second.
     */
    public int compare(Object o1, Object o2)
    {
        Option opt1 = (Option)o1;
        Option opt2 = (Option)o2;

        return opt1.getKey().compareToIgnoreCase(opt2.getKey());
    }
}

You can override the default comparator and define the order you want.

Comments