Class ArgumentParserImpl
- All Implemented Interfaces:
ArgumentContainer
,ArgumentParser
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
private static class
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final int
private final List
<ArgumentGroupImpl> private final String
private final ArgumentParserConfigurationImpl
private boolean
private static final int
private String
private String
private final ArgumentParserImpl
private final Map
<String, ArgumentImpl> private final List
<ArgumentImpl> private static final Pattern
private boolean
private final List
<ArgumentImpl> private static final Pattern
private final SubparsersImpl
private static final int
private static final int
private String
private String
-
Constructor Summary
ConstructorsConstructorDescriptionArgumentParserImpl
(ArgumentParserConfigurationImpl config, String command, ArgumentParserImpl mainParser) -
Method Summary
Modifier and TypeMethodDescriptionprivate void
accumulatePositionalArg
(ParseState state, ArgumentImpl arg) This function accumulates arguments for a given positional argument.private void
addArgDefaultIfNotSuppressed
(Map<String, Object> opts, ArgumentImpl arg) addArgument
(String... nameOrFlags) Creates newArgument
, adds it to this container and returns it.addArgument
(ArgumentGroupImpl group, String... nameOrFlags) addArgumentGroup
(String title) Creates newArgumentGroup
object and adds to this parser and returns the object.private void
addArgValue
(Map<String, Object> opts, ArgumentImpl arg, Object value) Creates new mutually exclusive group,MutuallyExclusiveGroup
object, without title and adds to this parser and returns the object.addMutuallyExclusiveGroup
(String title) Creates new mutually exclusive group,MutuallyExclusiveGroup
object, and adds to this parser and returns the object.ReturnsSubparsers
.private void
addUpperParserUsage
(List<String> opts, ArgumentParserImpl parser) Appends command, required named arguments and positional arguments inparser
toopts
recursively.private boolean
Check that term forms a valid concatenated short options.private boolean
checkDefaultGroup
(List<ArgumentImpl> args) private void
checkMutex
(ArgumentImpl arg, ArgumentImpl[] groupUsed) Check that another option in mutually exclusive group has already been specified.private void
checkRequiredArgument
(ParseState state, Set<ArgumentImpl> used) private void
checkRequiredMutex
(ParseState state, ArgumentImpl[] used) defaultHelp
(boolean defaultHelp) If defaultHelp istrue
, the default values of arguments are printed in help message.description
(String description) Set text to display before the argument help.Sets the text to display after the argument help.private void
extendArgs
(ParseState state, String file) Extends arguments by reading additional arguments from file.private void
fillUserDataFromAttrs
(Object userData, Map<String, Object> attrs) private static List
<ArgumentImpl> private boolean
flagFound
(ParseState state) Returns true if state.getArg() is flag.Returns help message.private String
formatUnrecognizedArgumentErrorMessage
(ParseState state, String args) Format message for "Unrecognized arguments" error.Returns a brief description of how the program should be invoked on the command line.Returns version string.private boolean
fromFileFound
(ParseState state) private String
Get the configuration of this argument parser.getDefault
(String dest) Returns default value set byArgumentImpl.setDefault(Object)
orsetDefault(String, Object)
.(package private) ArgumentParserImpl
Returns main (parent) parser.getProg()
(package private) TextWidthCounter
void
Prints usage and error message.void
handleError
(ArgumentParserException e, PrintWriter writer) Prints usage and error message to the given writer.(package private) boolean
private int
levenshtein
(String a, String b) Calculates Damerau–Levenshtein distance between stringa
andb
with given costs.(package private) String
Parses command line arguments.void
Parses command line arguments.void
Parses command line arguments.void
Parses command line arguments.(package private) void
parseArgs
(ParseState state, Map<String, Object> attrs) private void
parseArgsOrFail
(String[] args) Parses command line arguments, handling any errors.parseKnownArgs
(String[] args, List<String> unknown) Just likeArgumentParser.parseArgs(String[])
, but parses only known arguments without throwing exception for unrecognized arguments.void
parseKnownArgs
(String[] args, List<String> unknown, Object userData) Just likeArgumentParser.parseArgs(String[], Object)
, but parses only known arguments without throwing exception for unrecognized arguments.void
Just likeArgumentParser.parseArgs(String[], Map)
, but parses only known arguments without throwing exception for unrecognized arguments.void
Just likeArgumentParser.parseArgs(String[], Map, Object)
, but parses only known arguments without throwing exception for unrecognized arguments.private void
parseKnownArgsCreatingUnknownIfNeeded
(String[] args, List<String> unknown, Map<String, Object> attrs) parseKnownArgsOrFail
(String[] args, List<String> unknown) Just likeArgumentParser.parseArgsOrFail(String[])
, but parses only known arguments without throwing exception for unrecognized arguments.private void
populateDefaults
(Map<String, Object> opts) private void
printArgumentHelp
(PrintWriter writer, List<ArgumentImpl> args, int format_width) private void
printArgumentUsage
(PrintWriter writer, List<String> opts, int offset, String firstIndent, String subsequentIndent, int format_width) private void
printCandidates
(String body, List<ArgumentParserImpl.SubjectBody> subjects, PrintWriter writer) Prints most similar subjects in subjects to body.private void
printCommandCandidates
(String command, PrintWriter writer) private void
printFlagCandidates
(String flagBody, PrintWriter writer) void
Prints help message in stdout.void
printHelp
(PrintWriter writer) Prints help message in writer.void
Print a brief description of how the program should be invoked on the command line in stdout.void
printUsage
(PrintWriter writer) Print a brief description of how the program should be invoked on the command line in writer.private void
printUsage
(PrintWriter writer, int format_width) void
Prints version string in stdout.void
printVersion
(PrintWriter writer) Prints version string in writer.private void
processArg
(Map<String, Object> res, ParseState state, ArgumentImpl arg, String flag, String embeddedValue) This function only handles a named argument.private void
processPositionalArgs
(Map<String, Object> res, ParseState state) This function processes named arguments accumulated in state.private String
removePrefix
(String flag) private ArgumentImpl
resolveNextFlag
(String flag) Returns named argument ArgumentImpl which matches given flag.setDefault
(String dest, Object value) Sets parser-level default value of attributedest
.setDefaults
(Map<String, Object> attrs) Sets parser-level default values fromattrs
.private String
Replace placeholder in src with actual value.Sets the text to display as usage line.Sets version string.
-
Field Details
-
SUBSTITUTION_COST
private static final int SUBSTITUTION_COST- See Also:
-
SWAP_COST
private static final int SWAP_COST- See Also:
-
DELETION_COST
private static final int DELETION_COST- See Also:
-
ADDITION_COST
private static final int ADDITION_COST- See Also:
-
namedArgIndex_
-
namedArgs_
-
posArgs_
-
argGroups_
-
defaults_
-
subparsers_
-
mainParser_
-
command_
-
config_
-
usage_
-
description_
-
epilog_
-
version_
-
defaultHelp_
private boolean defaultHelp_ -
negNumFlag_
private boolean negNumFlag_ -
NEG_NUM_PATTERN
-
SHORT_OPTS_PATTERN
-
-
Constructor Details
-
ArgumentParserImpl
-
ArgumentParserImpl
public ArgumentParserImpl(ArgumentParserConfigurationImpl config, String command, ArgumentParserImpl mainParser)
-
-
Method Details
-
addArgument
Description copied from interface:ArgumentContainer
Creates new
Argument
, adds it to this container and returns it.The
nameOrFlags
is either a single name of positional argument or a list of option strings for named argument, e.g.foo
or-f, --foo
.- Specified by:
addArgument
in interfaceArgumentContainer
- Parameters:
nameOrFlags
- A name or a list of option strings of newArgument
.- Returns:
Argument
object.
-
addArgument
-
addSubparsers
Description copied from interface:ArgumentParser
Returns
Subparsers
.The method name is rather controversial because repeated call of this method does not add new
Subparsers
object. Instead, this method always returns sameSubparsers
object.Subparsers
object provides a way to add sub-commands.- Specified by:
addSubparsers
in interfaceArgumentParser
- Returns:
Subparsers
object.
-
addArgumentGroup
Description copied from interface:ArgumentParser
Creates new
ArgumentGroup
object and adds to this parser and returns the object.The
title
is printed in help message as a title of this group.ArgumentGroup
provides a way to conceptually group up command line arguments.- Specified by:
addArgumentGroup
in interfaceArgumentParser
- Parameters:
title
- The title printed in help message.- Returns:
ArgumentGroup
object.
-
addMutuallyExclusiveGroup
Description copied from interface:ArgumentParser
Creates new mutually exclusive group,
MutuallyExclusiveGroup
object, without title and adds to this parser and returns the object.- Specified by:
addMutuallyExclusiveGroup
in interfaceArgumentParser
- Returns:
MutuallyExclusiveGroup
object.
-
addMutuallyExclusiveGroup
Description copied from interface:ArgumentParser
Creates new mutually exclusive group,
MutuallyExclusiveGroup
object, and adds to this parser and returns the object.The arguments added to this group are mutually exclusive; if more than one argument belong to the group are specified, an error will be reported. The
title
is printed in help message as a title of this group.- Specified by:
addMutuallyExclusiveGroup
in interfaceArgumentParser
- Parameters:
title
- The title printed in help message.- Returns:
- The
MutuallyExclusiveGroup
object.
-
usage
Description copied from interface:ArgumentParser
Sets the text to display as usage line. By default, the usage line is calculated from the arguments this object contains.
If the given usage contains
${prog}
string, it will be replaced with the program name given inArgumentParsers.newArgumentParser(String)
.- Specified by:
usage
in interfaceArgumentParser
- Parameters:
usage
- usage text- Returns:
- this
-
description
Set text to display before the argument help.- Specified by:
description
in interfaceArgumentContainer
- Specified by:
description
in interfaceArgumentParser
- Parameters:
description
- text to display before the argument help- Returns:
- this
-
epilog
Description copied from interface:ArgumentParser
Sets the text to display after the argument help.- Specified by:
epilog
in interfaceArgumentParser
- Parameters:
epilog
- The text to display after the argument help.- Returns:
- this
-
version
Description copied from interface:ArgumentParser
Sets version string. It will be displayed
ArgumentParser.printVersion()
.If the given usage contains
${prog}
string, it will be replaced with the program name given inArgumentParsers.newArgumentParser(String)
. This processed text will be printed without text-wrapping.- Specified by:
version
in interfaceArgumentParser
- Parameters:
version
- The version string.- Returns:
- this
-
defaultHelp
Description copied from interface:ArgumentParser
If defaultHelp is
true
, the default values of arguments are printed in help message.By default, the default values are not printed in help message.
- Specified by:
defaultHelp
in interfaceArgumentParser
- Parameters:
defaultHelp
- Switch to display the default value in help message.- Returns:
- this
-
isDefaultHelp
boolean isDefaultHelp() -
printArgumentHelp
-
printHelp
public void printHelp()Description copied from interface:ArgumentParser
Prints help message in stdout.- Specified by:
printHelp
in interfaceArgumentParser
-
printHelp
Description copied from interface:ArgumentParser
Prints help message in writer.- Specified by:
printHelp
in interfaceArgumentParser
- Parameters:
writer
- Writer to print message.
-
checkDefaultGroup
-
formatHelp
Description copied from interface:ArgumentParser
Returns help message.- Specified by:
formatHelp
in interfaceArgumentParser
- Returns:
- The help message.
-
printArgumentUsage
private void printArgumentUsage(PrintWriter writer, List<String> opts, int offset, String firstIndent, String subsequentIndent, int format_width) -
printUsage
public void printUsage()Description copied from interface:ArgumentParser
Print a brief description of how the program should be invoked on the command line in stdout.- Specified by:
printUsage
in interfaceArgumentParser
-
printUsage
Description copied from interface:ArgumentParser
Print a brief description of how the program should be invoked on the command line in writer.- Specified by:
printUsage
in interfaceArgumentParser
- Parameters:
writer
- Writer to print message.
-
printUsage
-
filterSuppressedArgs
- Parameters:
args
- arguments to filter- Returns:
- filtered list of arguments
-
addUpperParserUsage
Appends command, required named arguments and positional arguments inparser
toopts
recursively. Most upper parser stores first, just like post order traversal.- Parameters:
opts
- Command, required named arguments and positional arguments.parser
- The parser
-
formatUsage
Description copied from interface:ArgumentParser
Returns a brief description of how the program should be invoked on the command line.- Specified by:
formatUsage
in interfaceArgumentParser
- Returns:
- Usage text.
-
setDefault
Description copied from interface:ArgumentParser
Sets parser-level default value of attribute
dest
.The parser-level defaults always override argument-level defaults.
- Specified by:
setDefault
in interfaceArgumentParser
- Parameters:
dest
- The attribute name.value
- The default value.- Returns:
- this
-
setDefaults
Description copied from interface:ArgumentParser
Sets parser-level default values from
attrs
.All key-value pair in
attrs
are registered to parser-level defaults. The parser-level defaults always override argument-level defaults.- Specified by:
setDefaults
in interfaceArgumentParser
- Parameters:
attrs
- The parser-level default values to add.- Returns:
- this
-
getDefault
Returns default value set byArgumentImpl.setDefault(Object)
orsetDefault(String, Object)
. Please note that while parser-level defaults always override argument-level defaults while parsing, this method examines argument-level defaults first. If no default value is found, then check parser-level defaults.- Specified by:
getDefault
in interfaceArgumentParser
- Parameters:
dest
- attribute name of default value to get.- Returns:
- default value of given dest.
-
parseArgsOrFail
Description copied from interface:ArgumentParser
Parses command line arguments, handling any errors.
This is a shortcut method that combines
ArgumentParser.parseArgs(java.lang.String[])
andArgumentParser.handleError(net.sourceforge.argparse4j.inf.ArgumentParserException)
. If the arguments can be successfully parsed, the resulted attributes are returned as aNamespace
object. Otherwise, the program exits with a1
return code.- Specified by:
parseArgsOrFail
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.- Returns:
Namespace
object.
-
parseKnownArgsOrFail
Description copied from interface:ArgumentParser
Just like
ArgumentParser.parseArgsOrFail(String[])
, but parses only known arguments without throwing exception for unrecognized arguments. Ifunknown
is not null, unrecognized arguments will be stored in it.- Specified by:
parseKnownArgsOrFail
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.unknown
- Output variable to store unrecognized arguments, or null- Returns:
Namespace
object.
-
parseArgs
Description copied from interface:ArgumentParser
Parses command line arguments.
The resulted attributes are returned as
Namespace
object. This method must not alter the status of this parser and can be called multiple times.- Specified by:
parseArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.- Returns:
Namespace
object.- Throws:
ArgumentParserException
- If an error occurred.
-
parseKnownArgs
Description copied from interface:ArgumentParser
Just like
ArgumentParser.parseArgs(String[])
, but parses only known arguments without throwing exception for unrecognized arguments. Ifunknown
is not null, unrecognized arguments will be stored in it.- Specified by:
parseKnownArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.unknown
- Output variable to store unrecognized arguments, or null- Returns:
Namespace
object.- Throws:
ArgumentParserException
- If an error occurred.
-
parseArgs
Description copied from interface:ArgumentParser
Parses command line arguments.
Unlike
ArgumentParser.parseArgs(String[])
, which returnsNamespace
object, this method stores attributes in givenattrs
.- Specified by:
parseArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.attrs
- Map object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
parseKnownArgs
public void parseKnownArgs(String[] args, List<String> unknown, Map<String, Object> attrs) throws ArgumentParserExceptionDescription copied from interface:ArgumentParser
Just like
ArgumentParser.parseArgs(String[], Map)
, but parses only known arguments without throwing exception for unrecognized arguments. Ifunknown
is not null, unrecognized arguments will be stored in it.- Specified by:
parseKnownArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.unknown
- Output variable to store unrecognized arguments, or nullattrs
- Map object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
parseArgs
Description copied from interface:ArgumentParser
Parses command line arguments.
Unlike
ArgumentParser.parseArgs(String[])
, which returnsNamespace
object, this method stores attributes in givenuserData
. The location to store value is designated usingArg
annotations. User don't have to specifyArg
for all attributes: the missing attributes are just skipped. This method performs simpleList
to generic array conversion. For example, user can assignList<Integer>
attribute to generic arrayint[]
.- Specified by:
parseArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.userData
- Object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
parseKnownArgs
public void parseKnownArgs(String[] args, List<String> unknown, Object userData) throws ArgumentParserException Description copied from interface:ArgumentParser
Just like
ArgumentParser.parseArgs(String[], Object)
, but parses only known arguments without throwing exception for unrecognized arguments. Ifunknown
is not null, unrecognized arguments will be stored in it.- Specified by:
parseKnownArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.unknown
- Output variable to store unrecognized arguments, or nulluserData
- Object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
parseArgs
public void parseArgs(String[] args, Map<String, Object> attrs, Object userData) throws ArgumentParserExceptionDescription copied from interface:ArgumentParser
Parses command line arguments.
This is a combination of
ArgumentParser.parseArgs(String[], Map)
andArgumentParser.parseArgs(String[], Object)
. The all attributes will be stored inattrs
. The attributes specified inArg
annotations will be also stored inuserData
.- Specified by:
parseArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.attrs
- Map to store attributes.userData
- Object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
parseKnownArgs
public void parseKnownArgs(String[] args, List<String> unknown, Map<String, Object> attrs, Object userData) throws ArgumentParserExceptionDescription copied from interface:ArgumentParser
Just like
ArgumentParser.parseArgs(String[], Map, Object)
, but parses only known arguments without throwing exception for unrecognized arguments. Ifunknown
is not null, unrecognized arguments will be stored in it.- Specified by:
parseKnownArgs
in interfaceArgumentParser
- Parameters:
args
- Command line arguments.unknown
- Output variable to store unrecognized arguments, or nullattrs
- Map to store attributes.userData
- Object to store attributes.- Throws:
ArgumentParserException
- If an error occurred.
-
fillUserDataFromAttrs
-
parseKnownArgsCreatingUnknownIfNeeded
private void parseKnownArgsCreatingUnknownIfNeeded(String[] args, List<String> unknown, Map<String, Object> attrs) throws ArgumentParserException- Throws:
ArgumentParserException
-
parseArgsAtOffsetZero
private void parseArgsAtOffsetZero(String[] args, List<String> unknown, Map<String, Object> attrs) throws ArgumentParserException- Throws:
ArgumentParserException
-
checkConcatenatedShortOpts
Check that term forms a valid concatenated short options. Note that this option does not actually process arguments. Therefore, true from this function does not mean all arguments in term are acceptable.- Parameters:
term
- string to inspect- Returns:
- true if term forms a valid concatenated short options.
-
resolveNextFlag
Returns named argument ArgumentImpl which matches given flag. This function handles abbreviation as well. If flag is ambiguous,ArgumentParserException
will be thrown. If flag does not match any ArgumentImpl, this function returns null.- Parameters:
flag
- flag to match- Returns:
- ArgumentImpl which matches flag if it succeeds, or null
- Throws:
ArgumentParserException
- if flag is ambiguous
-
parseArgs
- Throws:
ArgumentParserException
-
formatUnrecognizedArgumentErrorMessage
Format message for "Unrecognized arguments" error.- Parameters:
state
- Current parser stateargs
- Textual representation of unrecognized arguments to be included in the message as is.- Returns:
- formatted error message
-
checkMutex
Check that another option in mutually exclusive group has already been specified. If so, throw an exception.- Parameters:
arg
- The argument currently processedgroupUsed
- The cache of used argument in each groups.- Throws:
ArgumentParserException
- If another option in mutually exclusive group has already been used.
-
processArg
private void processArg(Map<String, Object> res, ParseState state, ArgumentImpl arg, String flag, String embeddedValue) throws ArgumentParserExceptionThis function only handles a named argument.- Parameters:
embeddedValue
- If named argument is given as "foo=bar" or "-fbar" (short option), embedded value is "bar". Otherwisenull
- Throws:
ArgumentParserException
-
accumulatePositionalArg
private void accumulatePositionalArg(ParseState state, ArgumentImpl arg) throws ArgumentParserException This function accumulates arguments for a given positional argument. It only accumulates arguments based on how many arguments can be consumed for given Argument object. The actual processing are done later.- Throws:
ArgumentParserException
-
processPositionalArgs
private void processPositionalArgs(Map<String, Object> res, ParseState state) throws ArgumentParserExceptionThis function processes named arguments accumulated in state.- Throws:
ArgumentParserException
-
flagFound
Returns true if state.getArg() is flag. Note that if "--" is met and not consumed, this function returns true, because "--" is treated as special named argument. If prefixFileChar is found in prefix of argument, read arguments from that file and expand arguments in state necessary.- Throws:
ArgumentParserException
-
fromFileFound
-
extendArgs
Extends arguments by reading additional arguments from file.- Parameters:
state
- Current parser state.file
- File from which additional arguments are read.- Throws:
ArgumentParserException
-
checkRequiredArgument
-
checkRequiredMutex
-
populateDefaults
-
addArgDefaultIfNotSuppressed
-
addArgValue
-
getActualArgumentName
-
removePrefix
-
getConfig
Description copied from interface:ArgumentParser
Get the configuration of this argument parser.
- Specified by:
getConfig
in interfaceArgumentParser
- Returns:
- The argument parser configuration.
-
getProg
-
printVersion
public void printVersion()Description copied from interface:ArgumentParser
Prints version string in stdout.- Specified by:
printVersion
in interfaceArgumentParser
-
printVersion
Description copied from interface:ArgumentParser
Prints version string in writer.- Specified by:
printVersion
in interfaceArgumentParser
- Parameters:
writer
- Writer to print version string.
-
formatVersion
Description copied from interface:ArgumentParser
Returns version string.- Specified by:
formatVersion
in interfaceArgumentParser
- Returns:
- The version string.
-
handleError
Description copied from interface:ArgumentParser
Prints usage and error message.
Please note that this method does not terminate the program.
- Specified by:
handleError
in interfaceArgumentParser
- Parameters:
e
- Error thrown byArgumentParser.parseArgs(String[])
.
-
handleError
Description copied from interface:ArgumentParser
Prints usage and error message to the given writer.
Please note that this method does not terminate the program.
- Specified by:
handleError
in interfaceArgumentParser
- Parameters:
e
- Error thrown byArgumentParser.parseArgs(String[])
.writer
- The writer to which to write error messages
-
levenshtein
Calculates Damerau–Levenshtein distance between stringa
andb
with given costs.- Parameters:
a
- Stringb
- String- Returns:
- Damerau–Levenshtein distance between
a
andb
-
printFlagCandidates
-
printCommandCandidates
-
printCandidates
private void printCandidates(String body, List<ArgumentParserImpl.SubjectBody> subjects, PrintWriter writer) Prints most similar subjects in subjects to body. Similarity is calculated between body and eachArgumentParserImpl.SubjectBody.body
in subjects.- Parameters:
body
- String to compare.subjects
- Target to be compared.writer
- Output
-
substitutePlaceholder
Replace placeholder in src with actual value. The only known placeholder is ${prog}, which is replaced withconfig_.prog_
.- Parameters:
src
- string to be processed- Returns:
- the substituted string
-
getCommand
-
getTextWidthCounter
TextWidthCounter getTextWidthCounter() -
getPrefixChars
-
getFromFilePrefixChars
-
getMainParser
ArgumentParserImpl getMainParser()Returns main (parent) parser.- Returns:
- The main (parent) parser. null if this object is a root parser.
-
localize
-