Package ucb.util

Class CommandArgs

  • All Implemented Interfaces:
    Iterable<String>

    public class CommandArgs
    extends Object
    implements Iterable<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 as a mapping between option keys (like "--opt" or "-x") to lists of argument values supplied for that option in the command-line arguments (these are lists 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 "--".

    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<String> arg1;
             CommandArgs args =
                new CommandArgs("-c -h -o={0,1} --={1}", args0);
             if (! args.ok())
                ERROR();
             cOptionSpecified = args.contains("-c");
             hOptionSpecified = args.contains("-h");
             oOptionValue = args.getLast("-o"); // null if absent.
             arg1 = args.getFirst("--");
             ...
       

    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.contains("-k"))
                count = args.getInt("-k");
             List<String> forms = args.get("--form");
             List<String> otherArgs = args.get("--");
        

    One can group options into mutually exclusive choices using a trailing ":N" label, where N is a numeral identifying the group. 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".

    • Constructor Summary

      Constructors 
      Constructor Description
      CommandArgs​(String optionString, String[] rawArgs)
      A set of argument values extracted from RAWARGS according to the description given in OPTIONSTRING.
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      boolean contains​(String key)
      Returns true iff option KEY is present.
      boolean containsKey​(String key)
      Deprecated.
      use contains(String) instead.
      List<String> get​(String key)
      Return the list of all argument values for option KEY, or null if the option does not appear.
      String[] getArguments()
      Return the argument array (not a copy) with which THIS was created.
      double getDouble​(String key)
      Return the value of the last occurrence of option KEY, as a floating-point value.
      double getDouble​(String key, double dflt)
      REturn the value of the last occurrence of option KEY, as a floating-point value, or DFLT if KEY is not present.
      String getFirst​(String key)
      The argument value of the first occurrence of option KEY, or null if there is no occurrence, or it has the wrong format.
      String getFirst​(String key, String dflt)
      The argument value of the first occurrence of option KEY, or DFLT if there is no occurrence, or it has the wrong format.
      int getInt​(String key)
      Return The value of the last occurrence of option KEY, as a decimal integer.
      int getInt​(String key, int radix)
      Return The value of the last occurrence of option KEY, as an integer of given RADIX.
      int getInt​(String key, int radix, int dflt)
      Return the value of the last occurrence of option KEY, as an integer of given RADIX, or DFLT if KEY is not present.
      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.
      String getLast​(String key, String dflt)
      The argument value of the last occurrence of option KEY, or DFLT if there is no occurrence, or it has the wrong format.
      long getLong​(String key)
      Return the value of the last occurrence of option KEY, as a decimal integer.
      long getLong​(String key, int radix)
      Return the value of the last occurrence of option KEY, as an integer of given RADIX.
      long getLong​(String key, int radix, long dflt)
      Return the value of the last occurrence of option KEY, as an integer of given RADIX, or DFLT if KEY is not present.
      String getOptionString()
      Return the option string with which THIS was created.
      Iterator<String> iterator()
      Return An iterator over the set of keys in optionKeys().
      int number​(String key)
      Return the number of occurrences of option key KEY.
      boolean ok()
      Return true iff all arguments were correct.
      List<String> optionKeys()
      Return a list of all keys that appeared in the arguments, in order of appearance.
      List<String> optionValues()
      Return A list of all option values that appeared in the arguments, in order of appearance.
    • 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. Throws PatternSyntaxException if a regular expression in OPTIONSTRING has invalid format.
    • Method Detail

      • getOptionString

        public String getOptionString()
        Return the option string with which THIS was created.
      • getArguments

        public String[] getArguments()
        Return the argument array (not a copy) with which THIS was created.
      • number

        public int number​(String key)
        Return the number of occurrences of option key KEY.
      • contains

        public boolean contains​(String key)
        Returns true iff option KEY is present.
      • get

        public List<String> get​(String key)
        Return the list of all argument values for option KEY, or null if the option does not appear. If an option appears, but does not take a value, the values in the list will all be "".
      • getFirst

        public String getFirst​(String key)
        The argument value of the first occurrence of option KEY, or null if there is no occurrence, or it has the wrong format. If an option appears, but does not take a value, returns "".
      • getFirst

        public String getFirst​(String key,
                               String dflt)
        The argument value of the first occurrence of option KEY, or DFLT if there is no occurrence, or it has the wrong format. If an option appears, but does not take a value, returns "".
      • getLast

        public String getLast​(String key,
                              String dflt)
        The argument value of the last occurrence of option KEY, or DFLT if there is no occurrence, or it has the wrong format. If an option appears, but does not take a value, returns "".
      • 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. If an option appears, but does not take a value, returns "".
      • getInt

        public int getInt​(String key)
        Return 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 in the range of type int.
      • getInt

        public int getInt​(String key,
                          int radix)
        Return 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, RADIX is not a valid RADIX, or the number if out of range.
      • getInt

        public int getInt​(String key,
                          int radix,
                          int dflt)
        Return the value of the last occurrence of option KEY, as an integer of given RADIX, or DFLT if KEY is not present. Exception if value 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, RADIX is not a valid RADIX, or the number if out of range.
      • getLong

        public long getLong​(String key)
        Return 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 in the range of long.
      • getLong

        public long getLong​(String key,
                            int radix)
        Return 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, RADIX is not a valid RADIX, or the result is not in the range of long.
      • getLong

        public long getLong​(String key,
                            int radix,
                            long dflt)
        Return the value of the last occurrence of option KEY, as an integer of given RADIX, or DFLT if KEY is not present. Exception if value does not have the format of a long 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, RADIX is not a valid RADIX, or the result is not in the range of long.
      • getDouble

        public double getDouble​(String key)
        Return 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.
      • getDouble

        public double getDouble​(String key,
                                double dflt)
        REturn the value of the last occurrence of option KEY, as a floating-point value, or DFLT if KEY is not present. Exception if value 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()
        Return true iff all arguments were correct.
      • optionKeys

        public List<String> optionKeys()
        Return 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()
        Return 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().