Apache Commons CLI - ordering help options?

Viewed 6579

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

6 Answers

You can order the help values using the following code:

    HelpFormatter formatter = new HelpFormatter();
    // print the help options in the save order you added 
    formatter.setOptionComparator(new Comparator<Option>() {
        @Override
        public int compare(Option o1, Option o2) {
            List<Option> options = new ArrayList<Option>(getOptions().getOptions());
            Integer indexOfO1 = options.indexOf(o1);
            Integer indexOfO2 = options.indexOf(o2);
            return indexOfO1.compareTo(indexOfO2);
        }
    });
    formatter.printHelp("Commandline syntax", OPTIONS);
Related