1 package org.openflow.codec.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$" + VALUE_WIDTH + "s%3$s\n";
27 * Need to use SimpleCLI.parse() instead
32 private SimpleCLI(Options options) {
33 this.options = options;
37 * @return the index of the last parsed option
39 * Useful for finding options that don't start with "-" or "--"
41 public int getOptind() {
49 public void setOptind(int optind) {
53 public boolean hasOption(String shortName) {
54 Option option = this.options.getOption(shortName);
57 return option.specified;
60 public String getOptionValue(String shortName) {
61 Option option = this.options.getOption(shortName);
64 if (!option.specified)
65 return option.defaultVal.toString();
70 public static SimpleCLI parse(Options options, String[] args) throws ParseException {
71 SimpleCLI simpleCLI = new SimpleCLI(options);
73 for (i = 0; i < args.length; i++) {
74 if (!args[i].startsWith("-"))
75 break; // not a short or long option
76 String optName = args[i].replaceFirst("^-*", ""); // remove leading
79 if (args[i].startsWith("--"))
80 option = options.getOptionByLongName(optName);
82 option = options.getOption(optName);
84 throw new ParseException("unknown option: " + optName);
85 option.specified = true;
86 if (option.needsArg()) {
87 if ((i + 1) >= args.length)
88 throw new ParseException("option " + optName + " requires an argument:: " + option.comment);
89 option.val = args[i + 1];
90 i++; // skip next element; we've parsed it
93 simpleCLI.setOptind(i);
97 public static void printHelp(String canonicalName, Options options) {
98 printHelp(canonicalName, options, System.err);
101 private static void printHelp(String helpString, Options options, PrintStream err) {
102 err.println(helpString);
103 err.format(FORMAT_STRING, "\toption", "type [default]", "usage");
104 for (Option option : options.getOptions()) {
106 if (option.shortOpt != null)
107 msg += "-" + option.shortOpt;
108 if (option.longOpt != null) {
109 if (!msg.equals("\t"))
111 msg += "--" + option.longOpt;
114 if (option.defaultVal != null)
115 val += option.defaultVal.getClass().getSimpleName() + " [" + option.defaultVal.toString() + "]";
117 if (option.comment != null)
118 comment = option.comment;
122 err.format(FORMAT_STRING, msg, val, comment);
124 err.println(""); // print blank line at the end, to look pretty