public class OptionParser extends java.lang.Object implements 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.
-") followed by a single letter or digit,
or question mark ("?"), or dot ("."), or underscore ("_").-d /tmp-d/tmp"="), 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.-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."--") signals that the remaining arguments are to be
treated as non-options."--"), 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.--directory /tmp"="), as in
--directory=/tmp
"-") instead of a double hyphen ("--") for a long
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 option foo with argument bar, as though you had written
--foo=bar.-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.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:
OptionParser parser = new OptionParser();
parser.accepts( "a" ).withOptionalArg().ofType( Integer.class );
parser.accepts( "2" );
OptionSet options = parser.parse( "-a", "-2" );
In this case, the option set contains "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:
accepts or acceptsAll 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 of OptionSpec, which can subsequently be used to
retrieve the arguments of the associated option in a type-safe manner.String.
Here are the rules for the format of the specification strings this constructor accepts:
*) to indicate that
the option is a "help" option.":"),
then the option requires an argument."::"),
then the option accepts an optional argument."+" ), the parser will behave
"POSIX-ly correct"."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 hastrue 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:
posixlyCorrect(boolean), or"+")| Modifier and Type | Field and Description |
|---|---|
private boolean |
allowsUnrecognizedOptions |
private java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> |
availableIf |
private java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> |
availableUnless |
private HelpFormatter |
helpFormatter |
private boolean |
posixlyCorrect |
private OptionNameMap<AbstractOptionSpec<?>> |
recognizedOptions |
private java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> |
requiredIf |
private java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> |
requiredUnless |
private OptionParserState |
state |
private java.util.ArrayList<AbstractOptionSpec<?>> |
trainingOrder |
| Constructor and Description |
|---|
OptionParser()
Creates 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(java.lang.String optionSpecification)
Creates an option parser and configures it to recognize the short options specified in the given string.
|
| Modifier and Type | Method and Description |
|---|---|
private java.util.Map<java.lang.String,AbstractOptionSpec<?>> |
_recognizedOptions() |
OptionSpecBuilder |
accepts(java.lang.String option)
Tells the parser to recognize the given option.
|
OptionSpecBuilder |
accepts(java.lang.String option,
java.lang.String description)
Tells the parser to recognize the given option.
|
OptionSpecBuilder |
acceptsAll(java.util.List<java.lang.String> options)
Tells the parser to recognize the given options, and treat them as synonymous.
|
OptionSpecBuilder |
acceptsAll(java.util.List<java.lang.String> options,
java.lang.String description)
Tells the parser to recognize the given options, and treat them as synonymous.
|
void |
allowsUnrecognizedOptions()
Tells the parser to treat unrecognized options as non-option arguments.
|
(package private) void |
availableIf(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> available) |
(package private) void |
availableIf(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String available) |
(package private) void |
availableUnless(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> available) |
(package private) void |
availableUnless(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String available) |
(package private) boolean |
doesAllowsUnrecognizedOptions() |
private void |
ensureAllowedOptions(OptionSet options) |
private void |
ensureRequiredOptions(OptionSet options) |
private static char[] |
extractShortOptionsFrom(java.lang.String argument) |
void |
formatHelpWith(HelpFormatter formatter)
Tells the parser to use the given formatter when asked to print help.
|
(package private) void |
handleLongOptionToken(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected) |
(package private) void |
handleNonOptionArgument(java.lang.String candidate,
ArgumentList arguments,
OptionSet detectedOptions) |
private void |
handleShortOptionCluster(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected) |
(package private) void |
handleShortOptionToken(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected) |
private boolean |
isHelpOptionPresent(OptionSet options) |
(package private) boolean |
isRecognized(java.lang.String option) |
(package private) boolean |
looksLikeAnOption(java.lang.String argument) |
private java.util.List<AbstractOptionSpec<?>> |
missingRequiredOptions(OptionSet options) |
void |
mutuallyExclusive(OptionSpecBuilder... specs)
Mandates mutual exclusiveness for the options built by the specified builders.
|
(package private) void |
noMoreOptions() |
NonOptionArgumentSpec<java.lang.String> |
nonOptions()
Gives an object that represents an access point for non-option arguments on a command line.
|
NonOptionArgumentSpec<java.lang.String> |
nonOptions(java.lang.String description)
Gives an object that represents an access point for non-option arguments on a command line.
|
private boolean |
optionsHasAnyOf(OptionSet options,
java.util.Collection<OptionSpec<?>> specs) |
OptionSet |
parse(java.lang.String... arguments)
Parses the given command line arguments according to the option specifications given to the parser.
|
private static KeyValuePair |
parseLongOptionWithArgument(java.lang.String argument) |
private static KeyValuePair |
parseShortOptionWithArgument(java.lang.String argument) |
(package private) boolean |
posixlyCorrect() |
void |
posixlyCorrect(boolean setting)
Tells the parser whether or not to behave "POSIX-ly correct"-ly.
|
void |
printHelpOn(java.io.OutputStream sink)
Writes information about the options this parser recognizes to the given output sink.
|
void |
printHelpOn(java.io.Writer sink)
Writes information about the options this parser recognizes to the given output sink.
|
private void |
putDependentOption(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required,
java.util.Map<java.util.List<java.lang.String>,java.util.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. |
java.util.Map<java.lang.String,OptionSpec<?>> |
recognizedOptions()
Retrieves all options-spec pairings which have been configured for the parser in the same order as declared
during training.
|
(package private) void |
requiredIf(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required) |
(package private) void |
requiredIf(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String required) |
(package private) void |
requiredUnless(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required) |
(package private) void |
requiredUnless(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String required) |
private void |
reset() |
private AbstractOptionSpec<?> |
specFor(char option) |
private AbstractOptionSpec<?> |
specFor(java.lang.String option) |
private java.util.List<AbstractOptionSpec<?>> |
unavailableOptions(OptionSet options) |
private void |
validateOptionCharacters(char[] options) |
private final OptionNameMap<AbstractOptionSpec<?>> recognizedOptions
private final java.util.ArrayList<AbstractOptionSpec<?>> trainingOrder
private final java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> requiredIf
private final java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> requiredUnless
private final java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> availableIf
private final java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> availableUnless
private OptionParserState state
private boolean posixlyCorrect
private boolean allowsUnrecognizedOptions
private HelpFormatter helpFormatter
public OptionParser()
public OptionParser(boolean allowAbbreviations)
allowAbbreviations - whether unambiguous abbreviations of long options should be recognized
by the parserpublic OptionParser(java.lang.String optionSpecification)
String.optionSpecification - an option specificationjava.lang.NullPointerException - if optionSpecification is nullOptionException - if the option specification contains illegal characters or otherwise cannot be
recognizedpublic OptionSpecBuilder accepts(java.lang.String option)
OptionDeclarerThis 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.
accepts in interface OptionDeclareroption - the option to recognizepublic OptionSpecBuilder accepts(java.lang.String option, java.lang.String description)
OptionDeclareraccepts in interface OptionDeclareroption - the option to recognizedescription - a string that describes the purpose of the option. This is used when generating help
information about the parser.OptionDeclarer.accepts(String)public OptionSpecBuilder acceptsAll(java.util.List<java.lang.String> options)
OptionDeclareracceptsAll in interface OptionDeclareroptions - the options to recognize and treat as synonymousOptionDeclarer.accepts(String)public OptionSpecBuilder acceptsAll(java.util.List<java.lang.String> options, java.lang.String description)
OptionDeclareracceptsAll in interface OptionDeclareroptions - 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.OptionDeclarer.acceptsAll(List)public NonOptionArgumentSpec<java.lang.String> nonOptions()
OptionDeclarernonOptions in interface OptionDeclarerpublic NonOptionArgumentSpec<java.lang.String> nonOptions(java.lang.String description)
OptionDeclarernonOptions in interface OptionDeclarerdescription - a string that describes the purpose of the non-option arguments. This is used when generating
help information about the parser.OptionDeclarer.nonOptions()public void posixlyCorrect(boolean setting)
OptionDeclarerposixlyCorrect in interface OptionDeclarersetting - true if the parser should behave "POSIX-ly correct"-lyboolean posixlyCorrect()
public void allowsUnrecognizedOptions()
OptionDeclarerTells 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.
allowsUnrecognizedOptions in interface OptionDeclarerboolean doesAllowsUnrecognizedOptions()
public void recognizeAlternativeLongOptions(boolean recognize)
OptionDeclarer-W-style long options.recognizeAlternativeLongOptions in interface OptionDeclarerrecognize - true if the parser is to recognize the special style of long optionsvoid recognize(AbstractOptionSpec<?> spec)
public void printHelpOn(java.io.OutputStream sink)
throws java.io.IOException
sink - the sink to write information tojava.io.IOException - if there is a problem writing to the sinkjava.lang.NullPointerException - if sink is nullprintHelpOn(Writer)public void printHelpOn(java.io.Writer sink)
throws java.io.IOException
sink - the sink to write information tojava.io.IOException - if there is a problem writing to the sinkjava.lang.NullPointerException - if sink is nullprintHelpOn(OutputStream)public void formatHelpWith(HelpFormatter formatter)
formatter - the formatter to use for printing helpjava.lang.NullPointerException - if the formatter is nullpublic java.util.Map<java.lang.String,OptionSpec<?>> recognizedOptions()
OptionSpec.options(); only the order of the
specs is preserved.
(Note: prior to 4.7 the order was alphabetical across all options regardless of spec.)OptionSpecprivate java.util.Map<java.lang.String,AbstractOptionSpec<?>> _recognizedOptions()
public OptionSet parse(java.lang.String... arguments)
arguments - arguments to parseOptionSet describing the parsed options, their arguments, and any non-option arguments foundOptionException - if problems are detected while parsingjava.lang.NullPointerException - if the argument list is nullpublic void mutuallyExclusive(OptionSpecBuilder... specs)
specs - descriptors for options that should be mutually exclusive on a command line.java.lang.NullPointerException - if specs is nullprivate void ensureRequiredOptions(OptionSet options)
private void ensureAllowedOptions(OptionSet options)
private java.util.List<AbstractOptionSpec<?>> missingRequiredOptions(OptionSet options)
private java.util.List<AbstractOptionSpec<?>> unavailableOptions(OptionSet options)
private boolean optionsHasAnyOf(OptionSet options, java.util.Collection<OptionSpec<?>> specs)
private boolean isHelpOptionPresent(OptionSet options)
void handleLongOptionToken(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected)
void handleShortOptionToken(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected)
private void handleShortOptionCluster(java.lang.String candidate,
ArgumentList arguments,
OptionSet detected)
void handleNonOptionArgument(java.lang.String candidate,
ArgumentList arguments,
OptionSet detectedOptions)
void noMoreOptions()
boolean looksLikeAnOption(java.lang.String argument)
boolean isRecognized(java.lang.String option)
void requiredIf(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String required)
void requiredIf(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required)
void requiredUnless(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String required)
void requiredUnless(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required)
void availableIf(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String available)
void availableIf(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> available)
void availableUnless(java.util.List<java.lang.String> precedentSynonyms,
java.lang.String available)
void availableUnless(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> available)
private void putDependentOption(java.util.List<java.lang.String> precedentSynonyms,
OptionSpec<?> required,
java.util.Map<java.util.List<java.lang.String>,java.util.Set<OptionSpec<?>>> target)
private AbstractOptionSpec<?> specFor(char option)
private AbstractOptionSpec<?> specFor(java.lang.String option)
private void reset()
private static char[] extractShortOptionsFrom(java.lang.String argument)
private void validateOptionCharacters(char[] options)
private static KeyValuePair parseLongOptionWithArgument(java.lang.String argument)
private static KeyValuePair parseShortOptionWithArgument(java.lang.String argument)