Friday 16 December 2016

Commons-CLI: Set the display name for the argument

This is continuation to my previous post, As you see the output of previous post application, it is like below.

usage: ls [-A] [-b <arg>] [-c]
     -A,--almost-all           do not list implied . and ..
     -b,--block-size <arg>     use SIZE-byte blocks
     -c                        with -lt: sort by, and show, ctime (time of last modification of file
                               status information) with -l:show ctime and sort by name otherwise:
                               sort by ctime

Observe above ouput, by default Commons-CLI library giving the argument name as ‘arg’, actually argument name should be ‘SIZE’ like below.

-b,--block-size <SIZE>     use SIZE-byte blocks

By using 'setArgName' methodof Option class, we can set the argument name.

Example
Option option3 = new Option("b", "block-size", true, "use SIZE-byte blocks");
option3.setArgName("SIZE");

Following is the complete working application.

OptionDemo.java

import java.io.OutputStream;
import java.io.PrintWriter;

import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

public class OptionDemo {

 public static void printHelp(final Options options, final int width, final String cmdLineSyntax,
   final String header, final String footer, final int leftPad, final int descPad, final boolean autoUsage,
   final OutputStream out) {
  PrintWriter writer = new PrintWriter(out);
  final HelpFormatter helpFormatter = new HelpFormatter();
  helpFormatter.printHelp(writer, width, cmdLineSyntax, header, options, leftPad, descPad, footer, autoUsage);
  writer.flush();
 }

 public static void main(String args[]) {

  Option option1 = new Option("A", "almost-all", false, "do not list implied . and ..");
  Option option2 = new Option("c", "with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime");
  Option option3 = new Option("b", "block-size", true, "use SIZE-byte blocks");
  
  option3.setArgName("SIZE");

  Options options = new Options();
  options.addOption(option1).addOption(option2).addOption(option3);

  printHelp(options, 100, "ls", "", "", 5, 5, true, System.out);

 }
}

Output

usage: ls [-A] [-b <SIZE>] [-c]
     -A,--almost-all            do not list implied . and ..
     -b,--block-size <SIZE>     use SIZE-byte blocks
     -c                         with -lt: sort by, and show, ctime (time of last modification of
                                file status information) with -l:show ctime and sort by name
                                otherwise: sort by ctime




Previous                                                 Next                                                 Home

No comments:

Post a Comment