1 package org.openflow.example.cli;
3 import java.io.PrintStream;
6 * Very basic command line interface
8 * (really should be something in java.* for this; only implementing this to
9 * remove external dependencies)
11 * Modeled after org.apache.common.cli .
13 * @author Rob Sherwood (rob.sherwood@stanford.edu)
17 public class SimpleCLI {
19 private static final String NAME_WIDTH = "-15";
20 private static final String VALUE_WIDTH = "-20";
21 private static final String FORMAT_STRING = "%1$" + NAME_WIDTH + "s%2$"
22 + VALUE_WIDTH + "s%3$s\n";
28 * Need to use SimpleCLI.parse() instead
33 private SimpleCLI(Options options) {
34 this.options = options;
38 * @return the index of the last parsed option
40 * Useful for finding options that don't start with "-" or "--"
42 public int getOptind() {
50 public void setOptind(int optind) {
54 public boolean hasOption(String shortName) {
55 Option option = this.options.getOption(shortName);
58 return option.specified;
61 public String getOptionValue(String shortName) {
62 Option option = this.options.getOption(shortName);
65 if (!option.specified)
66 return option.defaultVal.toString();
71 public static SimpleCLI parse(Options options, String[] args)
72 throws ParseException {
73 SimpleCLI simpleCLI = new SimpleCLI(options);
75 for (i = 0; i < args.length; i++) {
76 if (!args[i].startsWith("-"))
77 break; // not a short or long option
78 String optName = args[i].replaceFirst("^-*", ""); // remove leading
81 if (args[i].startsWith("--"))
82 option = options.getOptionByLongName(optName);
84 option = options.getOption(optName);
86 throw new ParseException("unknown option: " + optName);
87 option.specified = true;
88 if (option.needsArg()) {
89 if ((i + 1) >= args.length)
90 throw new ParseException("option " + optName
91 + " requires an argument:: " + option.comment);
92 option.val = args[i + 1];
93 i++; // skip next element; we've parsed it
96 simpleCLI.setOptind(i);
100 public static void printHelp(String canonicalName, Options options) {
101 printHelp(canonicalName, options, System.err);
104 private static void printHelp(String helpString, Options options,
106 err.println(helpString);
107 err.format(FORMAT_STRING, "\toption", "type [default]", "usage");
108 for (Option option : options.getOptions()) {
110 if (option.shortOpt != null)
111 msg += "-" + option.shortOpt;
112 if (option.longOpt != null) {
113 if (!msg.equals("\t"))
115 msg += "--" + option.longOpt;
118 if (option.defaultVal != null)
119 val += option.defaultVal.getClass().getSimpleName() + " ["
120 + option.defaultVal.toString() + "]";
122 if (option.comment != null)
123 comment = option.comment;
127 err.format(FORMAT_STRING, msg, val, comment);
129 err.println(""); // print blank line at the end, to look pretty