Class CommandLineParser


  • public class CommandLineParser
    extends java.lang.Object
    CommandLineParser provides a utility for specifying the format of a command line and parsing command lines to ensure that they fit their specified format. A command line is made up of flags and options, both may be referred to as options. A flag is an option that does not take an argument (specifying it means it has the value 'true' and not specifying it means it has the value 'false'). Options must take arguments but they can be set up with defaults so that they take a default value when not set. Options may be mandatory in which case it is an error not to specify them on the command line. Flags are never mandatory because they are implicitly set to false when not specified.

    Some example command lines are:

    • This one has two options that expect arguments:
       cruisecontrol -configfile cruisecontrol.xml -port 9000
       
    • This has one no-arg flag and two 'free' arguments:
       zip -r project.zip project/*
       
    • This one concatenates multiple flags into a single block with only one '-':
       jar -tvf mytar.tar
       

    The parsing rules are:

    1. Flags may be combined after a single '-' because they never take arguments. Normally such flags are single letter flags but this is only a convention and not enforced. Flags of more than one letter are usually specified on their own.
    2. Options expecting arguments must always be on their own.
    3. The argument to an option may be separated from it by whitespace or appended directly onto the option.
    4. The argument to an option may never begin with a '-' character.
    5. All other arguments not beginning with a '-' character are free arguments that do not belong to any option.
    6. The second or later of a set of duplicate or repeated flags are ignored.
    7. Options are matched up to the shortest matching option. This is because of the possibility of having no space between an option and its argument. This rules out the possibility of using two options where one is an opening substring of the other. For example, the options "foo" and "foobar" cannot be used on the same command line because it is not possible to distinguish the argument "-foobar" from being the "foobar" option or the "foo" option with the "bar" argument.

    By default, unknown options are simply ignored if specified on the command line. This behaviour may be changed so that the parser reports all unknowns as errors by using the setErrorsOnUnknowns(boolean) method.

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      protected static class  CommandLineParser.CommandLineOption
      Holds information about a command line options.
    • Constructor Summary

      Constructors 
      Constructor Description
      CommandLineParser​(java.lang.String[][] config)
      Creates a command line options parser from a command line specification.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void addCommandLineToProperties​(java.util.Properties properties)
      If a command line has been parsed, calling this method sets all of its parsed options into the specified properties.
      protected void addOption​(java.lang.String option, java.lang.String comment, java.lang.String argument, boolean mandatory, java.lang.String formatRegexp)
      Adds the option to list of available command line options.
      java.lang.String getErrors()
      Lists all the parsing errors from the most recent parsing in a string.
      java.lang.String getOptionsInForce()
      Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet.
      java.lang.String getUsage()
      Generates a usage string consisting of the name of each option and each options argument description and comment.
      java.util.Properties parseCommandLine​(java.lang.String[] args)
      Parses a set of command line arguments into a set of properties, keyed by the argument flag.
      static java.util.Properties processCommandLine​(java.lang.String[] args, CommandLineParser commandLine, java.util.Properties properties)
      Extracts all name=value pairs from the command line, sets them all as system properties and also returns a map of properties containing them.
      void reset()
      Resets this command line parser after it has been used to parse a command line.
      void setErrorsOnUnknowns​(boolean errors)
      Control the behaviour of the errors on unkowns reporting.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • CommandLineParser

        public CommandLineParser​(java.lang.String[][] config)
        Creates a command line options parser from a command line specification. This is passed to this constructor as an array of arrays of strings. Each array of strings specifies the command line for a single option. A static array may therefore easily be used to configure the command line parser in a single method call with an easily readable format.

        Each array of strings must be 2, 3, 4 or 5 elements long. If any of the last three elements are missing they are assumed to be null. The elements specify the following parameters:

        1. The name of the option without the leading '-'. For example, "file". To specify the format of the 'free' arguments use the option names "1", "2", ... and so on.
        2. The option comment. A line of text describing the usage of the option. For example, "The file to be processed."
        3. The options argument. This is a very short description of the argument to the option, often a single word or a reminder as to the arguments format. When this element is null the option is a flag and does not accept any arguments. For example, "filename" or "(unix | windows)" or null. The actual text specified is only used to print in the usage message to remind the user of the usage of the option.
        4. The mandatory flag. When set to "true" an option must always be specified. Any other value, including null, means that the option is mandatory. Flags are always mandatory (see class javadoc for explanation of why) so this is ignored for flags.
        5. A regular expression describing the format that the argument must take. Ignored if null.

        An example call to this constructor is:

         CommandLineParser commandLine = new CommandLineParser(
             new String[][] {{"file", "The file to be processed. ", "filename", "true"},
                             {"dir", "Directory to store results in. Current dir used if not set.", "out dir"},
                             {"os", "Operating system EOL format to use.", "(windows | unix)", null, "windows\|unix"},
                             {"v", "Verbose mode. Prints information about the processing as it goes."},
                             {"1", "The processing command to run.", "command", "true", "add\|remove\|list"}});
         
        Parameters:
        config - The configuration as an array of arrays of strings.
    • Method Detail

      • getErrors

        public java.lang.String getErrors()
        Lists all the parsing errors from the most recent parsing in a string.
        Returns:
        All the parsing errors from the most recent parsing.
      • getOptionsInForce

        public java.lang.String getOptionsInForce()
        Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet.
        Returns:
        The properties set from the most recent parsing or an empty string if no parsing has been done yet.
      • getUsage

        public java.lang.String getUsage()
        Generates a usage string consisting of the name of each option and each options argument description and comment.
        Returns:
        A usage string for all the options.
      • setErrorsOnUnknowns

        public void setErrorsOnUnknowns​(boolean errors)
        Control the behaviour of the errors on unkowns reporting. When turned on this reports all unkowns options as errors. When turned off, all unknowns are simply ignored.
        Parameters:
        errors - The setting of the errors on unkown flag. True to turn it on.
      • parseCommandLine

        public java.util.Properties parseCommandLine​(java.lang.String[] args)
                                              throws java.lang.IllegalArgumentException
        Parses a set of command line arguments into a set of properties, keyed by the argument flag. The free arguments are keyed by integers as strings starting at "1" and then "2", ... and so on.

        See the class level comment for a description of the parsing rules.

        Parameters:
        args - The command line arguments.
        Returns:
        The arguments as a set of properties.
        Throws:
        java.lang.IllegalArgumentException - If the command line cannot be parsed against its specification. If this exception is thrown a call to getErrors() will provide a diagnostic of the command line errors.
      • addCommandLineToProperties

        public void addCommandLineToProperties​(java.util.Properties properties)
        If a command line has been parsed, calling this method sets all of its parsed options into the specified properties.
        Parameters:
        properties - properties
      • reset

        public void reset()
        Resets this command line parser after it has been used to parse a command line. This method will only need to be called to use this parser a second time which is not likely seeing as a command line is usually only specified once. However, it is exposed as a public method for the rare case where this may be done.

        Cleans the internal state of this parser, removing all stored errors and information about the options in force.

      • addOption

        protected void addOption​(java.lang.String option,
                                 java.lang.String comment,
                                 java.lang.String argument,
                                 boolean mandatory,
                                 java.lang.String formatRegexp)
        Adds the option to list of available command line options.
        Parameters:
        option - The option to add as an available command line option.
        comment - A comment for the option.
        argument - The text that appears after the option in the usage string.
        mandatory - When true, indicates that this option is mandatory.
        formatRegexp - The format that the argument must take, defined as a regular expression.
      • processCommandLine

        public static java.util.Properties processCommandLine​(java.lang.String[] args,
                                                              CommandLineParser commandLine,
                                                              java.util.Properties properties)
        Extracts all name=value pairs from the command line, sets them all as system properties and also returns a map of properties containing them.
        Parameters:
        args - The command line.
        commandLine - The command line parser.
        properties - The properties object to inject all parsed properties into (optional may be null).
        Returns:
        A set of properties containing all name=value pairs from the command line.