Class OptionParser
- All Implemented Interfaces:
OptionDeclarer
Parses command line arguments, using a syntax that attempts to take from the best of POSIX getopt()
and GNU getopt_long()
.
This parser supports short options and long options.
- Short options begin with a single hyphen ("
-
") followed by a single letter or digit, or question mark ("?
"), or dot (".
"), or underscore ("_
"). - Short options can accept single arguments. The argument can be made required or optional. The option's
argument can occur:
- in the slot after the option, as in
-d /tmp
- right up against the option, as in
-d/tmp
- right up against the option separated by an equals sign (
"="
), as in-d=/tmp
-d /tmp -d /var -d /opt
; or, when using the "separated values" clause of the "fluent interface" (see below), give multiple values separated by a given character as a single argument to the option. - in the slot after the option, as in
- Short options can be clustered, so that
-abc
is treated as-a -b -c
. If a short option in the cluster can accept an argument, the remaining characters are interpreted as the argument for that option. - An argument consisting only of two hyphens (
"--"
) signals that the remaining arguments are to be treated as non-options. - An argument consisting only of a single hyphen is considered a non-option argument (though it can be an argument of an option). Many Unix programs treat single hyphens as stand-ins for the standard input or standard output streams.
- Long options begin with two hyphens (
"--"
), followed by multiple letters, digits, hyphens, question marks, or dots. A hyphen cannot be the first character of a long option specification when configuring the parser. - You can abbreviate long options, so long as the abbreviation is unique. Suppress this behavior if you wish using this constructor.
- Long options can accept single arguments. The argument can be made required or optional. The option's
argument can occur:
- in the slot after the option, as in
--directory /tmp
- right up against the option separated by an equals sign (
"="
), as in--directory=/tmp
- in the slot after the option, as in
- You can use a single hyphen (
"-"
) instead of a double hyphen ("--"
) for a long option. - The option
-W
is reserved. If you tell the parser to recognize alternative long options, then it will treat, for example,-W foo=bar
as the long optionfoo
with argumentbar
, as though you had written--foo=bar
. - You can specify
-W
as a valid short option, or use it as an abbreviation for a long option, but recognizing alternative long options will always supersede this behavior. - You can specify a given short or long option multiple times on a single command line. The parser collects any arguments specified for those options as a list.
- If the parser detects an option whose argument is optional, and the next argument "looks like" an option,
that argument is not treated as the argument to the option, but as a potentially valid option. If, on the other
hand, the optional argument is typed as a derivative of
Number
, then that argument is treated as the negative number argument of the option, even if the parser recognizes the corresponding numeric option. For example:
In this case, the option set containsOptionParser parser = new OptionParser(); parser.accepts( "a" ).withOptionalArg().ofType( Integer.class ); parser.accepts( "2" ); OptionSet options = parser.parse( "-a", "-2" );
"a"
with argument-2
, not both"a"
and"2"
. Swapping the elements in the args array gives the latter.
There are two ways to tell the parser what options to recognize:
- A "fluent interface"-style API for specifying options, available since version 2. Sentences in this fluent
interface language begin with a call to
accepts
oracceptsAll
methods; calls on the ensuing chain of objects describe whether the options can take an argument, whether the argument is required or optional, to what type arguments of the options should be converted if any, etc. Since version 3, these calls return an instance ofOptionSpec
, which can subsequently be used to retrieve the arguments of the associated option in a type-safe manner. - Since version 1, a more concise way of specifying short options has been to use the special constructor. Arguments of options specified in this manner will be of type
String
. Here are the rules for the format of the specification strings this constructor accepts:- Any letter or digit is treated as an option character.
- An option character can be immediately followed by an asterisk (
*)
to indicate that the option is a "help" option. - If an option character (with possible trailing asterisk) is followed by a single colon (
":"
), then the option requires an argument. - If an option character (with possible trailing asterisk) is followed by two colons (
"::"
), then the option accepts an optional argument. - Otherwise, the option character accepts no argument.
- If the option specification string begins with a plus sign (
"+"
), the parser will behave "POSIX-ly correct". - If the option specification string contains the sequence
"W;"
(capital W followed by a semicolon), the parser will recognize the alternative form of long options.
Each of the options in a list of options given to acceptsAll
is treated as a
synonym of the others. For example:
OptionParser parser = new OptionParser();
parser.acceptsAll( asList( "w", "interactive", "confirmation" ) );
OptionSet options = parser.parse( "-w" );
In this case, options.
would answer has
true
when given arguments
"w"
, "interactive"
, and "confirmation"
. The OptionSet
would give the same
responses to these arguments for its other methods as well.
By default, as with GNU getopt()
, the parser allows intermixing of options and non-options. If, however,
the parser has been created to be "POSIX-ly correct", then the first argument that does not look lexically like an
option, and is not a required argument of a preceding option, signals the end of options. You can still bind
optional arguments to their options using the abutting (for short options) or =
syntax.
Unlike GNU getopt()
, this parser does not honor the environment variable POSIXLY_CORRECT
.
"POSIX-ly correct" parsers are configured by either:
- using the method
posixlyCorrect(boolean)
, or - using the constructor with an argument whose first character is a plus sign
(
"+"
)
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate boolean
private final Map
<List<String>, Set<OptionSpec<?>>> private final Map
<List<String>, Set<OptionSpec<?>>> private HelpFormatter
private boolean
private final OptionNameMap
<AbstractOptionSpec<?>> private final Map
<List<String>, Set<OptionSpec<?>>> private final Map
<List<String>, Set<OptionSpec<?>>> private OptionParserState
private final ArrayList
<AbstractOptionSpec<?>> -
Constructor Summary
ConstructorsConstructorDescriptionCreates an option parser that initially recognizes no options, and does not exhibit "POSIX-ly correct" behavior.OptionParser
(boolean allowAbbreviations) Creates an option parser that initially recognizes no options, and does not exhibit "POSIX-ly correct" behavior.OptionParser
(String optionSpecification) Creates an option parser and configures it to recognize the short options specified in the given string. -
Method Summary
Modifier and TypeMethodDescriptionprivate Map
<String, AbstractOptionSpec<?>> Tells the parser to recognize the given option.Tells the parser to recognize the given option.acceptsAll
(List<String> options) Tells the parser to recognize the given options, and treat them as synonymous.acceptsAll
(List<String> options, String description) Tells the parser to recognize the given options, and treat them as synonymous.void
Tells the parser to treat unrecognized options as non-option arguments.(package private) void
availableIf
(List<String> precedentSynonyms, String available) (package private) void
availableIf
(List<String> precedentSynonyms, OptionSpec<?> available) (package private) void
availableUnless
(List<String> precedentSynonyms, String available) (package private) void
availableUnless
(List<String> precedentSynonyms, OptionSpec<?> available) (package private) boolean
private void
ensureAllowedOptions
(OptionSet options) private void
ensureRequiredOptions
(OptionSet options) private static char[]
extractShortOptionsFrom
(String argument) void
formatHelpWith
(HelpFormatter formatter) Tells the parser to use the given formatter when asked to print help.(package private) void
handleLongOptionToken
(String candidate, ArgumentList arguments, OptionSet detected) (package private) void
handleNonOptionArgument
(String candidate, ArgumentList arguments, OptionSet detectedOptions) private void
handleShortOptionCluster
(String candidate, ArgumentList arguments, OptionSet detected) (package private) void
handleShortOptionToken
(String candidate, ArgumentList arguments, OptionSet detected) private boolean
isHelpOptionPresent
(OptionSet options) (package private) boolean
isRecognized
(String option) (package private) boolean
looksLikeAnOption
(String argument) private List
<AbstractOptionSpec<?>> missingRequiredOptions
(OptionSet options) void
mutuallyExclusive
(OptionSpecBuilder... specs) Mandates mutual exclusiveness for the options built by the specified builders.(package private) void
Gives an object that represents an access point for non-option arguments on a command line.nonOptions
(String description) Gives an object that represents an access point for non-option arguments on a command line.private boolean
optionsHasAnyOf
(OptionSet options, Collection<OptionSpec<?>> specs) Parses the given command line arguments according to the option specifications given to the parser.private static KeyValuePair
parseLongOptionWithArgument
(String argument) private static KeyValuePair
parseShortOptionWithArgument
(String argument) (package private) boolean
void
posixlyCorrect
(boolean setting) Tells the parser whether or not to behave "POSIX-ly correct"-ly.void
printHelpOn
(OutputStream sink) Writes information about the options this parser recognizes to the given output sink.void
printHelpOn
(Writer sink) Writes information about the options this parser recognizes to the given output sink.private void
putDependentOption
(List<String> precedentSynonyms, OptionSpec<?> required, Map<List<String>, Set<OptionSpec<?>>> target) (package private) void
recognize
(AbstractOptionSpec<?> spec) void
recognizeAlternativeLongOptions
(boolean recognize) Tells the parser either to recognize or ignore-W
-style long options.Map
<String, OptionSpec<?>> Retrieves all options-spec pairings which have been configured for the parser in the same order as declared during training.(package private) void
requiredIf
(List<String> precedentSynonyms, String required) (package private) void
requiredIf
(List<String> precedentSynonyms, OptionSpec<?> required) (package private) void
requiredUnless
(List<String> precedentSynonyms, String required) (package private) void
requiredUnless
(List<String> precedentSynonyms, OptionSpec<?> required) private void
reset()
private AbstractOptionSpec
<?> specFor
(char option) private AbstractOptionSpec
<?> private List
<AbstractOptionSpec<?>> unavailableOptions
(OptionSet options) private void
validateOptionCharacters
(char[] options)
-
Field Details
-
recognizedOptions
-
trainingOrder
-
requiredIf
-
requiredUnless
-
availableIf
-
availableUnless
-
state
-
posixlyCorrect
private boolean posixlyCorrect -
allowsUnrecognizedOptions
private boolean allowsUnrecognizedOptions -
helpFormatter
-
-
Constructor Details
-
OptionParser
public OptionParser()Creates an option parser that initially recognizes no options, and does not exhibit "POSIX-ly correct" behavior. -
OptionParser
public OptionParser(boolean allowAbbreviations) Creates an option parser that initially recognizes no options, and does not exhibit "POSIX-ly correct" behavior.- Parameters:
allowAbbreviations
- whether unambiguous abbreviations of long options should be recognized by the parser
-
OptionParser
Creates an option parser and configures it to recognize the short options specified in the given string. Arguments of options specified this way will be of typeString
.- Parameters:
optionSpecification
- an option specification- Throws:
NullPointerException
- ifoptionSpecification
isnull
OptionException
- if the option specification contains illegal characters or otherwise cannot be recognized
-
-
Method Details
-
accepts
Description copied from interface:OptionDeclarer
Tells the parser to recognize the given option.This method returns an instance of
OptionSpecBuilder
to allow the formation of parser directives as sentences in a fluent interface language. For example:OptionDeclarer parser = new OptionParser(); parser.accepts( "c" ).withRequiredArg().ofType( Integer.class );
If no methods are invoked on the returned
OptionSpecBuilder
, then the parser treats the option as accepting no argument.- Specified by:
accepts
in interfaceOptionDeclarer
- Parameters:
option
- the option to recognize- Returns:
- an object that can be used to flesh out more detail about the option
-
accepts
Description copied from interface:OptionDeclarer
Tells the parser to recognize the given option.- Specified by:
accepts
in interfaceOptionDeclarer
- Parameters:
option
- the option to recognizedescription
- a string that describes the purpose of the option. This is used when generating help information about the parser.- Returns:
- an object that can be used to flesh out more detail about the option
- See Also:
-
acceptsAll
Description copied from interface:OptionDeclarer
Tells the parser to recognize the given options, and treat them as synonymous.- Specified by:
acceptsAll
in interfaceOptionDeclarer
- Parameters:
options
- the options to recognize and treat as synonymous- Returns:
- an object that can be used to flesh out more detail about the options
- See Also:
-
acceptsAll
Description copied from interface:OptionDeclarer
Tells the parser to recognize the given options, and treat them as synonymous.- Specified by:
acceptsAll
in interfaceOptionDeclarer
- Parameters:
options
- the options to recognize and treat as synonymousdescription
- a string that describes the purpose of the option. This is used when generating help information about the parser.- Returns:
- an object that can be used to flesh out more detail about the options
- See Also:
-
nonOptions
Description copied from interface:OptionDeclarer
Gives an object that represents an access point for non-option arguments on a command line.- Specified by:
nonOptions
in interfaceOptionDeclarer
- Returns:
- an object that can be used to flesh out more detail about the non-option arguments
-
nonOptions
Description copied from interface:OptionDeclarer
Gives an object that represents an access point for non-option arguments on a command line.- Specified by:
nonOptions
in interfaceOptionDeclarer
- Parameters:
description
- a string that describes the purpose of the non-option arguments. This is used when generating help information about the parser.- Returns:
- an object that can be used to flesh out more detail about the non-option arguments
- See Also:
-
posixlyCorrect
public void posixlyCorrect(boolean setting) Description copied from interface:OptionDeclarer
Tells the parser whether or not to behave "POSIX-ly correct"-ly.- Specified by:
posixlyCorrect
in interfaceOptionDeclarer
- Parameters:
setting
-true
if the parser should behave "POSIX-ly correct"-ly
-
posixlyCorrect
boolean posixlyCorrect() -
allowsUnrecognizedOptions
public void allowsUnrecognizedOptions()Description copied from interface:OptionDeclarer
Tells the parser to treat unrecognized options as non-option arguments.
If not called, then the parser raises an
OptionException
when it encounters an unrecognized option.- Specified by:
allowsUnrecognizedOptions
in interfaceOptionDeclarer
-
doesAllowsUnrecognizedOptions
boolean doesAllowsUnrecognizedOptions() -
recognizeAlternativeLongOptions
public void recognizeAlternativeLongOptions(boolean recognize) Description copied from interface:OptionDeclarer
Tells the parser either to recognize or ignore-W
-style long options.- Specified by:
recognizeAlternativeLongOptions
in interfaceOptionDeclarer
- Parameters:
recognize
-true
if the parser is to recognize the special style of long options
-
recognize
-
printHelpOn
Writes information about the options this parser recognizes to the given output sink. The output sink is flushed, but not closed.- Parameters:
sink
- the sink to write information to- Throws:
IOException
- if there is a problem writing to the sinkNullPointerException
- ifsink
isnull
- See Also:
-
printHelpOn
Writes information about the options this parser recognizes to the given output sink. The output sink is flushed, but not closed.- Parameters:
sink
- the sink to write information to- Throws:
IOException
- if there is a problem writing to the sinkNullPointerException
- ifsink
isnull
- See Also:
-
formatHelpWith
Tells the parser to use the given formatter when asked to print help.- Parameters:
formatter
- the formatter to use for printing help- Throws:
NullPointerException
- if the formatter isnull
-
recognizedOptions
Retrieves all options-spec pairings which have been configured for the parser in the same order as declared during training. Option flags for specs are alphabetized byOptionSpec.options()
; only the order of the specs is preserved. (Note: prior to 4.7 the order was alphabetical across all options regardless of spec.)- Returns:
- a map containing all the configured options and their corresponding
OptionSpec
- Since:
- 4.6
-
_recognizedOptions
-
parse
Parses the given command line arguments according to the option specifications given to the parser.- Parameters:
arguments
- arguments to parse- Returns:
- an
OptionSet
describing the parsed options, their arguments, and any non-option arguments found - Throws:
OptionException
- if problems are detected while parsingNullPointerException
- if the argument list isnull
-
mutuallyExclusive
Mandates mutual exclusiveness for the options built by the specified builders.- Parameters:
specs
- descriptors for options that should be mutually exclusive on a command line.- Throws:
NullPointerException
- ifspecs
isnull
-
ensureRequiredOptions
-
ensureAllowedOptions
-
missingRequiredOptions
-
optionsHasAnyOf
-
isHelpOptionPresent
-
handleLongOptionToken
-
handleShortOptionToken
-
handleShortOptionCluster
-
handleNonOptionArgument
-
noMoreOptions
void noMoreOptions() -
looksLikeAnOption
-
isRecognized
-
requiredIf
-
requiredIf
-
requiredUnless
-
requiredUnless
-
availableIf
-
availableIf
-
availableUnless
-
availableUnless
-
putDependentOption
private void putDependentOption(List<String> precedentSynonyms, OptionSpec<?> required, Map<List<String>, Set<OptionSpec<?>>> target) -
specFor
-
specFor
-
reset
private void reset() -
extractShortOptionsFrom
-
validateOptionCharacters
private void validateOptionCharacters(char[] options) -
parseLongOptionWithArgument
-
parseShortOptionWithArgument
-