public class CommandLine extends Object
CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the command line arguments.
import static picocli.CommandLine.*; @Command(header = "Encrypt FILE(s), or standard input, to standard output or to the output file.", version = "v1.2.3") public class Encrypt { @Parameters(type = File.class, 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 = "Verbosely list files processed") private boolean verbose; @Option(names = { "-h", "--help", "-?", "-help"}, usageHelp = true, description = "Display this help and exit") private boolean help; @Option(names = { "-V", "--version"}, versionHelp = true, description = "Display version info and exit") private boolean versionHelp; }
Use CommandLine
to initialize a domain object as follows:
public static void main(String... args) { Encrypt encrypt = new Encrypt(); try { List<CommandLine> parsedCommands = new CommandLine(encrypt).parse(args); if (!CommandLine.printHelpIfRequested(parsedCommands, System.err, Help.Ansi.AUTO)) { 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 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
Default exception handler that prints the exception message to the specified
PrintStream , followed by the
usage message for the command or subcommand whose input was invalid. |
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.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 interface |
CommandLine.IExceptionHandler
Represents a function that can handle a
ParameterException that occurred while
parsing the command line arguments. |
static class |
CommandLine.InitializationException
Exception indicating a problem during
CommandLine initialization. |
static interface |
CommandLine.IParseResultHandler
Represents a function that can process a List of
CommandLine objects resulting from successfully
parsing the command line arguments. |
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 class |
CommandLine.MaxValuesforFieldExceededException
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.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 class |
CommandLine.PicocliException
Base class of all exceptions thrown by
picocli.CommandLine . |
static class |
CommandLine.Range
Describes the number of parameters required and accepted by an option or a positional parameter.
|
static class |
CommandLine.RunAll
Command line parse result handler that prints help if requested, and otherwise executes the top-level command and
all subcommands as
Runnable or Callable . |
static class |
CommandLine.RunFirst
Command line parse result handler that prints help if requested, and otherwise executes the top-level
Runnable or Callable command. |
static class |
CommandLine.RunLast
Command line parse result handler that prints help if requested, and otherwise executes the most specific
Runnable or Callable subcommand. |
static class |
CommandLine.TypeConversionException
Exception thrown by
CommandLine.ITypeConverter implementations to indicate a String could not be converted. |
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 . |
Modifier and Type | Field and Description |
---|---|
static String |
VERSION
This is picocli version "2.0.3".
|
Constructor and Description |
---|
CommandLine(Object command)
Constructs a new
CommandLine interpreter with the specified annotated object. |
Modifier and Type | Method and Description |
---|---|
CommandLine |
addSubcommand(String name,
Object command)
Registers a subcommand with the specified name.
|
static <C extends Callable<T>,T> |
call(C callable,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application.
|
static <C extends Callable<T>,T> |
call(C callable,
PrintStream out,
String... args)
Delegates to
call(Callable, PrintStream, Help.Ansi, String...) with CommandLine.Help.Ansi.AUTO . |
<T> T |
getCommand()
Returns the annotated object that this
CommandLine instance was constructed with. |
String |
getCommandName()
Returns the command name (also called program name) displayed in the usage help synopsis.
|
CommandLine |
getParent()
Returns the command that this is a subcommand of, or
null if this is a top-level command. |
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.
|
boolean |
isOverwrittenOptionsAllowed()
Returns whether options for single-value fields can be specified multiple times on the command line.
|
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 |
isUsageHelpRequested()
Returns
true if an option annotated with CommandLine.Option.usageHelp() was specified on the command line. |
boolean |
isVersionHelpRequested()
Returns
true if an option annotated with CommandLine.Option.versionHelp() was specified on the command line. |
List<CommandLine> |
parse(String... args)
Parses the specified command line arguments and returns a list of
CommandLine objects representing the
top-level command and any subcommands (if any) that were recognized and initialized during the parsing process. |
List<Object> |
parseWithHandler(CommandLine.IParseResultHandler handler,
PrintStream out,
String... args)
Returns the result of calling
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
with Help.Ansi.AUTO and a new CommandLine.DefaultExceptionHandler in addition to the specified parse result handler,
PrintStream , and the specified command line arguments. |
List<Object> |
parseWithHandlers(CommandLine.IParseResultHandler handler,
PrintStream out,
CommandLine.Help.Ansi ansi,
CommandLine.IExceptionHandler exceptionHandler,
String... args)
|
static <T> T |
populateCommand(T command,
String... args)
Convenience method that initializes the specified annotated object from the specified command line arguments.
|
static boolean |
printHelpIfRequested(List<CommandLine> parsedCommands,
PrintStream out,
CommandLine.Help.Ansi ansi)
Helper method that may be useful when processing the list of
CommandLine objects that result from successfully
parsing command line arguments. |
void |
printVersionHelp(PrintStream out)
Delegates to
printVersionHelp(PrintStream, Help.Ansi) with the platform default. |
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 . |
<K> CommandLine |
registerConverter(Class<K> cls,
CommandLine.ITypeConverter<K> converter)
Registers the specified type converter for the specified class.
|
static <R extends Runnable> |
run(R runnable,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application.
|
static <R extends Runnable> |
run(R runnable,
PrintStream out,
String... args)
Delegates to
run(Runnable, PrintStream, Help.Ansi, String...) with CommandLine.Help.Ansi.AUTO . |
CommandLine |
setCommandName(String commandName)
Sets the command name (also called program name) displayed in the usage help synopsis to the specified value.
|
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 |
setSeparator(String separator)
Sets the String the parser uses to separate option names from option values to the specified value.
|
CommandLine |
setUnmatchedArgumentsAllowed(boolean newValue)
Sets whether the end user may specify unmatched arguments on the command line without a
CommandLine.UnmatchedArgumentException being thrown. |
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.Ansi) with the platform default. |
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 . |
public static final String VERSION
public CommandLine(Object command)
CommandLine
interpreter with the specified annotated object.
When the parse(String...)
method is called, fields of the specified object that are annotated
with @Option
or @Parameters
will be initialized based on command line arguments.command
- the 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 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 subcommandcommand
- the object to initialize with command line arguments following the subcommand name.
This may be a CommandLine
instance with its own (nested) subcommandsregisterConverter(Class, ITypeConverter)
,
CommandLine.Command.subcommands()
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 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 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 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 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 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 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
CommandLine cli = new CommandLine(command); cli.parse(args); return command;
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 invalidpublic List<CommandLine> parse(String... args)
CommandLine
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.
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 static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, CommandLine.Help.Ansi ansi)
CommandLine
objects that result from successfully
parsing command line arguments. This method prints out
usage help if requested
or version help if requested
and returns true
. Otherwise, if none of the specified CommandLine
objects have help requested,
this method returns false
.
Note that this method only looks at the usageHelp
and
versionHelp
attributes. The help
attribute is ignored.
parsedCommands
- the list of CommandLine
objects to check if help was requestedout
- the PrintStream
to print help to if requestedansi
- for printing help messages using ANSI styles and colorstrue
if help was printed, false
otherwisepublic List<Object> parseWithHandler(CommandLine.IParseResultHandler handler, PrintStream out, String... args)
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
with Help.Ansi.AUTO
and a new CommandLine.DefaultExceptionHandler
in addition to the specified parse result handler,
PrintStream
, 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 { List<CommandLine> parsedCommands = parse(args); return parseResultsHandler.handleParseResult(parsedCommands, out, Help.Ansi.AUTO); } catch (ParameterException ex) { return new DefaultExceptionHandler().handleException(ex, out, ansi, 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 helphandler
- the function that will process the result of successfully parsing the command line argumentsout
- the PrintStream
to print help to if requestedargs
- 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
public List<Object> parseWithHandlers(CommandLine.IParseResultHandler handler, PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, String... args)
CommandLine
objects 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.IExceptionHandler
.
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 { List<CommandLine> parsedCommands = parse(args); return parseResultsHandler.handleParseResult(parsedCommands, out, ansi); } catch (ParameterException ex) { return new exceptionHandler.handleException(ex, out, ansi, 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 helphandler
- the function that will process the result of successfully parsing the command line argumentsout
- the PrintStream
to print help to if requestedansi
- for printing help messages using ANSI styles and colorsexceptionHandler
- the function that can handle the ParameterException
thrown when the command line arguments are invalidargs
- the command line argumentsIParseResultHandler
or the IExceptionHandler
, or an empty list if there are no resultsCommandLine.ExecutionException
- if the command line arguments were parsed successfully but a problem occurred while processing the parse
result CommandLine
objects; 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.Ansi)
with the platform default.out
- the printStream to print tousage(PrintStream, 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(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 help = new Help(command).addAllSubcommands(getSubcommands()); StringBuilder sb = new StringBuilder() .append(help.headerHeading()) .append(help.header()) .append(help.synopsisHeading()) //e.g. Usage: .append(help.synopsis()) //e.g. <main class> [OPTIONS] <command> [COMMAND-OPTIONS] [ARGUMENTS] .append(help.descriptionHeading()) //e.g. %nDescription:%n%n .append(help.description()) //e.g. {"Converts foos to bars.", "Use options to control conversion mode."} .append(help.parameterListHeading()) //e.g. %nPositional parameters:%n%n .append(help.parameterList()) //e.g. [FILE...] the files to convert .append(help.optionListHeading()) //e.g. %nOptions:%n%n .append(help.optionList()) //e.g. -h, --help displays this help and exits .append(help.commandListHeading()) //e.g. %nCommands:%n%n .append(help.commandList()) //e.g. add adds the frup to the frooble .append(help.footerHeading()) .append(help.footer()); 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 enabledpublic void printVersionHelp(PrintStream out)
printVersionHelp(PrintStream, Help.Ansi)
with the platform default.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 static <C extends Callable<T>,T> T call(C callable, PrintStream out, String... args)
call(Callable, PrintStream, Help.Ansi, String...)
with CommandLine.Help.Ansi.AUTO
.
From picocli v2.0, this method prints usage help or version help if requested,
and any exceptions thrown by the Callable
are caught and rethrown wrapped in an ExecutionException
.
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 toargs
- the command line arguments to parsenull
if an error occurred while parsing the command line options, 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 exceptioncall(Callable, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
,
CommandLine.RunFirst
public static <C extends Callable<T>,T> T call(C callable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Callable
. Calling this method is equivalent to:
CommandLine cmd = new CommandLine(callable); List<CommandLine> parsedCommands; try { parsedCommands = cmd.parse(args); } catch (ParameterException ex) { out.println(ex.getMessage()); cmd.usage(out, ansi); return null; } if (CommandLine.printHelpIfRequested(parsedCommands, out, ansi)) { return null; } CommandLine last = parsedCommands.get(parsedCommands.size() - 1); try { Callable<Object> subcommand = last.getCommand(); return subcommand.call(); } catch (Exception ex) { throw new ExecutionException(last, "Error calling " + last.getCommand(), ex); }
If the specified Callable command has subcommands, the last subcommand specified on the
command line is executed.
Commands with subcommands may be interested in calling the parseWithHandler
method with a CommandLine.RunAll
handler or a custom handler.
From picocli v2.0, this method prints usage help or version help if requested,
and any exceptions thrown by the Callable
are caught and rethrown wrapped in an ExecutionException
.
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 toansi
- 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 exceptionparseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
,
CommandLine.RunLast
public static <R extends Runnable> void run(R runnable, PrintStream out, String... args)
run(Runnable, PrintStream, Help.Ansi, String...)
with CommandLine.Help.Ansi.AUTO
.
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 toargs
- 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 exceptionrun(Runnable, PrintStream, Help.Ansi, String...)
,
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
,
CommandLine.RunFirst
public static <R extends Runnable> void run(R runnable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Runnable
. Calling this method is equivalent to:
CommandLine cmd = new CommandLine(runnable); List<CommandLine> parsedCommands; try { parsedCommands = cmd.parse(args); } catch (ParameterException ex) { out.println(ex.getMessage()); cmd.usage(out, ansi); return null; } if (CommandLine.printHelpIfRequested(parsedCommands, out, ansi)) { return null; } CommandLine last = parsedCommands.get(parsedCommands.size() - 1); try { Runnable subcommand = last.getCommand(); subcommand.run(); } catch (Exception ex) { throw new ExecutionException(last, "Error running " + last.getCommand(), ex); }
If the specified Runnable command has subcommands, the last subcommand specified on the
command line is executed.
Commands with subcommands may be interested in calling the parseWithHandler
method with a CommandLine.RunAll
handler or a custom handler.
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 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 exceptionparseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)
,
CommandLine.RunLast
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()
public CommandLine setSeparator(String separator)
CommandLine.Command.separator()
annotation attribute.separator
- the String that separates option names from option valuesCommandLine
object, to allow method chainingpublic String getCommandName()
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 chaining Copyright © 1999-2023 The Apache Software Foundation. All Rights Reserved.
Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, the Apache Logging project logo, and the Apache Log4j logo are trademarks of The Apache Software Foundation.