ucb.util
Class CommandArgs

java.lang.Object
  extended by java.util.AbstractMap<String,List<String>>
      extended by ucb.util.CommandArgs
All Implemented Interfaces:
Map<String,List<String>>

public class CommandArgs
extends AbstractMap<String,List<String>>
implements Map<String,List<String>>

A CommandArgs object is a mapping from option keys to values that interprets the command-line options to a main program. It expects such arguments to conform to Sun's standard guidelines, according to which, a command (issued to a shell) has the following general form:

     COMMAND [ OPTION ... ] [ -- ] [ OTHER_ARGUMENT ... ]
  
([]'s indicate optional parts; ... indicates one or more). Each OPTION has one of the following forms (x, y, etc. denote non-blank characters):
  Single parameterless short option:
     -x 

  Several parameterless short options:
     -xyz...

  Single short option with parameter:
     -x OPTARG        
     or
     -xOPTARG
 
  Long parameterless option:
     --opt

  Long option with parameter:
     --opt=foo
  
If a short option takes an additional argument, that argument is always required to follow; it cannot be omitted. When a long argument takes an argument, it is optional.

The '--' before the first OTHER_ARGUMENT is optional unless that OTHER_ARGUMENT starts with '-'.

One creates a CommandArgs object by supplying a String describing the legal options, and an array of command-line argument strings (as sent to the main function).

The CommandArgs object then parses the command-line arguments according to the specification, and presents the options and other arguments by as a standard Java Map>. That is, it maps Strings that indicate option keys (like "--opt" or "-x") to a list of argument values supplied for that option in the command-line arguments (it is a list because in general, an option can appear several times). Options that take no arguments get the argument value "". Trailing arguments correspond to the option key "--". The CommandArgs class extends the normal Map methods with a few convenience methods to assist common use.

Any short option is considered equivalent to a one-character long option, and vice-versa.

For example, suppose that we have a program whose usage is

     foo [ -c ] [ -h ] [ -o FILE ] ARG1
  
where []'s indicate optional arguments, and there may be at most one -o argument. It's main program would begin
    import ucb.util.CommandArgs;
    class foo {
      public static void main (String[] args0) {
         boolean cOptionSpecified;
         boolean hOptionSpecified;
         String oOptionValue;
         List arg1;
         CommandArgs args = 
            new CommandArgs ("-c -h -o={0,1} --={1}", args0);
         if (! args.ok ())
            ERROR ();
         cOptionSpecified = args.containsKey ("-c");
         hOptionSpecified = args.containsKey ("-h");
         oOptionValue = args.getLast ("-o"); // null if absent.
         arg1 = args.get ("--").get (0);
         ...
   

For a program whose usage is

      bar [ -c ] [ -k COUNT ] [ --dry-run ] [ --form=NAME ] [ ARG ... ]
   
where there may be at most one -k option (which must be an integer), any number of --form options, and zero or more trailing arguments, we could write:
    import ucb.util.CommandArgs;
    class foo {
      public static void main (String[] args0) {
         ...
         String options = "-c -k=(\\d+){0,1} --dry-run --form="
                          + "--={0,}";
;
         CommandArgs args = new CommandArgs (options, args0);
         ...
         
         int count;
         if (args.containsKey ("-k"))
            count = args.getInt ("-k");
         List forms = args.get ("--form");
         List otherArgs = args.get ("--");
    

Here is an example in which there must be exactly one occurrence of either the option -i, -q, or -l, an optional occurrence of either of the mutually-exclusive options -n or -N, up to 3 occurrences of options -a and -b in any combination, and no trailing arguments:

    import ucb.util.CommandArgs;
    class foo {
      public static void main (String[] args0) {
         ...
         String options = "-c{1}:1 -q:1 -l:1 -n{0,1}:2 -N:2 -a={0,3}:3 -b=:3";
         CommandArgs args = new CommandArgs (options, args0);
         ...
    

By default, when an option has a value (indicated by = after the option key), that value may be any string. You may also describe argument values with general patterns in parentheses, using the regular-expression patterns provided by the Pattern class. For example, writing

    CommandArgs args = 
      new CommandArgs ("--flavor=(van(illa)?|choc(olate)?)", args0)
    
specifies any number of --flavor parameters, each of which may be either 'vanilla' ('van' for short) or 'chocolate' ('choc' for short).

Option descriptors

The option string that describes possible options consists of a sequence of option descriptors, separated by whitespace. The syntax of an option string is as follows:
       <option string> ::= <options> <trailing> | <options> | <trailing>
       <options> ::= <option> | <options> option>
       <option> ::= <option pattern> | <option pattern><repeat>
       <option pattern> ::= <simple pattern> | (<simple patterns>)
       <simple pattern> ::=
               <option key>
             | <option key>=<pattern>
       <option key> ::= 
                -<single graphic character other than ->
             | --<graphic characters other than = not starting with ->
       <simple patterns> ::= 
               <simple pattern> | <simple patterns> `|' <simple pattern>
       <repeat> ::= 
               <count> | <count> <label> | <label>
       <count> ::=
               {<integer>}
             | {<integer>,<integer>} 
             | {<integer>,} 
       <label> ::= : <positive integer>
       <trailing> ::= --=<pattern> | --=<pattern><repeat>
       <pattern> ::= <empty> | (<regular expression>)
     
<regular expression> is as described in the documentation for Pattern. The default is `.+' (any non-empty string).

A <repeat> clause limits the number of instances of a given option or trailing argument. When unspecified, it is "zero or more" ({0,}). A trailing <label> indicates a group of options that are mutually exclusive. The count that appears on the first option specification of the group applies to all (subsequent options should specify just the label part, not the { } part). At most one of the keys in any group may appear. The count applies to whichever one does.

No <option> may contain whitespace. Also, be careful of the usual escaping problems with representing regular expressions as java Strings. The regular expression \d, for example, is written as the String literal "\\d".


Nested Class Summary
 
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
 
Constructor Summary
CommandArgs(String optionString, String[] rawArgs)
          A set of argument values extracted from RAWARGS according to the description given in OPTIONSTRING.
 
Method Summary
 Set<Map.Entry<String,List<String>>> entrySet()
          The set of all pairs (KEY, VALUES) represented by THIS.
 String[] getArguments()
          The argument array (not a copy) with which THIS was created.
 double getDouble(String key)
          The value of the last occurrence of option KEY, as a floating-point value.
 int getInt(String key)
          The value of the last occurrence of option KEY, as a decimal integer.
 int getInt(String key, int radix)
          The value of the last occurrence of option KEY, as an integer of given RADIX.
 String getLast(String key)
          The argument value of the last occurrence of option KEY, or null if there is no occurrence, or it has the wrong format.
 long getLong(String key)
          The value of the last occurrence of option KEY, as a decimal integer.
 long getLong(String key, int radix)
          The value of the last occurrence of option KEY, as an integer of given RADIX.
 String getOptionString()
          The option string with which THIS was created.
 int number(String key)
          The number of occurrences of option key KEY.
 boolean ok()
          True iff all arguments were correct.
 List<String> optionKeys()
          A list of all keys that appeared in the arguments, in order of appearance.
 List<String> optionValues()
          A list of all option values that appeared in the arguments, in order of appearance.
 
Methods inherited from class java.util.AbstractMap
clear, clone, containsKey, containsValue, equals, get, hashCode, isEmpty, keySet, put, putAll, remove, size, toString, values
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface java.util.Map
clear, containsKey, containsValue, equals, get, hashCode, isEmpty, keySet, put, putAll, remove, size, values
 

Constructor Detail

CommandArgs

public CommandArgs(String optionString,
                   String[] rawArgs)
A set of argument values extracted from RAWARGS according to the description given in OPTIONSTRING. OPTIONSTRING is defined in the class documentation for this class (see above). RAWARGS is typically the array of arguments passed to the main procedure.

Throws:
IllegalArgumentException - if OPTIONSTRING does not conform to the syntax above.
PatternSyntaxException - if a regular expression in OPTIONSTRING has invalid format.
Method Detail

getOptionString

public String getOptionString()
The option string with which THIS was created.


getArguments

public String[] getArguments()
The argument array (not a copy) with which THIS was created.


number

public int number(String key)
The number of occurrences of option key KEY.


getLast

public String getLast(String key)
The argument value of the last occurrence of option KEY, or null if there is no occurrence, or it has the wrong format.


getInt

public int getInt(String key)
The value of the last occurrence of option KEY, as a decimal integer. Exception if there is no such option, or it does not have the format of an integer.

Throws:
NumberFormatException - if the value of option KEY is not a decimal numeral.

getInt

public int getInt(String key,
                  int radix)
The value of the last occurrence of option KEY, as an integer of given RADIX. Exception if there is no such option, or it does not have the format of an integer. Hexadecimal integers may have a leading '0x', which is ignored.

Throws:
NumberFormatException - if the value of option KEY is not a valid numeral of radix RADIX, or RADIX is not a valid RADIX.

getLong

public long getLong(String key)
The value of the last occurrence of option KEY, as a decimal integer. Exception if there is no such option, or it does not have the format of an integer.

Throws:
NumberFormatException - if the value of option KEY is not a decimal numeral.

getLong

public long getLong(String key,
                    int radix)
The value of the last occurrence of option KEY, as an integer of given RADIX. Exception if there is no such option, or it does not have the format of an integer. Hexadecimal integers may have a leading '0x', which is ignored.

Throws:
NumberFormatException - if the value of option KEY is not a valid numeral of radix RADIX, or RADIX is not a valid RADIX.

getDouble

public double getDouble(String key)
The value of the last occurrence of option KEY, as a floating-point value. Exception if there is no such option, or it does not have the proper format.

Throws:
NumberFormatException - if the value of option KEY is not a proper floating-point numeral.

ok

public boolean ok()
True iff all arguments were correct.


optionKeys

public List<String> optionKeys()
A list of all keys that appeared in the arguments, in order of appearance. Trailing arguments are marked with the key "--". Invalid keys are not represented.


optionValues

public List<String> optionValues()
A list of all option values that appeared in the arguments, in order of appearance. Trailing arguments appear at the end. Options that don't take values or are given a value of "", as are some options that are supplied incorrectly. The order and number of the elements corresponds to the result of optionKeys ().


entrySet

public Set<Map.Entry<String,List<String>>> entrySet()
The set of all pairs (KEY, VALUES) represented by THIS. Each key is an option key (such as "--output" or "-v"), and each value is a list of values that were supplied for that key (as by "--output=results.txt"). For options that don't accept an argument, the associated value is the empty string.

Specified by:
entrySet in interface Map<String,List<String>>
Specified by:
entrySet in class AbstractMap<String,List<String>>