public class CommandLine extends Object
CommandLine interpreter that uses reflection to initialize an annotated user object with values obtained from the command line arguments.
The full user manual is hosted at https://picocli.info.
An example that implements Callable
and uses the CommandLine.execute
convenience API to run in a single line of code:
@Command(name = "checksum", mixinStandardHelpOptions = true, version = "checksum 4.0", description = "Prints the checksum (SHA-1 by default) of a file to STDOUT.") class CheckSum implements Callable<Integer> { @Parameters(index = "0", description = "The file whose checksum to calculate.") private File file; @Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...") private String algorithm = "SHA-1"; @Override public Integer call() throws Exception { // your business logic goes here... byte[] fileContents = Files.readAllBytes(file.toPath()); byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents); System.out.printf("%0" + (digest.length*2) + "x%n", new BigInteger(1,digest)); return 0; } // CheckSum implements Callable, so parsing, error handling and handling user // requests for usage help or version help can be done with one line of code. public static void main(String[] args) { int exitCode = new CommandLine(new CheckSum()).execute(args); System.exit(exitCode); } }
Another example where the application calls parseArgs
and takes responsibility
for error handling and checking whether the user requested help:
import static picocli.CommandLine.*; @Command(mixinStandardHelpOptions = true, version = "v3.0.0", header = "Encrypt FILE(s), or standard input, to standard output or to the output file.") public class Encrypt { @Parameters(description = "Any number of input files") private List<File> files = new ArrayList<File>(); @Option(names = { "-o", "--out" }, description = "Output file (default: print to console)") private File outputFile; @Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.") private boolean[] verbose; }
Use CommandLine
to initialize a user object as follows:
public static void main(String... args) { Encrypt encrypt = new Encrypt(); try { ParseResult parseResult = new CommandLine(encrypt).parseArgs(args); if (!CommandLine.printHelpIfRequested(parseResult)) { runProgram(encrypt); } } catch (ParameterException ex) { // command line arguments could not be parsed System.err.println(ex.getMessage()); ex.getCommandLine().usage(System.err); } }
Invoke the above program with some command line arguments. The below are all equivalent:
--verbose --out=outfile in1 in2 --verbose --out outfile in1 in2 -v --out=outfile in1 in2 -v -o outfile in1 in2 -v -o=outfile in1 in2 -vo outfile in1 in2 -vo=outfile in1 in2 -v -ooutfile in1 in2 -vooutfile in1 in2
Modifier and Type | Class and Description |
---|---|
static class |
CommandLine.AbstractHandler<R,T extends CommandLine.AbstractHandler<R,T>>
Deprecated.
|
static class |
CommandLine.AbstractParseResultHandler<R>
|
static interface |
CommandLine.ArgGroup
A
Command may define one or more ArgGroups : a group of options, positional parameters or a mixture of the two. |
static interface |
CommandLine.Command
Annotate your class with
@Command when you want more control over the format of the generated help
message. |
static class |
CommandLine.DefaultExceptionHandler<R>
Deprecated.
|
static class |
CommandLine.DuplicateNameException
Exception indicating that multiple named elements have incorrectly used the same name.
|
static class |
CommandLine.DuplicateOptionAnnotationsException
Exception indicating that multiple fields have been annotated with the same Option name.
|
static class |
CommandLine.ExecutionException
Exception indicating a problem while invoking a command or subcommand.
|
static class |
CommandLine.ExitCode
Defines some exit codes used by picocli as default return values from the
execute
and executeHelpRequest methods. |
static class |
CommandLine.Help
A collection of methods and inner classes that provide fine-grained control over the contents and layout of
the usage help message to display to end users when help is requested or invalid input values were specified.
|
static class |
CommandLine.HelpCommand
Help command that can be installed as a subcommand on all application commands.
|
static interface |
CommandLine.IDefaultValueProvider
Provides default value for a command.
|
static interface |
CommandLine.IExceptionHandler
|
static interface |
CommandLine.IExceptionHandler2<R>
|
static interface |
CommandLine.IExecutionExceptionHandler
Classes implementing this interface know how to handle Exceptions that occurred while executing the
Runnable , Callable or Method user object of the command. |
static interface |
CommandLine.IExecutionStrategy
Implementations are responsible for "executing" the user input and returning an exit code.
|
static interface |
CommandLine.IExitCodeExceptionMapper
Interface that provides the appropriate exit code that will be returned from the
execute
method for an exception that occurred during parsing or while invoking the command's Runnable, Callable, or Method. |
static interface |
CommandLine.IExitCodeGenerator
@Command -annotated classes can implement this interface to specify an exit code that will be returned
from the execute method when the command is successfully invoked. |
static interface |
CommandLine.IFactory
Factory for instantiating classes that are registered declaratively with annotation attributes, like
CommandLine.Command.subcommands() , CommandLine.Option.converter() , CommandLine.Parameters.converter() and CommandLine.Command.versionProvider() . |
static interface |
CommandLine.IHelpCommandInitializable
Deprecated.
use
CommandLine.IHelpCommandInitializable2 instead |
static interface |
CommandLine.IHelpCommandInitializable2
Help commands that provide usage help for other commands can implement this interface to be initialized with the information they need.
|
static interface |
CommandLine.IHelpFactory
Creates the
CommandLine.Help instance used to render the usage help message. |
static interface |
CommandLine.IHelpSectionRenderer
Renders a section of the usage help message.
|
static interface |
CommandLine.IModelTransformer
Provides a way to modify how the command model is built.
|
static interface |
CommandLine.INegatableOptionTransformer
Determines the option name transformation of negatable boolean options.
|
static class |
CommandLine.InitializationException
Exception indicating a problem during
CommandLine initialization. |
static interface |
CommandLine.IParameterConsumer
Options or positional parameters can be assigned a
IParameterConsumer that implements
custom logic to process the parameters for this option or this position. |
static interface |
CommandLine.IParameterExceptionHandler
Classes implementing this interface know how to handle
ParameterExceptions (usually from invalid user input). |
static interface |
CommandLine.IParameterPreprocessor
Options, positional parameters and commands can be assigned a
IParameterPreprocessor that
implements custom logic to preprocess the parameters for this option, position or command. |
static interface |
CommandLine.IParseResultHandler
Deprecated.
Use
CommandLine.IExecutionStrategy instead. |
static interface |
CommandLine.IParseResultHandler2<R>
Deprecated.
use
CommandLine.IExecutionStrategy instead, see execute(String...) |
static interface |
CommandLine.ITypeConverter<K>
When parsing command line arguments and initializing
fields annotated with
@Option or @Parameters ,
String values can be converted to any type for which a ITypeConverter is registered. |
static interface |
CommandLine.IVersionProvider
Provides version information for a command.
|
static class |
CommandLine.MaxValuesExceededException
Exception indicating that more values were specified for an option or parameter than its
arity allows. |
static class |
CommandLine.MissingParameterException
Exception indicating that a required parameter was not specified.
|
static class |
CommandLine.MissingTypeConverterException
Exception indicating that an annotated field had a type for which no
CommandLine.ITypeConverter was
registered. |
static interface |
CommandLine.Mixin
Fields annotated with
@Mixin are "expanded" into the current command: @Option and
@Parameters in the mixin class are added to the options and positional parameters of this command. |
static class |
CommandLine.Model
This class provides a namespace for classes and interfaces that model concepts and attributes of command line interfaces in picocli.
|
static class |
CommandLine.MutuallyExclusiveArgsException
Exception indicating that the user input included multiple arguments from a mutually exclusive group.
|
static interface |
CommandLine.Option
Annotate fields in your class with
@Option and picocli will initialize these fields when matching
arguments are specified on the command line. |
static class |
CommandLine.OverwrittenOptionException
Exception indicating that an option for a single-value option field has been specified multiple times on the command line.
|
static class |
CommandLine.ParameterException
Exception indicating something went wrong while parsing command line options.
|
static class |
CommandLine.ParameterIndexGapException
Exception indicating that there was a gap in the indices of the fields annotated with
CommandLine.Parameters . |
static interface |
CommandLine.Parameters
Fields annotated with
@Parameters will be initialized with positional parameters. |
static interface |
CommandLine.ParentCommand
Fields annotated with
@ParentCommand will be initialized with the parent command of the current subcommand. |
static class |
CommandLine.ParseResult
Encapsulates the result of parsing an array of command line arguments.
|
static class |
CommandLine.PicocliException
Base class of all exceptions thrown by
picocli.CommandLine . |
static class |
CommandLine.PropertiesDefaultProvider
IDefaultValueProvider implementation that loads default values for command line
options and positional parameters from a properties file or Properties object. |
static class |
CommandLine.Range
Describes the number of parameters required and accepted by an option or a positional parameter.
|
static class |
CommandLine.RegexTransformer
A regular expression-based option name transformation for negatable options.
|
static class |
CommandLine.RunAll
Command line execution strategy that prints help if requested, and otherwise executes the top-level command and
all subcommands as
Runnable , Callable or Method . |
static class |
CommandLine.RunFirst
Command line execution strategy that prints help if requested, and otherwise executes the top-level
Runnable or Callable command. |
static class |
CommandLine.RunLast
Command line execution strategy that prints help if requested, and otherwise executes the most specific
Runnable or Callable subcommand. |
static class |
CommandLine.ScopeType
Specifies the scope of the element.
|
static interface |
CommandLine.Spec
Fields annotated with
@Spec will be initialized with the CommandSpec for the command the field is part of. |
static class |
CommandLine.TraceLevel
Enumerates over the trace level values for filtering which internal debug statements should be printed.
|
static class |
CommandLine.Tracer
Utility class for printing internal debug statements.
|
static class |
CommandLine.TypeConversionException
Exception thrown by
CommandLine.ITypeConverter implementations to indicate a String could not be converted. |
static interface |
CommandLine.Unmatched
Fields annotated with
@Unmatched will be initialized with the list of unmatched command line arguments, if any. |
static class |
CommandLine.UnmatchedArgumentException
Exception indicating that a command line argument could not be mapped to any of the fields annotated with
CommandLine.Option or CommandLine.Parameters . |
static class |
CommandLine.UseDefaultConverter
Converter that can be used to signal to picocli that it should use the default converter.
|
Modifier and Type | Field and Description |
---|---|
static String |
VERSION
This is picocli version "4.7.6".
|
Constructor and Description |
---|
CommandLine(Object command)
Constructs a new
CommandLine interpreter with the specified object (which may be an annotated user object or a CommandSpec ) and a default factory. |
CommandLine(Object command,
CommandLine.IFactory factory)
Constructs a new
CommandLine interpreter with the specified object (which may be an annotated user object or a CommandSpec ) and object factory. |
Modifier and Type | Method and Description |
---|---|
CommandLine |
addMixin(String name,
Object mixin)
Adds the options and positional parameters in the specified mixin to this command.
|
CommandLine |
addSubcommand(Object command)
Registers a subcommand with the name obtained from the
@Command(name = "...") annotation attribute of the specified command. |
CommandLine |
addSubcommand(String name,
Object command)
Registers a subcommand with the specified name.
|
CommandLine |
addSubcommand(String name,
Object command,
String... aliases)
Registers a subcommand with the specified name and all specified aliases.
|
static <C extends Callable<T>,T> |
call(Class<C> callableClass,
CommandLine.IFactory factory,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(Class<C> callableClass,
CommandLine.IFactory factory,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(Class<C> callableClass,
CommandLine.IFactory factory,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(Class<C> callableClass,
CommandLine.IFactory factory,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(C callable,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(C callable,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(C callable,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <C extends Callable<T>,T> |
call(C callable,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
void |
clearExecutionResults()
Clears the execution result of a previous invocation from this
CommandLine and all subcommands. |
static CommandLine.DefaultExceptionHandler<List<Object>> |
defaultExceptionHandler()
Convenience method that returns
new DefaultExceptionHandler<List<Object>>() . |
static CommandLine.IFactory |
defaultFactory()
Returns the default
CommandLine.IFactory implementation used if no factory was specified in the CommandLine constructor . |
int |
execute(String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application.
|
static Integer |
executeHelpRequest(CommandLine.ParseResult parseResult)
Helper method that may be useful when processing the
ParseResult that results from successfully
parsing command line arguments. |
Character |
getAtFileCommentChar()
Returns the character that starts a single-line comment or
null if all content of argument files should
be interpreted as arguments (without comments). |
CommandLine.Help.ColorScheme |
getColorScheme()
Returns the color scheme to use when printing help.
|
<T> T |
getCommand()
Returns the annotated user object that this
CommandLine instance was constructed with. |
static List<Method> |
getCommandMethods(Class<?> cls,
String methodName)
Helper to get methods of a class annotated with
@Command via reflection, optionally filtered by method name (not @Command.name ). |
String |
getCommandName()
Returns the command name (also called program name) displayed in the usage help synopsis.
|
CommandLine.Model.CommandSpec |
getCommandSpec()
Returns the
CommandSpec model that this CommandLine was constructed with. |
CommandLine.IDefaultValueProvider |
getDefaultValueProvider()
Returns the default value provider for the command, or
null if none has been set. |
String |
getEndOfOptionsDelimiter()
Returns the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
|
PrintWriter |
getErr()
Returns the writer to use when printing diagnostic (error) messages during command execution.
|
CommandLine.IExecutionExceptionHandler |
getExecutionExceptionHandler()
Returns the handler for dealing with exceptions that occurred in the
Callable , Runnable or Method
user object of a command when the command was executed. |
<T> T |
getExecutionResult()
Returns the result of calling the user object
Callable or invoking the user object Method
after parsing the user input, or null if this command has not been executed
or if this CommandLine is for a subcommand that was not specified by the end user on the command line. |
CommandLine.IExecutionStrategy |
getExecutionStrategy()
Returns the execution strategy used by the
execute method to invoke
the business logic on the user objects of this command and/or the user-specified subcommand(s). |
CommandLine.IExitCodeExceptionMapper |
getExitCodeExceptionMapper()
Returns the mapper that was set by the application to map from exceptions to exit codes, for use by the
execute method. |
CommandLine.IFactory |
getFactory()
Returns the factory that this
CommandLine was constructed with. |
CommandLine.Help |
getHelp()
Returns a new
Help object created by the IHelpFactory with the CommandSpec and ColorScheme of this command. |
CommandLine.IHelpFactory |
getHelpFactory()
Returns the
IHelpFactory that is used to construct the usage help message. |
List<String> |
getHelpSectionKeys()
Returns the section keys in the order that the usage help message should render the sections.
|
Map<String,CommandLine.IHelpSectionRenderer> |
getHelpSectionMap()
Returns the map of section keys and renderers used to construct the usage help message.
|
Map<String,Object> |
getMixins()
Returns a map of user objects whose options and positional parameters were added to ("mixed in" with) this command.
|
CommandLine.INegatableOptionTransformer |
getNegatableOptionTransformer()
Returns the
INegatableOptionTransformer used to create the negative form of negatable options. |
PrintWriter |
getOut()
Returns the writer used when printing user-requested usage help or version help during command execution.
|
CommandLine.IParameterExceptionHandler |
getParameterExceptionHandler()
Returns the handler for dealing with invalid user input when the command is executed.
|
CommandLine |
getParent()
Returns the command that this is a subcommand of, or
null if this is a top-level command. |
CommandLine.ParseResult |
getParseResult() |
ResourceBundle |
getResourceBundle()
Returns the ResourceBundle of this command or
null if no resource bundle is set. |
String |
getSeparator()
Returns the String that separates option names from option values when parsing command line options.
|
Map<String,CommandLine> |
getSubcommands()
Returns a map with the subcommands registered on this instance.
|
List<String> |
getUnmatchedArguments()
Returns the list of unmatched command line arguments, if any.
|
int |
getUsageHelpLongOptionsMaxWidth()
Returns the maximum usage help long options column max width to the specified value.
|
int |
getUsageHelpWidth()
Returns the maximum width of the usage help message.
|
String |
getUsageMessage()
Similar to
usage(PrintStream) , but returns the usage help message as a String instead of printing it to the PrintStream . |
String |
getUsageMessage(CommandLine.Help.Ansi ansi)
Similar to
usage(PrintStream, Help.Ansi) , but returns the usage help message as a String instead of printing it to the PrintStream . |
String |
getUsageMessage(CommandLine.Help.ColorScheme colorScheme)
Similar to
usage(PrintStream, Help.ColorScheme) , but returns the usage help message as a String instead of printing it to the PrintStream . |
static Object |
invoke(String methodName,
Class<?> cls,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static Object |
invoke(String methodName,
Class<?> cls,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static Object |
invoke(String methodName,
Class<?> cls,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static Object |
invoke(String methodName,
Class<?> cls,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
boolean |
isAbbreviatedOptionsAllowed()
Returns whether abbreviation of option names should be allowed when matching options.
|
boolean |
isAbbreviatedSubcommandsAllowed()
Returns whether abbreviation of subcommands should be allowed when matching subcommands.
|
boolean |
isAdjustLineBreaksForWideCJKCharacters()
Returns whether line breaks should take wide Chinese, Japanese and Korean characters into account for line-breaking purposes.
|
boolean |
isAllowOptionsAsOptionParameters()
Returns whether options can have parameter values that match the name of an option in this command,
or whether such values should be rejected with a missing parameter exception.
|
boolean |
isAllowSubcommandsAsOptionParameters()
Returns whether options can have parameter values that match subcommand names or aliases,
or whether such values should be rejected with a missing parameter exception.
|
boolean |
isCaseInsensitiveEnumValuesAllowed()
Returns whether the parser should ignore case when converting arguments to
enum values. |
boolean |
isExpandAtFiles()
Returns whether arguments starting with
'@' should be treated as the path to an argument file and its
contents should be expanded into separate arguments for each line in the specified file. |
boolean |
isInterpolateVariables()
Returns whether variables should be interpolated in String values.
|
boolean |
isOptionsCaseInsensitive()
Returns whether upper case and lower case should be ignored when matching option names.
|
boolean |
isOverwrittenOptionsAllowed()
Returns whether options for single-value fields can be specified multiple times on the command line.
|
boolean |
isPosixClusteredShortOptionsAllowed()
Returns whether the parser accepts clustered short options.
|
boolean |
isSplitQuotedStrings()
Deprecated.
Most applications should not change the default. The rare application that does need to split parameter values
without respecting quotes should use
CommandLine.Model.ParserSpec.splitQuotedStrings(boolean) . |
boolean |
isStopAtPositional()
Returns whether the parser interprets the first positional parameter as "end of options" so the remaining
arguments are all treated as positional parameters.
|
boolean |
isStopAtUnmatched()
Returns whether the parser should stop interpreting options and positional parameters as soon as it encounters an
unmatched option.
|
boolean |
isSubcommandsCaseInsensitive()
Returns whether upper case and lower case should be ignored when matching subcommands.
|
boolean |
isToggleBooleanFlags()
Returns whether the value of boolean flag options should be "toggled" when the option is matched.
|
boolean |
isTrimQuotes()
Returns whether the parser should trim quotes from command line arguments.
|
boolean |
isUnmatchedArgumentsAllowed()
Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.
|
boolean |
isUnmatchedOptionsAllowedAsOptionParameters()
Returns whether options can have parameter values that resemble an option, or whether such values should be rejected as unknown options.
|
boolean |
isUnmatchedOptionsArePositionalParams()
Returns whether arguments on the command line that resemble an option should be treated as positional parameters.
|
boolean |
isUsageHelpAutoWidth()
Returns whether picocli should attempt to detect the terminal size and adjust the usage help message width
to take the full terminal width.
|
boolean |
isUsageHelpRequested()
Returns
true if an option annotated with CommandLine.Option.usageHelp() was specified on the command line. |
boolean |
isUseSimplifiedAtFiles()
Returns whether to use a simplified argument file format that is compatible with JCommander.
|
boolean |
isVersionHelpRequested()
Returns
true if an option annotated with CommandLine.Option.versionHelp() was specified on the command line. |
List<CommandLine> |
parse(String... args)
Deprecated.
use
parseArgs(String...) instead |
CommandLine.ParseResult |
parseArgs(String... args)
Expands any @-files in the specified command line arguments, then
parses the arguments and returns a
ParseResult with the options, positional
parameters, and subcommands (if any) that were recognized and initialized during the parsing process. |
<R> R |
parseWithHandler(CommandLine.IParseResultHandler2<R> handler,
String[] args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
List<Object> |
parseWithHandler(CommandLine.IParseResultHandler handler,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
<R> R |
parseWithHandlers(CommandLine.IParseResultHandler2<R> handler,
CommandLine.IExceptionHandler2<R> exceptionHandler,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
List<Object> |
parseWithHandlers(CommandLine.IParseResultHandler handler,
PrintStream out,
CommandLine.Help.Ansi ansi,
CommandLine.IExceptionHandler exceptionHandler,
String... args)
Deprecated.
use
execute(String...) and getExecutionResult() instead |
static <T> T |
populateCommand(T command,
String... args)
Convenience method that initializes the specified annotated object from the specified command line arguments.
|
static <T> T |
populateSpec(Class<T> spec,
String... args)
Convenience method that derives the command specification from the specified interface class, and returns an
instance of the specified interface.
|
static boolean |
printHelpIfRequested(CommandLine.ParseResult parseResult)
Delegates to
executeHelpRequest(ParseResult) . |
static boolean |
printHelpIfRequested(List<CommandLine> parsedCommands,
PrintStream out,
CommandLine.Help.Ansi ansi)
Deprecated.
use
printHelpIfRequested(ParseResult) instead |
static boolean |
printHelpIfRequested(List<CommandLine> parsedCommands,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi)
Deprecated.
use
executeHelpRequest(ParseResult) instead |
static boolean |
printHelpIfRequested(List<CommandLine> parsedCommands,
PrintStream out,
PrintStream err,
CommandLine.Help.ColorScheme colorScheme)
Deprecated.
use
executeHelpRequest(ParseResult) instead |
void |
printVersionHelp(PrintStream out)
Delegates to
printVersionHelp(PrintStream, Help.Ansi) with the ANSI setting of the configured color scheme. |
void |
printVersionHelp(PrintStream out,
CommandLine.Help.Ansi ansi)
Prints version information from the
CommandLine.Command.version() annotation to the specified PrintStream . |
void |
printVersionHelp(PrintStream out,
CommandLine.Help.Ansi ansi,
Object... params)
Prints version information from the
CommandLine.Command.version() annotation to the specified PrintStream . |
void |
printVersionHelp(PrintWriter out)
Delegates to
printVersionHelp(PrintWriter, Help.Ansi, Object...) with the ANSI setting of the configured color scheme. |
void |
printVersionHelp(PrintWriter out,
CommandLine.Help.Ansi ansi,
Object... params)
Prints version information from the
CommandLine.Command.version() annotation to the specified PrintWriter . |
<K> CommandLine |
registerConverter(Class<K> cls,
CommandLine.ITypeConverter<K> converter)
Registers the specified type converter for the specified class.
|
static <R extends Runnable> |
run(Class<R> runnableClass,
CommandLine.IFactory factory,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(Class<R> runnableClass,
CommandLine.IFactory factory,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(Class<R> runnableClass,
CommandLine.IFactory factory,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(Class<R> runnableClass,
CommandLine.IFactory factory,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(R runnable,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(R runnable,
PrintStream out,
PrintStream err,
CommandLine.Help.Ansi ansi,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(R runnable,
PrintStream out,
String... args)
Deprecated.
use
execute(String...) instead |
static <R extends Runnable> |
run(R runnable,
String... args)
Deprecated.
use
execute(String...) instead |
CommandLine |
setAbbreviatedOptionsAllowed(boolean newValue)
Sets whether abbreviated option names should be matched.
|
CommandLine |
setAbbreviatedSubcommandsAllowed(boolean newValue)
Sets whether abbreviated subcommands should be matched.
|
CommandLine |
setAdjustLineBreaksForWideCJKCharacters(boolean adjustForWideChars)
Sets whether line breaks should take wide Chinese, Japanese and Korean characters into account, and returns this UsageMessageSpec.
|
CommandLine |
setAllowOptionsAsOptionParameters(boolean newValue)
Sets whether options can have parameter values that match the name of an option in this command, or whether such values should be rejected with a missing parameter exception.
|
CommandLine |
setAllowSubcommandsAsOptionParameters(boolean newValue)
Sets whether options can have parameter values that match subcommand names or aliases, or whether such values should be rejected with a missing parameter exception.
|
CommandLine |
setAtFileCommentChar(Character atFileCommentChar)
Sets the character that starts a single-line comment or
null if all content of argument files should
be interpreted as arguments (without comments). |
CommandLine |
setCaseInsensitiveEnumValuesAllowed(boolean newValue)
Sets whether the parser should ignore case when converting arguments to
enum values. |
CommandLine |
setColorScheme(CommandLine.Help.ColorScheme colorScheme)
Sets the color scheme to use when printing help.
|
CommandLine |
setCommandName(String commandName)
Sets the command name (also called program name) displayed in the usage help synopsis to the specified value.
|
CommandLine |
setDefaultValueProvider(CommandLine.IDefaultValueProvider newValue)
Sets a default value provider for the command and sub-commands
|
CommandLine |
setEndOfOptionsDelimiter(String delimiter)
Sets the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
|
CommandLine |
setErr(PrintWriter err)
Sets the writer to use when printing diagnostic (error) messages during command execution.
|
CommandLine |
setExecutionExceptionHandler(CommandLine.IExecutionExceptionHandler executionExceptionHandler)
Sets a custom handler for dealing with exceptions that occurred in the
Callable , Runnable or Method
user object of a command when the command was executed via the execute method. |
void |
setExecutionResult(Object result)
Sets the result of calling the business logic on the command's user object.
|
CommandLine |
setExecutionStrategy(CommandLine.IExecutionStrategy executionStrategy)
Sets the execution strategy that the
execute method should use to invoke
the business logic on the user objects of this command and/or the user-specified subcommand(s). |
CommandLine |
setExitCodeExceptionMapper(CommandLine.IExitCodeExceptionMapper exitCodeExceptionMapper)
Sets the mapper used by the
execute method to map exceptions to exit codes. |
CommandLine |
setExpandAtFiles(boolean expandAtFiles)
Sets whether arguments starting with
'@' should be treated as the path to an argument file and its
contents should be expanded into separate arguments for each line in the specified file. |
CommandLine |
setHelpFactory(CommandLine.IHelpFactory helpFactory)
Sets a new
IHelpFactory to customize the usage help message. |
CommandLine |
setHelpSectionKeys(List<String> keys)
Sets the section keys in the order that the usage help message should render the sections.
|
CommandLine |
setHelpSectionMap(Map<String,CommandLine.IHelpSectionRenderer> map)
Sets the map of section keys and renderers used to construct the usage help message.
|
CommandLine |
setInterpolateVariables(boolean interpolate)
Sets whether variables should be interpolated in String values.
|
CommandLine |
setNegatableOptionTransformer(CommandLine.INegatableOptionTransformer transformer)
Sets the
INegatableOptionTransformer used to create the negative form of negatable options. |
CommandLine |
setOptionsCaseInsensitive(boolean newValue)
Sets whether upper case and lower case should be ignored when matching option names.
|
CommandLine |
setOut(PrintWriter out)
Sets the writer to use when printing user-requested usage help or version help during command execution.
|
CommandLine |
setOverwrittenOptionsAllowed(boolean newValue)
Sets whether options for single-value fields can be specified multiple times on the command line without a
CommandLine.OverwrittenOptionException being thrown. |
CommandLine |
setParameterExceptionHandler(CommandLine.IParameterExceptionHandler parameterExceptionHandler)
Sets the handler for dealing with invalid user input when the command is executed.
|
CommandLine |
setPosixClusteredShortOptionsAllowed(boolean newValue)
Sets whether short options like
-x -v -f SomeFile can be clustered together like -xvfSomeFile . |
CommandLine |
setResourceBundle(ResourceBundle bundle)
Sets the ResourceBundle containing usage help message strings.
|
CommandLine |
setSeparator(String separator)
Sets the String the parser uses to separate option names from option values to the specified value.
|
CommandLine |
setSplitQuotedStrings(boolean newValue)
Deprecated.
Most applications should not change the default. The rare application that does need to split parameter values
without respecting quotes should use
CommandLine.Model.ParserSpec.splitQuotedStrings(boolean) . |
CommandLine |
setStopAtPositional(boolean newValue)
Sets whether the parser interprets the first positional parameter as "end of options" so the remaining
arguments are all treated as positional parameters.
|
CommandLine |
setStopAtUnmatched(boolean newValue)
Sets whether the parser should stop interpreting options and positional parameters as soon as it encounters an
unmatched option.
|
CommandLine |
setSubcommandsCaseInsensitive(boolean newValue)
Sets whether upper case and lower case should be ignored when matching subcommands.
|
CommandLine |
setToggleBooleanFlags(boolean newValue)
Sets whether the value of boolean flag options should be "toggled" when the option is matched.
|
CommandLine |
setTrimQuotes(boolean newValue)
Sets whether the parser should trim quotes from command line arguments before processing them.
|
CommandLine |
setUnmatchedArgumentsAllowed(boolean newValue)
Sets whether the end user may specify unmatched arguments on the command line without a
CommandLine.UnmatchedArgumentException being thrown. |
CommandLine |
setUnmatchedOptionsAllowedAsOptionParameters(boolean newValue)
Sets whether options can have parameter values that resemble an option, or whether such values should be rejected as unknown options.
|
CommandLine |
setUnmatchedOptionsArePositionalParams(boolean newValue)
Sets whether arguments on the command line that resemble an option should be treated as positional parameters.
|
CommandLine |
setUsageHelpAutoWidth(boolean detectTerminalSize)
Sets whether picocli should attempt to detect the terminal size and adjust the usage help message width
to take the full terminal width.
|
CommandLine |
setUsageHelpLongOptionsMaxWidth(int columnWidth)
Returns the maximum usage help long options column max width to the specified value.
|
CommandLine |
setUsageHelpWidth(int width)
Sets the maximum width of the usage help message.
|
CommandLine |
setUseSimplifiedAtFiles(boolean simplifiedAtFiles)
Sets whether to use a simplified argument file format that is compatible with JCommander.
|
static CommandLine.Tracer |
tracer()
Returns the
Tracer used internally for printing internal debug statements. |
static void |
usage(Object command,
PrintStream out)
Equivalent to
new CommandLine(command).usage(out) . |
static void |
usage(Object command,
PrintStream out,
CommandLine.Help.Ansi ansi)
Equivalent to
new CommandLine(command).usage(out, ansi) . |
static void |
usage(Object command,
PrintStream out,
CommandLine.Help.ColorScheme colorScheme)
Equivalent to
new CommandLine(command).usage(out, colorScheme) . |
void |
usage(PrintStream out)
Delegates to
usage(PrintStream, Help.ColorScheme) with the configured color scheme. |
void |
usage(PrintStream out,
CommandLine.Help.Ansi ansi)
Delegates to
usage(PrintStream, Help.ColorScheme) with the default color scheme. |
void |
usage(PrintStream out,
CommandLine.Help.ColorScheme colorScheme)
Prints a usage help message for the annotated command class to the specified
PrintStream . |
void |
usage(PrintWriter writer)
Delegates to
usage(PrintWriter, Help.ColorScheme) with the configured color scheme. |
void |
usage(PrintWriter writer,
CommandLine.Help.Ansi ansi)
Similar to
usage(PrintStream, Help.Ansi) but with the specified PrintWriter instead of a PrintStream . |
void |
usage(PrintWriter writer,
CommandLine.Help.ColorScheme colorScheme)
Similar to
usage(PrintStream, Help.ColorScheme) , but with the specified PrintWriter instead of a PrintStream . |
public static final String VERSION
public CommandLine(Object command)
CommandLine
interpreter with the specified object (which may be an annotated user object or a CommandSpec
) and a default factory.
The specified object may be a CommandSpec
object, or it may be a @Command
-annotated
user object with @Option
and @Parameters
-annotated fields and methods, in which case picocli automatically
constructs a CommandSpec
from this user object.
If the specified command object is an interface Class
with @Option
and @Parameters
-annotated methods,
picocli creates a Proxy
whose methods return the matched command line values.
If the specified command object is a concrete Class
, picocli delegates to the default factory to get an instance.
If the specified object implements Runnable
or Callable
, or if it is a Method
object,
the command can be run as an application in a single line of code by using the
execute
method to omit some boilerplate code for handling help requests and invalid input.
See getCommandMethods
for a convenient way to obtain a command Method
.
When the parseArgs(String...)
method is called, the CommandSpec
object will be
initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
user object will be initialized based on the command line arguments.
command
- an annotated user object or a CommandSpec
object to initialize from the command line argumentsCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic CommandLine(Object command, CommandLine.IFactory factory)
CommandLine
interpreter with the specified object (which may be an annotated user object or a CommandSpec
) and object factory.
The specified object may be a CommandSpec
object, or it may be a @Command
-annotated
user object with @Option
and @Parameters
-annotated fields and methods, in which case picocli automatically
constructs a CommandSpec
from this user object.
If the specified command object is an interface Class
with @Option
and @Parameters
-annotated methods,
picocli creates a Proxy
whose methods return the matched command line values.
If the specified command object is a concrete Class
, picocli delegates to the factory to get an instance.
If the specified object implements Runnable
or Callable
, or if it is a Method
object,
the command can be run as an application in a single line of code by using the
execute
method to omit some boilerplate code for handling help requests and invalid input.
See getCommandMethods
for a convenient way to obtain a command Method
.
When the parseArgs(String...)
method is called, the CommandSpec
object will be
initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
user object will be initialized based on the command line arguments.
command
- an annotated user object or a CommandSpec
object to initialize from the command line argumentsfactory
- the factory used to create instances of subcommands, converters, etc., that are registered declaratively with annotation attributesCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic CommandLine.Model.CommandSpec getCommandSpec()
CommandSpec
model that this CommandLine
was constructed with.CommandSpec
modelpublic CommandLine addMixin(String name, Object mixin)
The specified object may be a CommandSpec
object, or it may be a user object with
@Option
and @Parameters
-annotated fields, in which case picocli automatically
constructs a CommandSpec
from this user object.
name
- the name by which the mixin object may later be retrievedmixin
- an annotated user object or a CommandSpec
object whose options and positional parameters to add to this commandpublic Map<String,Object> getMixins()
CommandSpec
objects without
user objects were programmatically added, use the underlying model
directly.public CommandLine addSubcommand(Object command)
@Command(name = "...")
annotation attribute of the specified command.command
- the object to initialize with command line arguments following the subcommand name.
This may be a Class
that has a @Command
annotation, or an instance of such a
class, or a CommandSpec
or CommandLine
instance with its own (nested) subcommands.CommandLine.InitializationException
- if no name could be found for the specified subcommand,
or if another subcommand was already registered under the same name, or if one of the aliases
of the specified subcommand was already used by another subcommand.addSubcommand(String, Object)
public CommandLine addSubcommand(String name, Object command)
CommandLine commandLine = new CommandLine(new Git()) .addSubcommand("status", new GitStatus()) .addSubcommand("commit", new GitCommit(); .addSubcommand("add", new GitAdd()) .addSubcommand("branch", new GitBranch()) .addSubcommand("checkout", new GitCheckout()) //... ;
The specified object can be an annotated object or a
CommandLine
instance with its own nested subcommands. For example:
CommandLine commandLine = new CommandLine(new MainCommand()) .addSubcommand("cmd1", new ChildCommand1()) // subcommand .addSubcommand("cmd2", new ChildCommand2()) .addSubcommand("cmd3", new CommandLine(new ChildCommand3()) // subcommand with nested sub-subcommands .addSubcommand("cmd3sub1", new GrandChild3Command1()) .addSubcommand("cmd3sub2", new GrandChild3Command2()) .addSubcommand("cmd3sub3", new CommandLine(new GrandChild3Command3()) // deeper nesting .addSubcommand("cmd3sub3sub1", new GreatGrandChild3Command3_1()) .addSubcommand("cmd3sub3sub2", new GreatGrandChild3Command3_2()) ) );
The default type converters are available on all subcommands and nested sub-subcommands, but custom type converters are registered only with the subcommand hierarchy as it existed when the custom type was registered. To ensure a custom type converter is available to all subcommands, register the type converter last, after adding subcommands.
See also the CommandLine.Command.subcommands()
annotation to register subcommands declaratively.
name
- the string to recognize on the command line as a subcommand.
If null
, the name of the specified subcommand is used;
if this is also null
, the first alias is used.command
- the object to initialize with command line arguments following the subcommand name.
This may be a Class
that has a @Command
annotation, or an instance of such a
class, or a CommandSpec
or CommandLine
instance with its own (nested) subcommands.CommandLine.InitializationException
- if the specified name is null
, and no alternative name could be found,
or if another subcommand was already registered under the same name, or if one of the aliases
of the specified subcommand was already used by another subcommand.registerConverter(Class, ITypeConverter)
,
CommandLine.Command.subcommands()
public CommandLine addSubcommand(String name, Object command, String... aliases)
addSubcommand(String, Object)
.name
- the string to recognize on the command line as a subcommand.
If null
, the name of the specified subcommand is used;
if this is also null
, the first alias is used.command
- the object to initialize with command line arguments following the subcommand name.
This may be a Class
that has a @Command
annotation, or an instance of such a
class, or a CommandSpec
or CommandLine
instance with its own (nested) subcommands.aliases
- zero or more alias names that are also recognized on the command line as this subcommandCommandLine.InitializationException
- if the specified name is null
, and no alternative name could be found,
or if another subcommand was already registered under the same name, or if one of the aliases
of the specified subcommand was already used by another subcommand.addSubcommand(String, Object)
public Map<String,CommandLine> getSubcommands()
public CommandLine getParent()
null
if this is a top-level command.null
if this is a top-level commandaddSubcommand(String, Object)
,
CommandLine.Command.subcommands()
public <T> T getCommand()
CommandLine
instance was constructed with.T
- the type of the variable that the return value is being assigned toCommandLine
instance was constructed withpublic CommandLine.IFactory getFactory()
CommandLine
was constructed with.CommandLine
was constructed with, never null
public boolean isUsageHelpRequested()
true
if an option annotated with CommandLine.Option.usageHelp()
was specified on the command line.CommandLine.Option.usageHelp()
.public boolean isVersionHelpRequested()
true
if an option annotated with CommandLine.Option.versionHelp()
was specified on the command line.CommandLine.Option.versionHelp()
.public CommandLine.Help getHelp()
Help
object created by the IHelpFactory
with the CommandSpec
and ColorScheme
of this command.Help#Help(CommandSpec, Help.ColorScheme)
,
getHelpFactory()
,
getCommandSpec()
,
getColorScheme()
public CommandLine.IHelpFactory getHelpFactory()
IHelpFactory
that is used to construct the usage help message.setHelpFactory(IHelpFactory)
public CommandLine setHelpFactory(CommandLine.IHelpFactory helpFactory)
IHelpFactory
to customize the usage help message.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
helpFactory
- the new help factory. Must be non-null
.CommandLine
object, to allow method chainingpublic List<String> getHelpSectionKeys()
setSectionKeys
. The default keys are (in order):
SECTION_KEY_HEADER_HEADING
SECTION_KEY_HEADER
SECTION_KEY_SYNOPSIS_HEADING
SECTION_KEY_SYNOPSIS
SECTION_KEY_DESCRIPTION_HEADING
SECTION_KEY_DESCRIPTION
SECTION_KEY_PARAMETER_LIST_HEADING
SECTION_KEY_AT_FILE_PARAMETER
SECTION_KEY_PARAMETER_LIST
SECTION_KEY_OPTION_LIST_HEADING
SECTION_KEY_OPTION_LIST
SECTION_KEY_COMMAND_LIST_HEADING
SECTION_KEY_COMMAND_LIST
SECTION_KEY_EXIT_CODE_LIST_HEADING
SECTION_KEY_EXIT_CODE_LIST
SECTION_KEY_FOOTER_HEADING
SECTION_KEY_FOOTER
public CommandLine setHelpSectionKeys(List<String> keys)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
Use CommandLine.Model.UsageMessageSpec.sectionKeys(List)
to customize a command without affecting its subcommands.
getHelpSectionKeys()
public Map<String,CommandLine.IHelpSectionRenderer> getHelpSectionMap()
setSectionKeys
.
Sections that are either not in this map or not in the list returned by getSectionKeys
are omitted.
NOTE: By modifying the returned Map
, only the usage help message of this command is affected.
Use setHelpSectionMap(Map)
to customize the usage help message for this command and all subcommands.
public CommandLine setHelpSectionMap(Map<String,CommandLine.IHelpSectionRenderer> map)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
Use CommandLine.Model.UsageMessageSpec.sectionMap(Map)
to customize a command without affecting its subcommands.
getHelpSectionMap()
public boolean isAdjustLineBreaksForWideCJKCharacters()
true
.public CommandLine setAdjustLineBreaksForWideCJKCharacters(boolean adjustForWideChars)
true
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
adjustForWideChars
- if true, wide Chinese, Japanese and Korean characters are counted as double the size of other characters for line-breaking purposespublic boolean isToggleBooleanFlags()
false
by default, and when a flag option is specified on the command line picocli
will set its value to the opposite of its default value.
If this method returns true
, flags are toggled, so if the value is true
it is
set to false
, and when the value is false
it is set to true
.
When toggling is enabled, specifying a flag option twice on the command line will have no effect because they cancel each other out.true
the value of boolean flag options should be "toggled" when the option is matched, false
otherwisepublic CommandLine setToggleBooleanFlags(boolean newValue)
false
,
and when a flag option is specified on the command line picocli will set its value to the opposite of its default value.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isInterpolateVariables()
true
.public CommandLine setInterpolateVariables(boolean interpolate)
true
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
public boolean isOverwrittenOptionsAllowed()
false
and a CommandLine.OverwrittenOptionException
is thrown if this happens.
When true
, the last specified value is retained.true
if options for single-value fields can be specified multiple times on the command line, false
otherwisepublic CommandLine setOverwrittenOptionsAllowed(boolean newValue)
CommandLine.OverwrittenOptionException
being thrown.
The default is false
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isPosixClusteredShortOptionsAllowed()
true
.true
if short options like -x -v -f SomeFile
can be clustered together like -xvfSomeFile
, false
otherwisepublic CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue)
-x -v -f SomeFile
can be clustered together like -xvfSomeFile
. The default is true
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isCaseInsensitiveEnumValuesAllowed()
enum
values. The default is false
.true
if enum values can be specified that don't match the toString()
value of the enum constant, false
otherwise;
e.g., for an option of type java.time.DayOfWeek,
values MonDaY
, monday
and MONDAY
are all recognized if true
.public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue)
enum
values. The default is false
.
When set to true, for example, for an option of type java.time.DayOfWeek,
values MonDaY
, monday
and MONDAY
are all recognized if true
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isTrimQuotes()
true
if the property is present and empty,
or if its value is "true".
If this property is set to true
, the parser will remove quotes from the command line arguments, as follows:
split
regular expression inside
a quoted region should be ignored, so arguments like "a,b","x,y"
are handled correctly.
For arguments with nested quotes, quotes are removed later in the processing pipeline, after split
operations are applied.true
if the parser should trim quotes from command line arguments before processing them, false
otherwise;CommandLine.Model.ParserSpec.trimQuotes()
public CommandLine setTrimQuotes(boolean newValue)
true
if the property is set and empty, or
if its value is "true".
If this property is set to true
, the parser will remove quotes from the command line arguments, as follows:
split
regular expression inside
a quoted region should be ignored, so arguments like "a,b","x,y"
are handled correctly.
For arguments with nested quotes, quotes are removed later in the processing pipeline, after split
operations are applied.The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
Calling this method will cause the "picocli.trimQuotes" property to have no effect.
newValue
- the new settingCommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.trimQuotes(boolean)
@Deprecated public boolean isSplitQuotedStrings()
CommandLine.Model.ParserSpec.splitQuotedStrings(boolean)
.false
,
so quotes are respected: quoted strings are treated as a single value that should not be broken up.
For example, take a single command line parameter "a,b","x,y"
. With a comma split regex, the default of splitQuotedStrings = false
means that this value will be split into two strings: "a,b"
and "x,y"
. This is usually what you want.
If splitQuotedStrings
is set to true
, quotes are not respected, and the value is split up into four parts:
the first is "a
, the second is b"
, the third is "x
, and the last part is y"
. This is generally not what you want.
true
if the parser is allowed to split quoted Strings, false
otherwise;CommandLine.Model.ArgSpec.splitRegex()
,
CommandLine.Model.ParserSpec.splitQuotedStrings()
@Deprecated public CommandLine setSplitQuotedStrings(boolean newValue)
CommandLine.Model.ParserSpec.splitQuotedStrings(boolean)
.false
,
so quotes are respected: quoted strings are treated as a single value that should not be broken up.
For example, take a single command line parameter "a,b","x,y"
. With a comma split regex, the default of splitQuotedStrings = false
means that this value will be split into two strings: "a,b"
and "x,y"
. This is usually what you want.
However, if splitQuotedStrings
is set to true
, quotes are not respected, and the value is split up into four parts:
the first is "a
, the second is b"
, the third is "x
, and the last part is y"
. This is generally not what you want.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingCommandLine.Model.ArgSpec.splitRegex()
,
CommandLine.Model.ParserSpec.splitQuotedStrings(boolean)
public String getEndOfOptionsDelimiter()
"--"
.public CommandLine setEndOfOptionsDelimiter(String delimiter)
delimiter
- the end-of-options delimiter; must not be null
. The default is "--"
.CommandLine
object, to allow method chainingpublic boolean isSubcommandsCaseInsensitive()
false
.true
if subcommands can be matched when they differ only in case from the getCommandName()
value of a registered one, false
otherwise.
For example, if true, for a subcommand with name help
, inputs like help
, HeLp
and HELP
are all recognized.public CommandLine setSubcommandsCaseInsensitive(boolean newValue)
false
.
For example, when set to true
, for a subcommand with name help
, inputs like help
, HeLp
and HELP
are all recognized.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isOptionsCaseInsensitive()
false
.true
if options can be matched when they differ only in case from the names()
value of a registered one, false
otherwise;
For example, if true, for an option with name -h
, inputs like -h
, -H
are both recognized.public CommandLine setOptionsCaseInsensitive(boolean newValue)
false
.
For example, when set to true
, for an option with name -h
, inputs like -h
, -H
are both recognized.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
CommandLine.INegatableOptionTransformer
that was previously installed will be replaced by the case-insensitive
version of the default transformer. To ensure your custom transformer is used, install it last, after changing case sensitivity.newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isAbbreviatedSubcommandsAllowed()
false
.true
if subcommands can be matched when they are abbreviations of the getCommandName()
value of a registered one, false
otherwise.
For example, if true, for a subcommand with name helpCommand
, inputs like h
, h-c
and hC
are all recognized.public CommandLine setAbbreviatedSubcommandsAllowed(boolean newValue)
false
.
For example, when set to true
, for a subcommand helpCommand
, inputs like h
, h-c
and hC
are all recognized.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isAbbreviatedOptionsAllowed()
false
.true
if options can be matched when they are abbreviations of the names()
value of a registered one, false
otherwise.
For example, if true, for a subcommand with name --helpMe
, inputs like --h
, --h-m
and --hM
are all recognized.public CommandLine setAbbreviatedOptionsAllowed(boolean newValue)
false
.
For example, when set to true
, for an option with name --helpMe
, inputs like --h
, --h-m
and --hM
are all recognized.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic CommandLine.IDefaultValueProvider getDefaultValueProvider()
null
if none has been set.null
CommandLine.Command.defaultValueProvider()
,
CommandLine.Model.CommandSpec.defaultValueProvider()
,
CommandLine.Model.ArgSpec.defaultValueString()
public CommandLine setDefaultValueProvider(CommandLine.IDefaultValueProvider newValue)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
sub-commands and nested sub-subcommands at the moment this method is called. Sub-commands added
later will have the default setting. To ensure a setting is applied to all
sub-commands, call the setter last, after adding sub-commands.
newValue
- the default value provider to useCommandLine
object, to allow method chainingpublic boolean isStopAtPositional()
false
.true
if all values following the first positional parameter should be treated as positional parameters, false
otherwisepublic CommandLine setStopAtPositional(boolean newValue)
false
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- true
if all values following the first positional parameter should be treated as positional parameters, false
otherwiseCommandLine
object, to allow method chainingpublic boolean isStopAtUnmatched()
false
.
Setting this flag to true
automatically sets the unmatchedArgumentsAllowed flag to true
also.
true
when an unmatched option should result in the remaining command line arguments to be added to the
unmatchedArguments listpublic CommandLine setStopAtUnmatched(boolean newValue)
false
.
Setting this flag to true
automatically sets the unmatchedArgumentsAllowed flag to true
also.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- true
when an unmatched option should result in the remaining command line arguments to be added to the
unmatchedArguments listCommandLine
object, to allow method chainingpublic boolean isAllowSubcommandsAsOptionParameters()
false
, so by default input like -x=subcommand
is rejected if -x
is an option that takes a String parameter, and subcommand
is a subcommand of this command.true
when options can have parameter values that match subcommand names or aliases, false
when such values should be rejected with a missing parameter exceptionCommandLine.Model.ParserSpec.allowSubcommandsAsOptionParameters()
public CommandLine setAllowSubcommandsAsOptionParameters(boolean newValue)
false
, so by default
input like -x=subcommand
is rejected if -x
is an option that takes a String parameter, and subcommand
is a subcommand of this command.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new setting. When true
, options can have parameter values that match subcommand names or aliases, when false
, such values are rejected with a missing parameter exceptionCommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.allowSubcommandsAsOptionParameters(boolean)
public boolean isAllowOptionsAsOptionParameters()
false
, so by default input like -x=--some-option
is rejected if -x
is an option that takes a String parameter, and --some-option
is an option of this command.
This method only considers actual options of this command, as opposed to isUnmatchedOptionsAllowedAsOptionParameters()
, which considers values that resemble options.
true
when options can have parameter values that match the name of an option in this command, false
when such values should be rejected with a missing parameter exceptionisUnmatchedOptionsAllowedAsOptionParameters()
,
CommandLine.Model.ParserSpec.allowOptionsAsOptionParameters()
public CommandLine setAllowOptionsAsOptionParameters(boolean newValue)
false
, so by default
input like -x=--some-option
is rejected if -x
is an option that takes a String parameter, and --some-option
is an option of this command.
This method only considers actual options of this command, as opposed to setUnmatchedOptionsAllowedAsOptionParameters(boolean)
, which considers values that resemble options.
Use with caution! When set to true
, any option in the command will consume the maximum number of arguments possible for its arity.
This means that an option with arity = "*"
will consume all command line arguments following that option.
If this is not what you want, consider custom parameter processing.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new setting. When true
, options can have parameter values that match the name of an option in this command, when false
, such values are rejected with a missing parameter exceptionCommandLine
object, to allow method chainingsetUnmatchedOptionsAllowedAsOptionParameters(boolean)
,
CommandLine.Model.ParserSpec.allowOptionsAsOptionParameters(boolean)
public boolean isUnmatchedOptionsAllowedAsOptionParameters()
true
, so by default input like -x=-unknown
is accepted if -x
is an option that takes a String parameter.
This method only considers values that resemble options, as opposed to isAllowOptionsAsOptionParameters()
, which considers actual options of this command.
true
when options can have parameter values that resemble an option, false
when such values should be rejected as unknown optionsisAllowOptionsAsOptionParameters()
,
CommandLine.Model.ParserSpec.unmatchedOptionsAllowedAsOptionParameters()
public CommandLine setUnmatchedOptionsAllowedAsOptionParameters(boolean newValue)
true
, so by default
input like -x=-unknown
is accepted if -x
is an option that takes a String parameter.
This method only considers values that resemble options, as opposed to setAllowOptionsAsOptionParameters(boolean)
, which considers actual options of this command.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new setting. When true
, options can have parameter values that resemble an option, when false
, such values are rejected as unknown optionsCommandLine
object, to allow method chainingsetAllowOptionsAsOptionParameters(boolean)
,
CommandLine.Model.ParserSpec.unmatchedOptionsAllowedAsOptionParameters(boolean)
public boolean isUnmatchedOptionsArePositionalParams()
false
and the parser behaviour depends on isUnmatchedArgumentsAllowed()
.true
arguments on the command line that resemble an option should be treated as positional parameters, false
otherwisegetUnmatchedArguments()
public CommandLine setUnmatchedOptionsArePositionalParams(boolean newValue)
false
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new setting. When true
, arguments on the command line that resemble an option should be treated as positional parameters.CommandLine
object, to allow method chaininggetUnmatchedArguments()
,
isUnmatchedArgumentsAllowed()
public boolean isUnmatchedArgumentsAllowed()
false
and a CommandLine.UnmatchedArgumentException
is thrown if this happens.
When true
, the last unmatched arguments are available via the getUnmatchedArguments()
method.true
if the end use may specify unmatched arguments on the command line, false
otherwisegetUnmatchedArguments()
public CommandLine setUnmatchedArgumentsAllowed(boolean newValue)
CommandLine.UnmatchedArgumentException
being thrown.
The default is false
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new setting. When true
, the last unmatched arguments are available via the getUnmatchedArguments()
method.CommandLine
object, to allow method chaininggetUnmatchedArguments()
public List<String> getUnmatchedArguments()
isUnmatchedArgumentsAllowed()
public CommandLine.Help.ColorScheme getColorScheme()
Ansi.AUTO
.public CommandLine setColorScheme(CommandLine.Help.ColorScheme colorScheme)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
colorScheme
- the new color schemeexecute(String...)
,
usage(PrintStream)
,
usage(PrintWriter)
,
getUsageMessage()
public PrintWriter getOut()
System.out
unless setOut(PrintWriter)
was called with a different writer.
This method is used by execute(String...)
. Custom IExecutionStrategy
implementations should also use this writer.
By convention, when the user requests
help with a --help
or similar option, the usage help message is printed to the standard output stream so that it can be easily searched and paged.
public CommandLine setOut(PrintWriter out)
This method is used by execute(String...)
. Custom IExecutionStrategy
implementations should also use this writer.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
out
- the new PrintWriter to usepublic PrintWriter getErr()
System.err
, unless setErr(PrintWriter)
was called with a different writer.
This method is used by execute(String...)
.
IParameterExceptionHandler
and IExecutionExceptionHandler
implementations
should use this writer to print error messages (which may include a usage help message) when an unexpected error occurs.
public CommandLine setErr(PrintWriter err)
This method is used by execute(String...)
.
IParameterExceptionHandler
and IExecutionExceptionHandler
implementations
should use this writer to print error messages (which may include a usage help message) when an unexpected error occurs.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
err
- the new PrintWriter to usepublic CommandLine.IExitCodeExceptionMapper getExitCodeExceptionMapper()
execute
method.null
if none was setpublic CommandLine setExitCodeExceptionMapper(CommandLine.IExitCodeExceptionMapper exitCodeExceptionMapper)
execute
method to map exceptions to exit codes.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
exitCodeExceptionMapper
- the new valuepublic CommandLine.IExecutionStrategy getExecutionStrategy()
execute
method to invoke
the business logic on the user objects of this command and/or the user-specified subcommand(s).
The default value is RunLast
.public CommandLine setExecutionStrategy(CommandLine.IExecutionStrategy executionStrategy)
execute
method should use to invoke
the business logic on the user objects of this command and/or the user-specified subcommand(s).
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
executionStrategy
- the new execution strategy to run the user-specified commandpublic CommandLine.IParameterExceptionHandler getParameterExceptionHandler()
The default implementation prints an error message describing the problem, followed by either suggested alternatives
for mistyped options, or the full usage help message of the problematic command;
it then delegates to the exit code exception mapper for an exit code, with
exitCodeOnInvalidInput
as the default exit code.
Alternatively, you can install a "short error message handler" like this:
static class ShortErrorMessageHandler implements IParameterExceptionHandler { public int handleParseException(ParameterException ex, String[] args) { CommandLine cmd = ex.getCommandLine(); PrintWriter writer = cmd.getErr(); writer.println(ex.getMessage()); UnmatchedArgumentException.printSuggestions(ex, writer); writer.print(cmd.getHelp().fullSynopsis()); CommandSpec spec = cmd.getCommandSpec(); writer.printf("Try '%s --help' for more information.%n", spec.qualifiedName()); return cmd.getExitCodeExceptionMapper() != null ? cmd.getExitCodeExceptionMapper().getExitCode(ex) : spec.exitCodeOnInvalidInput(); } }
Install this error handler like this:
new CommandLine(new MyApp()) .setParameterExceptionHandler(new ShortErrorMessageHandler()) .execute(args);
public CommandLine setParameterExceptionHandler(CommandLine.IParameterExceptionHandler parameterExceptionHandler)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
parameterExceptionHandler
- the new handler for dealing with invalid user inputan example short exception handler
public CommandLine.IExecutionExceptionHandler getExecutionExceptionHandler()
Callable
, Runnable
or Method
user object of a command when the command was executed.
The default implementation rethrows the specified exception.
execute
method was invoked.public CommandLine setExecutionExceptionHandler(CommandLine.IExecutionExceptionHandler executionExceptionHandler)
Callable
, Runnable
or Method
user object of a command when the command was executed via the execute method.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
executionExceptionHandler
- the handler for dealing with exceptions that occurred in the business logic when the execute
method was invoked.public static <T> T populateCommand(T command, String... args)
Convenience method that initializes the specified annotated object from the specified command line arguments.
This is equivalent to
new CommandLine(command).parseArgs(args); return command;
All this method does is parse the arguments and populate the annotated fields and methods.
The caller is responsible for catching any exceptions, handling requests for usage help
or version information, and invoking the business logic.
Applications may be interested in using the execute(String...)
method instead.
T
- the type of the annotated objectcommand
- the object to initialize. This object contains fields annotated with
@Option
or @Parameters
.args
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ParameterException
- if the specified command line arguments are invalidexecute(String...)
public static <T> T populateSpec(Class<T> spec, String... args)
Convenience method that derives the command specification from the specified interface class, and returns an instance of the specified interface. The interface is expected to have annotated getter methods. Picocli will instantiate the interface and the getter methods will return the option and positional parameter values matched on the command line.
This is equivalent to
CommandLine cli = new CommandLine(spec); cli.parse(args); return cli.getCommand();
All this method does is parse the arguments and return an instance whose annotated methods return the specified values.
The caller is responsible for catching any exceptions, handling requests for usage help
or version information, and invoking the business logic.
Applications may be interested in using the execute(String...)
method instead.
T
- the type of the annotated objectspec
- the interface that defines the command specification. This object contains getter methods annotated with
@Option
or @Parameters
.args
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ParameterException
- if the specified command line arguments are invalidexecute(String...)
@Deprecated public List<CommandLine> parse(String... args)
parseArgs(String...)
insteadCommandLine
objects representing the
top-level command and any subcommands (if any) that were recognized and initialized during the parsing process.
If parsing succeeds, the first element in the returned list is always this CommandLine
object. The
returned list may contain more elements if subcommands were registered
and these subcommands were initialized by matching command line arguments. If parsing fails, a
CommandLine.ParameterException
is thrown.
All this method does is parse the arguments and populate the annotated fields and methods.
The caller is responsible for catching any exceptions, handling requests for usage help
or version information, and invoking the business logic.
Applications may be interested in using the execute(String...)
method instead.
args
- the command line arguments to parseCommandLine.ParameterException
- if the specified command line arguments are invalid; use
CommandLine.ParameterException.getCommandLine()
to get the command or subcommand whose user input was invalidpublic CommandLine.ParseResult parseArgs(String... args)
ParseResult
with the options, positional
parameters, and subcommands (if any) that were recognized and initialized during the parsing process.
If parsing fails, a CommandLine.ParameterException
is thrown.
All this method does is parse the arguments and populate the annotated fields and methods.
The caller is responsible for catching any exceptions, handling requests for usage help
or version information, and invoking the business logic.
Applications may be interested in using the execute(String...)
method instead.
args
- the command line arguments to parseCommandLine.ParameterException
- if the specified command line arguments are invalid; use
CommandLine.ParameterException.getCommandLine()
to get the command or subcommand whose user input was invalidexecute(String...)
public CommandLine.ParseResult getParseResult()
public <T> T getExecutionResult()
Callable
or invoking the user object Method
after parsing the user input, or null
if this command has not been executed
or if this CommandLine
is for a subcommand that was not specified by the end user on the command line.
Implementation note:
It is the responsibility of the IExecutionStrategy
to set this value.
T
- type of the result valueCallable
or Method
(may be null
), or null
if this (sub)command was not executedpublic void setExecutionResult(Object result)
result
- the business logic result, may be null
execute(String...)
,
CommandLine.IExecutionStrategy
public void clearExecutionResults()
CommandLine
and all subcommands.public static CommandLine.DefaultExceptionHandler<List<Object>> defaultExceptionHandler()
new DefaultExceptionHandler<List<Object>>()
.@Deprecated public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, CommandLine.Help.Ansi ansi)
printHelpIfRequested(ParseResult)
insteadpublic static boolean printHelpIfRequested(CommandLine.ParseResult parseResult)
executeHelpRequest(ParseResult)
.parseResult
- contains the CommandLine
objects found during parsing; check these to see if help was requestedtrue
if help was printed, false
otherwise@Deprecated public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi)
executeHelpRequest(ParseResult)
insteadexecuteHelpRequest(ParseResult)
.parsedCommands
- the list of CommandLine
objects to check if help was requestedout
- the PrintStream
to print help to if requestederr
- the error string to print diagnostic messages to, in addition to the output from the exception handleransi
- for printing help messages using ANSI styles and colorstrue
if help was printed, false
otherwise@Deprecated public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, CommandLine.Help.ColorScheme colorScheme)
executeHelpRequest(ParseResult)
insteadexecuteHelpRequest(ParseResult)
.parsedCommands
- the list of CommandLine
objects to check if help was requestedout
- the PrintStream
to print help to if requestederr
- the error string to print diagnostic messages to, in addition to the output from the exception handlercolorScheme
- for printing help messages using ANSI styles and colorstrue
if help was printed, false
otherwisepublic static Integer executeHelpRequest(CommandLine.ParseResult parseResult)
ParseResult
that results from successfully
parsing command line arguments. This method prints out
usage help to the configured output writer
if requested or version help
to the configured output writer if requested
and returns CommandLine.Model.CommandSpec.exitCodeOnUsageHelp()
or CommandLine.Model.CommandSpec.exitCodeOnVersionHelp()
, respectively.
If the command is a CommandLine.Command.helpCommand()
and runnable
or callable
,
that command is executed and this method returns CommandLine.Model.CommandSpec.exitCodeOnUsageHelp()
.
Otherwise, if none of the specified CommandLine
objects have help requested,
this method returns null
.
Note that this method only looks at the usageHelp
and
versionHelp
attributes. The help
attribute is ignored.
Implementation note:
When an error occurs while processing the help request, it is recommended custom Help commands throw a
CommandLine.ParameterException
with a reference to the parent command. This will print the error message and the
usage for the parent command, and will use the exit code of the exception handler if one was set.
parseResult
- contains the CommandLine
objects found during parsing; check these to see if help was requestedCommandLine.Model.CommandSpec.exitCodeOnUsageHelp()
if usage help was requested,
CommandLine.Model.CommandSpec.exitCodeOnVersionHelp()
if version help was requested, and null
otherwiseCommandLine.IHelpCommandInitializable2
public int execute(String... args)
CommandLine
is constructed with needs to
either implement Runnable
, Callable
, or be a Method
object.
See getCommandMethods
for a convenient way to obtain a command Method
.
This method replaces the run
, call
and invoke
convenience methods that were available with previous versions of picocli.
Exit Code
This method returns an exit code that applications can use to call System.exit
.
(The return value of the Callable
or Method
can still be obtained via getExecutionResult
.)
If the user object Callable
or Method
returns an int
or Integer
,
this will be used as the exit code. Additionally, if the user object implements IExitCodeGenerator
,
an exit code is obtained by calling its getExitCode()
method (after invoking the user object).
In the case of multiple exit codes the highest value will be used (or if all values are negative, the lowest value will be used).
Exception Handling
This method never throws an exception.
If the user specified invalid input, the parameter exception handler is invoked. By default this prints an error message and the usage help message, and returns an exit code.
If an exception occurred while the user object Runnable
, Callable
, or Method
was invoked, this exception is caught and passed to the execution exception handler.
The default IExecutionExceptionHandler
will rethrow this Exception.
Any exception thrown from the IParameterExceptionHandler
or IExecutionExceptionHandler
is caught,
it stacktrace is printed and is mapped to an exit code, using the following logic:
If an IExitCodeExceptionMapper
is configured,
this mapper is used to determine the exit code based on the exception.
If an IExitCodeExceptionMapper
is not set, by default this method will return the @Command
annotation's
exitCodeOnInvalidInput
or exitCodeOnExecutionException
value, respectively.
Example Usage:
@Command class MyCommand implements Callable<Integer> { public Integer call() { return 123; } } CommandLine cmd = new CommandLine(new MyCommand()); int exitCode = cmd.execute(args); assert exitCode == 123; System.exit(exitCode);
Since execute
is an instance method, not a static method, applications can do configuration before invoking the command. For example:
CommandLine cmd = new CommandLine(new MyCallable())
.setCaseInsensitiveEnumValuesAllowed(true) // configure a non-default parser option
.setOut(myOutWriter()) // configure an alternative to System.out
.setErr(myErrWriter()) // configure an alternative to System.err
.setColorScheme(myColorScheme()); // configure a custom color scheme
int exitCode = cmd.execute(args);
System.exit(exitCode);
If the specified command has subcommands, the last subcommand specified on the command line is executed. This can be configured by setting the execution strategy. Built-in alternatives are executing the first subcommand, or executing all specified subcommands.
args
- the command line arguments to parseCommandLine.ExitCode
,
CommandLine.IExitCodeGenerator
,
getExecutionResult()
,
getExecutionStrategy()
,
getParameterExceptionHandler()
,
getExecutionExceptionHandler()
,
getExitCodeExceptionMapper()
@Deprecated public List<Object> parseWithHandler(CommandLine.IParseResultHandler handler, PrintStream out, String... args)
execute(String...)
and getExecutionResult()
instead@Deprecated public <R> R parseWithHandler(CommandLine.IParseResultHandler2<R> handler, String[] args)
execute(String...)
and getExecutionResult()
insteadparseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
with
a new CommandLine.DefaultExceptionHandler
in addition to the specified parse result handler and the specified command line arguments.
This is a convenience method intended to offer the same ease of use as the run
and call
methods, but with more flexibility and better
support for nested subcommands.
Calling this method roughly expands to:
try {
ParseResult parseResult = parseArgs(args);
return handler.handleParseResult(parseResult);
} catch (ParameterException ex) {
return new DefaultExceptionHandler<R>().handleParseException(ex, args);
}
Picocli provides some default handlers that allow you to accomplish some common tasks with very little code. The following handlers are available:
CommandLine.RunLast
handler prints help if requested, and otherwise gets the last specified command or subcommand
and tries to execute it as a Runnable
or Callable
.CommandLine.RunFirst
handler prints help if requested, and otherwise executes the top-level command as a Runnable
or Callable
.CommandLine.RunAll
handler prints help if requested, and otherwise executes all recognized commands and subcommands as Runnable
or Callable
tasks.CommandLine.DefaultExceptionHandler
prints the error message followed by usage helpR
- the return type of this handlerhandler
- the function that will handle the result of successfully parsing the command line argumentsargs
- the command line argumentsCommandLine.ExecutionException
- if the command line arguments were parsed successfully but a problem occurred while processing the
parse results; use CommandLine.ExecutionException.getCommandLine()
to get the command or subcommand where processing failedCommandLine.RunLast
,
CommandLine.RunAll
@Deprecated public List<Object> parseWithHandlers(CommandLine.IParseResultHandler handler, PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, String... args)
execute(String...)
and getExecutionResult()
instead@Deprecated public <R> R parseWithHandlers(CommandLine.IParseResultHandler2<R> handler, CommandLine.IExceptionHandler2<R> exceptionHandler, String... args)
execute(String...)
and getExecutionResult()
insteadParseResult
object to the specified handler.
If the command line arguments were invalid, the ParameterException
thrown from the parse
method
is caught and passed to the specified CommandLine.IExceptionHandler2
.
This is a convenience method intended to offer the same ease of use as the run
and call
methods, but with more flexibility and better
support for nested subcommands.
Calling this method roughly expands to:
ParseResult parseResult = null; try { parseResult = parseArgs(args); return handler.handleParseResult(parseResult); } catch (ParameterException ex) { return exceptionHandler.handleParseException(ex, (String[]) args); } catch (ExecutionException ex) { return exceptionHandler.handleExecutionException(ex, parseResult); }
Picocli provides some default handlers that allow you to accomplish some common tasks with very little code. The following handlers are available:
CommandLine.RunLast
handler prints help if requested, and otherwise gets the last specified command or subcommand
and tries to execute it as a Runnable
or Callable
.CommandLine.RunFirst
handler prints help if requested, and otherwise executes the top-level command as a Runnable
or Callable
.CommandLine.RunAll
handler prints help if requested, and otherwise executes all recognized commands and subcommands as Runnable
or Callable
tasks.CommandLine.DefaultExceptionHandler
prints the error message followed by usage helpR
- the return type of the result handler and exception handlerhandler
- the function that will handle the result of successfully parsing the command line argumentsexceptionHandler
- the function that can handle the ParameterException
thrown when the command line arguments are invalidargs
- the command line argumentsCommandLine.ExecutionException
- if the command line arguments were parsed successfully but a problem occurred while processing the parse
result ParseResult
object; use CommandLine.ExecutionException.getCommandLine()
to get the command or subcommand where processing failedCommandLine.RunLast
,
CommandLine.RunAll
,
CommandLine.DefaultExceptionHandler
public static void usage(Object command, PrintStream out)
new CommandLine(command).usage(out)
. See usage(PrintStream)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message toIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic static void usage(Object command, PrintStream out, CommandLine.Help.Ansi ansi)
new CommandLine(command).usage(out, ansi)
.
See usage(PrintStream, Help.Ansi)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message toansi
- whether the usage message should contain ANSI escape codes or notIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic static void usage(Object command, PrintStream out, CommandLine.Help.ColorScheme colorScheme)
new CommandLine(command).usage(out, colorScheme)
.
See usage(PrintStream, Help.ColorScheme)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message tocolorScheme
- the ColorScheme
defining the styles for options, parameters and commands when ANSI is enabledIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic void usage(PrintStream out)
usage(PrintStream, Help.ColorScheme)
with the configured color scheme.out
- the printStream to print tousage(PrintStream, Help.ColorScheme)
public void usage(PrintWriter writer)
usage(PrintWriter, Help.ColorScheme)
with the configured color scheme.writer
- the PrintWriter to print tousage(PrintWriter, Help.ColorScheme)
public void usage(PrintStream out, CommandLine.Help.Ansi ansi)
usage(PrintStream, Help.ColorScheme)
with the default color scheme.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notusage(PrintStream, Help.ColorScheme)
public void usage(PrintWriter writer, CommandLine.Help.Ansi ansi)
usage(PrintStream, Help.Ansi)
but with the specified PrintWriter
instead of a PrintStream
.public void usage(PrintStream out, CommandLine.Help.ColorScheme colorScheme)
PrintStream
.
Delegates construction of the usage help message to the CommandLine.Help
inner class and is equivalent to:
Help.ColorScheme colorScheme = Help.defaultColorScheme(Help.Ansi.AUTO); Help help = getHelpFactory().create(getCommandSpec(), colorScheme) StringBuilder sb = new StringBuilder(); for (String key : getHelpSectionKeys()) { IHelpSectionRenderer renderer = getHelpSectionMap().get(key); if (renderer != null) { sb.append(renderer.render(help)); } } out.print(sb);
Annotate your class with CommandLine.Command
to control many aspects of the usage help message, including
the program name, text of section headings and section contents, and some aspects of the auto-generated sections
of the usage help message.
To customize the auto-generated sections of the usage help message, like how option details are displayed,
instantiate a CommandLine.Help
object and use a CommandLine.Help.TextTable
with more of fewer columns, a custom
layout, and/or a custom option renderer
for ultimate control over which aspects of an Option or Field are displayed where.
out
- the PrintStream
to print the usage help message tocolorScheme
- the ColorScheme
defining the styles for options, parameters and commands when ANSI is enabledCommandLine.Model.UsageMessageSpec
public void usage(PrintWriter writer, CommandLine.Help.ColorScheme colorScheme)
usage(PrintStream, Help.ColorScheme)
, but with the specified PrintWriter
instead of a PrintStream
.public String getUsageMessage()
usage(PrintStream)
, but returns the usage help message as a String instead of printing it to the PrintStream
.public String getUsageMessage(CommandLine.Help.Ansi ansi)
usage(PrintStream, Help.Ansi)
, but returns the usage help message as a String instead of printing it to the PrintStream
.public String getUsageMessage(CommandLine.Help.ColorScheme colorScheme)
usage(PrintStream, Help.ColorScheme)
, but returns the usage help message as a String instead of printing it to the PrintStream
.public void printVersionHelp(PrintStream out)
printVersionHelp(PrintStream, Help.Ansi)
with the ANSI setting of the configured color scheme.out
- the printStream to print toprintVersionHelp(PrintStream, Help.Ansi)
public void printVersionHelp(PrintStream out, CommandLine.Help.Ansi ansi)
CommandLine.Command.version()
annotation to the specified PrintStream
.
Each element of the array of version strings is printed on a separate line. Version strings may contain
markup for colors and style.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notCommandLine.Command.version()
,
CommandLine.Option.versionHelp()
,
isVersionHelpRequested()
public void printVersionHelp(PrintStream out, CommandLine.Help.Ansi ansi, Object... params)
CommandLine.Command.version()
annotation to the specified PrintStream
.
Each element of the array of version strings is formatted with the
specified parameters, and printed on a separate line. Both version strings and parameters may contain
markup for colors and style.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notparams
- Arguments referenced by the format specifiers in the version stringsCommandLine.Command.version()
,
CommandLine.Option.versionHelp()
,
isVersionHelpRequested()
public void printVersionHelp(PrintWriter out)
printVersionHelp(PrintWriter, Help.Ansi, Object...)
with the ANSI setting of the configured color scheme.out
- the PrintWriter to print topublic void printVersionHelp(PrintWriter out, CommandLine.Help.Ansi ansi, Object... params)
CommandLine.Command.version()
annotation to the specified PrintWriter
.
Each element of the array of version strings is formatted with the
specified parameters, and printed on a separate line. Both version strings and parameters may contain
markup for colors and style.out
- the PrintWriter to print toansi
- whether the usage message should include ANSI escape codes or notparams
- Arguments referenced by the format specifiers in the version stringsCommandLine.Command.version()
,
CommandLine.Option.versionHelp()
,
isVersionHelpRequested()
@Deprecated public static <C extends Callable<T>,T> T call(C callable, String... args)
execute(String...)
and getExecutionResult()
insteadnew CommandLine(callable).execute(args)
, except for the return value.C
- the annotated object must implement CallableT
- the return type of the most specific command (must implement Callable
)callable
- the command to call when parsing succeeds.args
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exceptionexecute(String...)
@Deprecated public static <C extends Callable<T>,T> T call(C callable, PrintStream out, String... args)
execute(String...)
and getExecutionResult()
insteadcall(Callable, PrintStream, PrintStream, Help.Ansi, String...)
with System.err
for
diagnostic error messages and CommandLine.Help.Ansi.AUTO
.C
- the annotated object must implement CallableT
- the return type of the most specific command (must implement Callable
)callable
- the command to call when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helpargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exceptionCommandLine.RunLast
@Deprecated public static <C extends Callable<T>,T> T call(C callable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadcall(Callable, PrintStream, PrintStream, Help.Ansi, String...)
with System.err
for diagnostic error messages.C
- the annotated object must implement CallableT
- the return type of the most specific command (must implement Callable
)callable
- the command to call when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helpansi
- the ANSI style to useargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exceptionCommandLine.RunLast
@Deprecated public static <C extends Callable<T>,T> T call(C callable, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadCallable
.
Consider using the execute(String...)
method instead:
CommandLine cmd = new CommandLine(callable)
.setOut(myOutWriter()) // System.out by default
.setErr(myErrWriter()) // System.err by default
.setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default
int exitCode = cmd.execute(args);
//System.exit(exitCode);
If the specified Callable command has subcommands, the last subcommand specified on the command line is executed.
C
- the annotated object must implement CallableT
- the return type of the specified Callable
callable
- the command to call when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helperr
- the printStream to print diagnostic messages toansi
- including whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exception@Deprecated public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, String... args)
execute(String...)
and getExecutionResult()
insteadnew CommandLine(callableClass, factory).execute(args)
, except for the return value.C
- the annotated class must implement CallableT
- the return type of the most specific command (must implement Callable
)callableClass
- class of the command to call when parsing succeeds.factory
- the factory responsible for instantiating the specified callable class and potentially inject other componentsargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exceptionexecute(String...)
@Deprecated public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, String... args)
execute(String...)
and getExecutionResult()
insteadcall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
with
System.err
for diagnostic error messages, and CommandLine.Help.Ansi.AUTO
.C
- the annotated class must implement CallableT
- the return type of the most specific command (must implement Callable
)callableClass
- class of the command to call when parsing succeeds.factory
- the factory responsible for instantiating the specified callable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helpargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exception@Deprecated public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadcall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
with
System.err
for diagnostic error messages.C
- the annotated class must implement CallableT
- the return type of the most specific command (must implement Callable
)callableClass
- class of the command to call when parsing succeeds.factory
- the factory responsible for instantiating the specified callable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helpansi
- the ANSI style to useargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exception@Deprecated public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadcallableClass
;
use this method instead of call(Callable, ...)
if you want to use a factory that performs Dependency Injection.
The annotated class needs to implement Callable
.
Consider using the execute(String...)
method instead:
CommandLine cmd = new CommandLine(callableClass, factory)
.setOut(myOutWriter()) // System.out by default
.setErr(myErrWriter()) // System.err by default
.setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default
int exitCode = cmd.execute(args);
//System.exit(exitCode);
If the specified Callable command has subcommands, the last subcommand specified on the command line is executed.
C
- the annotated class must implement CallableT
- the return type of the most specific command (must implement Callable
)callableClass
- class of the command to call when parsing succeeds.factory
- the factory responsible for instantiating the specified callable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helperr
- the printStream to print diagnostic messages toansi
- the ANSI style to useargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the CallableCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Callable throws an exception@Deprecated public static <R extends Runnable> void run(R runnable, String... args)
execute(String...)
insteadnew CommandLine(runnable).execute(args)
.R
- the annotated object must implement Runnablerunnable
- the command to run when parsing succeeds.args
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionexecute(String...)
@Deprecated public static <R extends Runnable> void run(R runnable, PrintStream out, String... args)
execute(String...)
insteadrun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
with System.err
for diagnostic error messages and CommandLine.Help.Ansi.AUTO
.R
- the annotated object must implement Runnablerunnable
- the command to run when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helpargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionCommandLine.RunLast
@Deprecated public static <R extends Runnable> void run(R runnable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
insteadrun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
with System.err
for diagnostic error messages.R
- the annotated object must implement Runnablerunnable
- the command to run when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helpansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionCommandLine.RunLast
@Deprecated public static <R extends Runnable> void run(R runnable, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
insteadRunnable
.
Consider using the execute(String...)
method instead:
CommandLine cmd = new CommandLine(runnable)
.setOut(myOutWriter()) // System.out by default
.setErr(myErrWriter()) // System.err by default
.setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default
int exitCode = cmd.execute(args);
//System.exit(exitCode);
If the specified Runnable command has subcommands, the last subcommand specified on the command line is executed.
From picocli v2.0, this method prints usage help or version help if requested,
and any exceptions thrown by the Runnable
are caught and rethrown wrapped in an ExecutionException
.
R
- the annotated object must implement Runnablerunnable
- the command to run when parsing succeeds.out
- the printStream to print the usage help message to when the user requested helperr
- the printStream to print diagnostic messages toansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exception@Deprecated public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, String... args)
execute(String...)
insteadnew CommandLine(runnableClass, factory).execute(args)
.R
- the annotated class must implement RunnablerunnableClass
- class of the command to run when parsing succeeds.factory
- the factory responsible for instantiating the specified Runnable class and potentially injecting other componentsargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionexecute(String...)
@Deprecated public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, String... args)
execute(String...)
insteadrun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
with
System.err
for diagnostic error messages, and CommandLine.Help.Ansi.AUTO
.R
- the annotated class must implement RunnablerunnableClass
- class of the command to run when parsing succeeds.factory
- the factory responsible for instantiating the specified Runnable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helpargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionrun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
,
CommandLine.RunLast
@Deprecated public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
insteadrun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
with
System.err
for diagnostic error messages.R
- the annotated class must implement RunnablerunnableClass
- class of the command to run when parsing succeeds.factory
- the factory responsible for instantiating the specified Runnable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helpansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified class cannot be instantiated by the factory, or does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ExecutionException
- if the Runnable throws an exceptionrun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
,
CommandLine.RunLast
@Deprecated public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
insteadrunnableClass
;
use this method instead of run(Runnable, ...)
if you want to use a factory that performs Dependency Injection.
The annotated class needs to implement Runnable
.
Consider using the execute(String...)
method instead:
CommandLine cmd = new CommandLine(runnableClass, factory)
.setOut(myOutWriter()) // System.out by default
.setErr(myErrWriter()) // System.err by default
.setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default
int exitCode = cmd.execute(args);
//System.exit(exitCode);
If the specified Runnable command has subcommands, the last subcommand specified on the command line is executed.
This method prints usage help or version help if requested,
and any exceptions thrown by the Runnable
are caught and rethrown wrapped in an ExecutionException
.
R
- the annotated class must implement RunnablerunnableClass
- class of the command to run when parsing succeeds.factory
- the factory responsible for instantiating the specified Runnable class and potentially injecting other componentsout
- the printStream to print the usage help message to when the user requested helperr
- the printStream to print diagnostic messages toansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parse@Deprecated public static Object invoke(String methodName, Class<?> cls, String... args)
execute(String...)
and getExecutionResult()
insteadinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
with System.out
for
requested usage help messages, System.err
for diagnostic error messages, and CommandLine.Help.Ansi.AUTO
.methodName
- the @Command
-annotated method to build a CommandLine.Model.CommandSpec
model from,
and run when parsing succeeds.cls
- the class where the @Command
-annotated method is declared, or a subclassargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified method does not have a CommandLine.Command
annotation,
or if the specified class contains multiple @Command
-annotated methods with the specified nameCommandLine.ExecutionException
- if the Runnable throws an exceptioninvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
@Deprecated public static Object invoke(String methodName, Class<?> cls, PrintStream out, String... args)
execute(String...)
and getExecutionResult()
insteadinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
with the specified stream for
requested usage help messages, System.err
for diagnostic error messages, and CommandLine.Help.Ansi.AUTO
.methodName
- the @Command
-annotated method to build a CommandLine.Model.CommandSpec
model from,
and run when parsing succeeds.cls
- the class where the @Command
-annotated method is declared, or a subclassout
- the printstream to print requested help message toargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified method does not have a CommandLine.Command
annotation,
or if the specified class contains multiple @Command
-annotated methods with the specified nameCommandLine.ExecutionException
- if the Runnable throws an exceptioninvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
@Deprecated public static Object invoke(String methodName, Class<?> cls, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
with the specified stream for
requested usage help messages, System.err
for diagnostic error messages, and the specified Ansi mode.methodName
- the @Command
-annotated method to build a CommandLine.Model.CommandSpec
model from,
and run when parsing succeeds.cls
- the class where the @Command
-annotated method is declared, or a subclassout
- the printstream to print requested help message toansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified method does not have a CommandLine.Command
annotation,
or if the specified class contains multiple @Command
-annotated methods with the specified nameCommandLine.ExecutionException
- if the Runnable throws an exceptioninvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
@Deprecated public static Object invoke(String methodName, Class<?> cls, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
execute(String...)
and getExecutionResult()
insteadCommandLine.Model.CommandSpec
model from the @Option
and @Parameters
-annotated method parameters
of the @Command
-annotated method, parses the specified command line arguments and invokes the specified method.
Consider using the execute(String...)
method instead:
Method commandMethod = getCommandMethods(cls, methodName).get(0);
CommandLine cmd = new CommandLine(commandMethod)
.setOut(myOutWriter()) // System.out by default
.setErr(myErrWriter()) // System.err by default
.setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default
int exitCode = cmd.execute(args);
//System.exit(exitCode);
methodName
- the @Command
-annotated method to build a CommandLine.Model.CommandSpec
model from,
and run when parsing succeeds.cls
- the class where the @Command
-annotated method is declared, or a subclassout
- the printStream to print the usage help message to when the user requested helperr
- the printStream to print diagnostic messages toansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseCommandLine.InitializationException
- if the specified method does not have a CommandLine.Command
annotation,
or if the specified class contains multiple @Command
-annotated methods with the specified nameCommandLine.ExecutionException
- if the method throws an exceptionpublic static List<Method> getCommandMethods(Class<?> cls, String methodName)
@Command
via reflection, optionally filtered by method name (not @Command.name
).
Methods have to be either public (inherited) members or be declared by cls
, that is "inherited" static or protected methods will not be picked up.cls
- the class to search for methods annotated with @Command
methodName
- if not null
, return only methods whose method name (not @Command.name
) equals this string. Ignored if null
.invoke(String, Class, String...)
public <K> CommandLine registerConverter(Class<K> cls, CommandLine.ITypeConverter<K> converter)
CommandLine.Option
, the field's type is used as a lookup key to find the associated type converter, and this
type converter converts the original command line argument string value to the correct type.
Java 8 lambdas make it easy to register custom type converters:
commandLine.registerConverter(java.nio.file.Path.class, s -> java.nio.file.Paths.get(s)); commandLine.registerConverter(java.time.Duration.class, s -> java.time.Duration.parse(s));
Built-in type converters are pre-registered for the following java 1.5 types:
The specified converter will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment the converter is registered. Subcommands added
later will not have this converter added automatically. To ensure a custom type converter is available to all
subcommands, register the type converter last, after adding subcommands.
K
- the target typecls
- the target class to convert parameter string values toconverter
- the class capable of converting string values to the specified target typeaddSubcommand(String, Object)
public String getSeparator()
CommandLine.Model.ParserSpec.separator()
public CommandLine setSeparator(String separator)
CommandLine.Command.separator()
annotation attribute.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
separator
- the String that separates option names from option valuesCommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.separator(String)
public ResourceBundle getResourceBundle()
null
if no resource bundle is set.CommandLine.Command.resourceBundle()
,
CommandLine.Model.CommandSpec.resourceBundle()
public CommandLine setResourceBundle(ResourceBundle bundle)
The specified bundle will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will not be impacted. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
bundle
- the ResourceBundle containing usage help message stringsCommandLine
object, to allow method chainingCommandLine.Command.resourceBundle()
,
CommandLine.Model.CommandSpec.resourceBundle(ResourceBundle)
public int getUsageHelpWidth()
public CommandLine setUsageHelpWidth(int width)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
width
- the maximum width of the usage help messageCommandLine
object, to allow method chainingCommandLine.Model.UsageMessageSpec.width(int)
public int getUsageHelpLongOptionsMaxWidth()
CommandLine.Model.UsageMessageSpec.longOptionsMaxWidth()
public CommandLine setUsageHelpLongOptionsMaxWidth(int columnWidth)
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
columnWidth
- the new maximum usage help long options column max width. Must be 20 or greater.CommandLine
object, to allow method chainingCommandLine.Model.UsageMessageSpec.longOptionsMaxWidth(int)
public boolean isUsageHelpAutoWidth()
"picocli.usage.width"
to AUTO
,
and may disable this by setting this system property to a numeric value.
This feature requires Java 7 or greater. The default is false
.CommandLine.Model.UsageMessageSpec.autoWidth()
public CommandLine setUsageHelpAutoWidth(boolean detectTerminalSize)
false
.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
detectTerminalSize
- whether picocli should attempt to detect the terminal sizeCommandLine
object, to allow method chainingCommandLine.Model.UsageMessageSpec.autoWidth(boolean)
public String getCommandName()
CommandLine.Model.CommandSpec.name()
public CommandLine setCommandName(String commandName)
CommandLine.Command.name()
annotation attribute.commandName
- command name (also called program name) displayed in the usage help synopsisCommandLine
object, to allow method chainingCommandLine.Model.CommandSpec.name(String)
public boolean isExpandAtFiles()
'@'
should be treated as the path to an argument file and its
contents should be expanded into separate arguments for each line in the specified file.
This property is true
by default.@files
should be expanded into their contentCommandLine.Model.ParserSpec.expandAtFiles()
public CommandLine setExpandAtFiles(boolean expandAtFiles)
'@'
should be treated as the path to an argument file and its
contents should be expanded into separate arguments for each line in the specified file. (true
by default.)expandAtFiles
- whether "argument files" or @files
should be expanded into their contentCommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.expandAtFiles(boolean)
public Character getAtFileCommentChar()
null
if all content of argument files should
be interpreted as arguments (without comments).
If specified, all characters from the comment character to the end of the line are ignored.null
. The default is '#'
.CommandLine.Model.ParserSpec.atFileCommentChar()
public CommandLine setAtFileCommentChar(Character atFileCommentChar)
null
if all content of argument files should
be interpreted as arguments (without comments).
If specified, all characters from the comment character to the end of the line are ignored.atFileCommentChar
- the character that starts a single-line comment or null
. The default is '#'
.CommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.atFileCommentChar(Character)
public boolean isUseSimplifiedAtFiles()
"picocli.useSimplifiedAtFiles"
is defined, the system property value overrides the programmatically set value.false
.CommandLine.Model.ParserSpec.useSimplifiedAtFiles()
public CommandLine setUseSimplifiedAtFiles(boolean simplifiedAtFiles)
"picocli.useSimplifiedAtFiles"
is defined, the system property value overrides the programmatically set value.simplifiedAtFiles
- whether to use a simplified argument file format. The default is false
.CommandLine
object, to allow method chainingCommandLine.Model.ParserSpec.useSimplifiedAtFiles(boolean)
public CommandLine.INegatableOptionTransformer getNegatableOptionTransformer()
INegatableOptionTransformer
used to create the negative form of negatable options.
By default this returns the result of CommandLine.RegexTransformer.createDefault()
.INegatableOptionTransformer
used to create negative option names.CommandLine.Option.negatable()
,
CommandLine.Model.CommandSpec.negatableOptionTransformer()
public CommandLine setNegatableOptionTransformer(CommandLine.INegatableOptionTransformer transformer)
INegatableOptionTransformer
used to create the negative form of negatable options.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
setOptionsCaseInsensitive(boolean)
will also change the case sensitivity of negatable options:
any custom CommandLine.INegatableOptionTransformer
that was previously installed will be replaced by the case-insensitive
version of the default transformer. To ensure your custom transformer is used, install it last, after changing case sensitivity.transformer
- the INegatableOptionTransformer
used to create negative option names.CommandLine
object, to allow method chainingCommandLine.Option.negatable()
,
CommandLine.Model.CommandSpec.negatableOptionTransformer(CommandLine.INegatableOptionTransformer)
public static CommandLine.IFactory defaultFactory()
CommandLine.IFactory
implementation used if no factory was specified in the CommandLine constructor
.
This implementation has special logic for instantiating Collections
and Maps
, and otherwise tries to create an instance by invoking the default constructor of the specified class.
Special logic for instantiating Collections and Maps:
// if class is an interface that extends java.util.Collection, return a new instance of:
1. List -> ArrayList
2. SortedSet -> TreeSet
3. Set -> LinkedHashSet
4. Queue -> LinkedList
5. Collection -> ArrayList
// if extending or implementing java.util.Map:
1. try invoking the default constructor; return this on success.
2. if this fails, return a LinkedHashMap
public static CommandLine.Tracer tracer()
Tracer
used internally for printing internal debug statements.Tracer
used internally for printing internal debug statements