Class CommandLine
- java.lang.Object
-
- org.apache.logging.log4j.core.tools.picocli.CommandLine
-
public class CommandLine extends java.lang.ObjectCommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the command line arguments.
Example
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
CommandLineto 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
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classCommandLine.AssertUtility class providing some defensive coding convenience methods.private static classCommandLine.BuiltInInner class to group the built-inCommandLine.ITypeConverterimplementations.static interfaceCommandLine.CommandAnnotate your class with@Commandwhen you want more control over the format of the generated help message.static classCommandLine.DefaultExceptionHandlerDefault exception handler that prints the exception message to the specifiedPrintStream, followed by the usage message for the command or subcommand whose input was invalid.static classCommandLine.DuplicateOptionAnnotationsExceptionException indicating that multiple fields have been annotated with the same Option name.static classCommandLine.ExecutionExceptionException indicating a problem while invoking a command or subcommand.static classCommandLine.HelpA 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 interfaceCommandLine.IExceptionHandlerRepresents a function that can handle aParameterExceptionthat occurred while parsing the command line arguments.static classCommandLine.InitializationExceptionException indicating a problem duringCommandLineinitialization.private classCommandLine.InterpreterHelper class responsible for processing command line arguments.static interfaceCommandLine.IParseResultHandlerRepresents a function that can process a List ofCommandLineobjects resulting from successfully parsing the command line arguments.static interfaceCommandLine.ITypeConverter<K>When parsing command line arguments and initializing fields annotated with@Optionor@Parameters, String values can be converted to any type for which aITypeConverteris registered.static classCommandLine.MaxValuesforFieldExceededExceptionException indicating that more values were specified for an option or parameter than itsarityallows.static classCommandLine.MissingParameterExceptionException indicating that a required parameter was not specified.static classCommandLine.MissingTypeConverterExceptionException indicating that an annotated field had a type for which noCommandLine.ITypeConverterwas registered.static interfaceCommandLine.OptionAnnotate fields in your class with@Optionand picocli will initialize these fields when matching arguments are specified on the command line.static classCommandLine.OverwrittenOptionExceptionException indicating that an option for a single-value option field has been specified multiple times on the command line.static classCommandLine.ParameterExceptionException indicating something went wrong while parsing command line options.static classCommandLine.ParameterIndexGapExceptionException indicating that there was a gap in the indices of the fields annotated withCommandLine.Parameters.static interfaceCommandLine.ParametersFields annotated with@Parameterswill be initialized with positional parameters.static classCommandLine.PicocliExceptionBase class of all exceptions thrown bypicocli.CommandLine.private static classCommandLine.PositionalParametersSorterstatic classCommandLine.RangeDescribes the number of parameters required and accepted by an option or a positional parameter.static classCommandLine.RunAllCommand line parse result handler that prints help if requested, and otherwise executes the top-level command and all subcommands asRunnableorCallable.static classCommandLine.RunFirstCommand line parse result handler that prints help if requested, and otherwise executes the top-levelRunnableorCallablecommand.static classCommandLine.RunLastCommand line parse result handler that prints help if requested, and otherwise executes the most specificRunnableorCallablesubcommand.private static classCommandLine.TraceLevelprivate static classCommandLine.Tracerstatic classCommandLine.TypeConversionExceptionException thrown byCommandLine.ITypeConverterimplementations to indicate a String could not be converted.static classCommandLine.UnmatchedArgumentExceptionException indicating that a command line argument could not be mapped to any of the fields annotated withCommandLine.OptionorCommandLine.Parameters.
-
Field Summary
Fields Modifier and Type Field Description private java.lang.StringcommandNameprivate CommandLine.Interpreterinterpreterprivate booleanoverwrittenOptionsAllowedprivate CommandLineparentprivate CommandLine.Tracertracerprivate java.util.List<java.lang.String>unmatchedArgumentsprivate booleanunmatchedArgumentsAllowedprivate booleanusageHelpRequestedstatic java.lang.StringVERSIONThis is picocli version "2.0.3".private booleanversionHelpRequestedprivate java.util.List<java.lang.String>versionLines
-
Constructor Summary
Constructors Constructor Description CommandLine(java.lang.Object command)Constructs a newCommandLineinterpreter with the specified annotated object.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description CommandLineaddSubcommand(java.lang.String name, java.lang.Object command)Registers a subcommand with the specified name.static <C extends java.util.concurrent.Callable<T>,T>
Tcall(C callable, java.io.PrintStream out, java.lang.String... args)Delegates tocall(Callable, PrintStream, Help.Ansi, String...)withCommandLine.Help.Ansi.AUTO.static <C extends java.util.concurrent.Callable<T>,T>
Tcall(C callable, java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.String... args)Convenience method to allow command line application authors to avoid some boilerplate code in their application.private static booleanempty(java.lang.Object[] array)private static booleanempty(java.lang.String str)private static booleanempty(CommandLine.Help.Ansi.Text txt)private static java.lang.Objectexecute(CommandLine parsed)<T> TgetCommand()Returns the annotated object that thisCommandLineinstance was constructed with.java.lang.StringgetCommandName()Returns the command name (also called program name) displayed in the usage help synopsis.CommandLinegetParent()Returns the command that this is a subcommand of, ornullif this is a top-level command.java.lang.StringgetSeparator()Returns the String that separates option names from option values when parsing command line options.java.util.Map<java.lang.String,CommandLine>getSubcommands()Returns a map with the subcommands registered on this instance.private static java.lang.Class<?>[]getTypeAttribute(java.lang.reflect.Field field)java.util.List<java.lang.String>getUnmatchedArguments()Returns the list of unmatched command line arguments, if any.(package private) static voidinit(java.lang.Class<?> cls, java.util.List<java.lang.reflect.Field> requiredFields, java.util.Map<java.lang.String,java.lang.reflect.Field> optionName2Field, java.util.Map<java.lang.Character,java.lang.reflect.Field> singleCharOption2Field, java.util.List<java.lang.reflect.Field> positionalParametersFields)private static booleanisBoolean(java.lang.Class<?> type)private static booleanisMultiValue(java.lang.Class<?> cls)private static booleanisMultiValue(java.lang.reflect.Field field)booleanisOverwrittenOptionsAllowed()Returns whether options for single-value fields can be specified multiple times on the command line.booleanisUnmatchedArgumentsAllowed()Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.booleanisUsageHelpRequested()Returnstrueif an option annotated withCommandLine.Option.usageHelp()was specified on the command line.booleanisVersionHelpRequested()Returnstrueif an option annotated withCommandLine.Option.versionHelp()was specified on the command line.java.util.List<CommandLine>parse(java.lang.String... args)Parses the specified command line arguments and returns a list ofCommandLineobjects representing the top-level command and any subcommands (if any) that were recognized and initialized during the parsing process.java.util.List<java.lang.Object>parseWithHandler(CommandLine.IParseResultHandler handler, java.io.PrintStream out, java.lang.String... args)Returns the result of callingparseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)withHelp.Ansi.AUTOand a newCommandLine.DefaultExceptionHandlerin addition to the specified parse result handler,PrintStream, and the specified command line arguments.java.util.List<java.lang.Object>parseWithHandlers(CommandLine.IParseResultHandler handler, java.io.PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, java.lang.String... args)static <T> TpopulateCommand(T command, java.lang.String... args)Convenience method that initializes the specified annotated object from the specified command line arguments.static booleanprintHelpIfRequested(java.util.List<CommandLine> parsedCommands, java.io.PrintStream out, CommandLine.Help.Ansi ansi)Helper method that may be useful when processing the list ofCommandLineobjects that result from successfully parsing command line arguments.voidprintVersionHelp(java.io.PrintStream out)Delegates toprintVersionHelp(PrintStream, Help.Ansi)with the platform default.voidprintVersionHelp(java.io.PrintStream out, CommandLine.Help.Ansi ansi)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream.voidprintVersionHelp(java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.Object... params)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream.<K> CommandLineregisterConverter(java.lang.Class<K> cls, CommandLine.ITypeConverter<K> converter)Registers the specified type converter for the specified class.private static <T> java.util.Stack<T>reverse(java.util.Stack<T> stack)static <R extends java.lang.Runnable>
voidrun(R runnable, java.io.PrintStream out, java.lang.String... args)Delegates torun(Runnable, PrintStream, Help.Ansi, String...)withCommandLine.Help.Ansi.AUTO.static <R extends java.lang.Runnable>
voidrun(R runnable, java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.String... args)Convenience method to allow command line application authors to avoid some boilerplate code in their application.CommandLinesetCommandName(java.lang.String commandName)Sets the command name (also called program name) displayed in the usage help synopsis to the specified value.CommandLinesetOverwrittenOptionsAllowed(boolean newValue)Sets whether options for single-value fields can be specified multiple times on the command line without aCommandLine.OverwrittenOptionExceptionbeing thrown.CommandLinesetSeparator(java.lang.String separator)Sets the String the parser uses to separate option names from option values to the specified value.CommandLinesetUnmatchedArgumentsAllowed(boolean newValue)Sets whether the end user may specify unmatched arguments on the command line without aCommandLine.UnmatchedArgumentExceptionbeing thrown.private static java.lang.Stringstr(java.lang.String[] arr, int i)private static CommandLinetoCommandLine(java.lang.Object obj)voidusage(java.io.PrintStream out)Delegates tousage(PrintStream, Help.Ansi)with the platform default.voidusage(java.io.PrintStream out, CommandLine.Help.Ansi ansi)Delegates tousage(PrintStream, Help.ColorScheme)with the default color scheme.voidusage(java.io.PrintStream out, CommandLine.Help.ColorScheme colorScheme)Prints a usage help message for the annotated command class to the specifiedPrintStream.static voidusage(java.lang.Object command, java.io.PrintStream out)Equivalent tonew CommandLine(command).usage(out).static voidusage(java.lang.Object command, java.io.PrintStream out, CommandLine.Help.Ansi ansi)Equivalent tonew CommandLine(command).usage(out, ansi).static voidusage(java.lang.Object command, java.io.PrintStream out, CommandLine.Help.ColorScheme colorScheme)Equivalent tonew CommandLine(command).usage(out, colorScheme).(package private) static voidvalidatePositionalParameters(java.util.List<java.lang.reflect.Field> positionalParametersFields)
-
-
-
Field Detail
-
VERSION
public static final java.lang.String VERSION
This is picocli version "2.0.3".- See Also:
- Constant Field Values
-
tracer
private final CommandLine.Tracer tracer
-
interpreter
private final CommandLine.Interpreter interpreter
-
commandName
private java.lang.String commandName
-
overwrittenOptionsAllowed
private boolean overwrittenOptionsAllowed
-
unmatchedArgumentsAllowed
private boolean unmatchedArgumentsAllowed
-
unmatchedArguments
private final java.util.List<java.lang.String> unmatchedArguments
-
parent
private CommandLine parent
-
usageHelpRequested
private boolean usageHelpRequested
-
versionHelpRequested
private boolean versionHelpRequested
-
versionLines
private final java.util.List<java.lang.String> versionLines
-
-
Constructor Detail
-
CommandLine
public CommandLine(java.lang.Object command)
Constructs a newCommandLineinterpreter with the specified annotated object. When theparse(String...)method is called, fields of the specified object that are annotated with@Optionor@Parameterswill be initialized based on command line arguments.- Parameters:
command- the object to initialize from the command line arguments- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
-
Method Detail
-
addSubcommand
public CommandLine addSubcommand(java.lang.String name, java.lang.Object command)
Registers a subcommand with the specified name. For example: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
CommandLineinstance 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.- Parameters:
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 aCommandLineinstance with its own (nested) subcommands- Returns:
- this CommandLine object, to allow method chaining
- Since:
- 0.9.7
- See Also:
registerConverter(Class, ITypeConverter),CommandLine.Command.subcommands()
-
getSubcommands
public java.util.Map<java.lang.String,CommandLine> getSubcommands()
Returns a map with the subcommands registered on this instance.- Returns:
- a map with the registered subcommands
- Since:
- 0.9.7
-
getParent
public CommandLine getParent()
Returns the command that this is a subcommand of, ornullif this is a top-level command.- Returns:
- the command that this is a subcommand of, or
nullif this is a top-level command - Since:
- 0.9.8
- See Also:
addSubcommand(String, Object),CommandLine.Command.subcommands()
-
getCommand
public <T> T getCommand()
Returns the annotated object that thisCommandLineinstance was constructed with.- Type Parameters:
T- the type of the variable that the return value is being assigned to- Returns:
- the annotated object that this
CommandLineinstance was constructed with - Since:
- 0.9.7
-
isUsageHelpRequested
public boolean isUsageHelpRequested()
Returnstrueif an option annotated withCommandLine.Option.usageHelp()was specified on the command line.- Returns:
- whether the parser encountered an option annotated with
CommandLine.Option.usageHelp(). - Since:
- 0.9.8
-
isVersionHelpRequested
public boolean isVersionHelpRequested()
Returnstrueif an option annotated withCommandLine.Option.versionHelp()was specified on the command line.- Returns:
- whether the parser encountered an option annotated with
CommandLine.Option.versionHelp(). - Since:
- 0.9.8
-
isOverwrittenOptionsAllowed
public boolean isOverwrittenOptionsAllowed()
Returns whether options for single-value fields can be specified multiple times on the command line. The default isfalseand aCommandLine.OverwrittenOptionExceptionis thrown if this happens. Whentrue, the last specified value is retained.- Returns:
trueif options for single-value fields can be specified multiple times on the command line,falseotherwise- Since:
- 0.9.7
-
setOverwrittenOptionsAllowed
public CommandLine setOverwrittenOptionsAllowed(boolean newValue)
Sets whether options for single-value fields can be specified multiple times on the command line without aCommandLine.OverwrittenOptionExceptionbeing thrown.The specified setting will be registered with this
CommandLineand 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.- Parameters:
newValue- the new setting- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 0.9.7
-
isUnmatchedArgumentsAllowed
public boolean isUnmatchedArgumentsAllowed()
Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields. The default isfalseand aCommandLine.UnmatchedArgumentExceptionis thrown if this happens. Whentrue, the last unmatched arguments are available via thegetUnmatchedArguments()method.- Returns:
trueif the end use may specify unmatched arguments on the command line,falseotherwise- Since:
- 0.9.7
- See Also:
getUnmatchedArguments()
-
setUnmatchedArgumentsAllowed
public CommandLine setUnmatchedArgumentsAllowed(boolean newValue)
Sets whether the end user may specify unmatched arguments on the command line without aCommandLine.UnmatchedArgumentExceptionbeing thrown.The specified setting will be registered with this
CommandLineand 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.- Parameters:
newValue- the new setting. Whentrue, the last unmatched arguments are available via thegetUnmatchedArguments()method.- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 0.9.7
- See Also:
getUnmatchedArguments()
-
getUnmatchedArguments
public java.util.List<java.lang.String> getUnmatchedArguments()
Returns the list of unmatched command line arguments, if any.- Returns:
- the list of unmatched command line arguments or an empty list
- Since:
- 0.9.7
- See Also:
isUnmatchedArgumentsAllowed()
-
populateCommand
public static <T> T populateCommand(T command, java.lang.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;
- Type Parameters:
T- the type of the annotated object- Parameters:
command- the object to initialize. This object contains fields annotated with@Optionor@Parameters.args- the command line arguments to parse- Returns:
- the specified annotated object
- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ParameterException- if the specified command line arguments are invalid- Since:
- 0.9.7
-
parse
public java.util.List<CommandLine> parse(java.lang.String... args)
Parses the specified command line arguments and returns a list ofCommandLineobjects 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 CommandLineobject. The returned list may contain more elements if subcommands were registered and these subcommands were initialized by matching command line arguments. If parsing fails, aCommandLine.ParameterExceptionis thrown.- Parameters:
args- the command line arguments to parse- Returns:
- a list with the top-level command and any subcommands initialized by this method
- Throws:
CommandLine.ParameterException- if the specified command line arguments are invalid; useCommandLine.ParameterException.getCommandLine()to get the command or subcommand whose user input was invalid
-
printHelpIfRequested
public static boolean printHelpIfRequested(java.util.List<CommandLine> parsedCommands, java.io.PrintStream out, CommandLine.Help.Ansi ansi)
Helper method that may be useful when processing the list ofCommandLineobjects that result from successfully parsing command line arguments. This method prints out usage help if requested or version help if requested and returnstrue. Otherwise, if none of the specifiedCommandLineobjects have help requested, this method returnsfalse.Note that this method only looks at the
usageHelpandversionHelpattributes. Thehelpattribute is ignored.- Parameters:
parsedCommands- the list ofCommandLineobjects to check if help was requestedout- thePrintStreamto print help to if requestedansi- for printing help messages using ANSI styles and colors- Returns:
trueif help was printed,falseotherwise- Since:
- 2.0
-
execute
private static java.lang.Object execute(CommandLine parsed)
-
parseWithHandler
public java.util.List<java.lang.Object> parseWithHandler(CommandLine.IParseResultHandler handler, java.io.PrintStream out, java.lang.String... args)
Returns the result of callingparseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...)withHelp.Ansi.AUTOand a newCommandLine.DefaultExceptionHandlerin 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
runandcallmethods, 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.RunLasthandler prints help if requested, and otherwise gets the last specified command or subcommand and tries to execute it as aRunnableorCallable.CommandLine.RunFirsthandler prints help if requested, and otherwise executes the top-level command as aRunnableorCallable.CommandLine.RunAllhandler prints help if requested, and otherwise executes all recognized commands and subcommands asRunnableorCallabletasks.CommandLine.DefaultExceptionHandlerprints the error message followed by usage help
- Parameters:
handler- the function that will process the result of successfully parsing the command line argumentsout- thePrintStreamto print help to if requestedargs- the command line arguments- Returns:
- a list of results, or an empty list if there are no results
- Throws:
CommandLine.ExecutionException- if the command line arguments were parsed successfully but a problem occurred while processing the parse results; useCommandLine.ExecutionException.getCommandLine()to get the command or subcommand where processing failed- Since:
- 2.0
- See Also:
CommandLine.RunLast,CommandLine.RunAll
-
parseWithHandlers
public java.util.List<java.lang.Object> parseWithHandlers(CommandLine.IParseResultHandler handler, java.io.PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, java.lang.String... args)
Tries to parse the specified command line arguments, and if successful, delegates the processing of the resulting list ofCommandLineobjects to the specified handler. If the command line arguments were invalid, theParameterExceptionthrown from theparsemethod is caught and passed to the specifiedCommandLine.IExceptionHandler.This is a convenience method intended to offer the same ease of use as the
runandcallmethods, 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.RunLasthandler prints help if requested, and otherwise gets the last specified command or subcommand and tries to execute it as aRunnableorCallable.CommandLine.RunFirsthandler prints help if requested, and otherwise executes the top-level command as aRunnableorCallable.CommandLine.RunAllhandler prints help if requested, and otherwise executes all recognized commands and subcommands asRunnableorCallabletasks.CommandLine.DefaultExceptionHandlerprints the error message followed by usage help
- Parameters:
handler- the function that will process the result of successfully parsing the command line argumentsout- thePrintStreamto print help to if requestedansi- for printing help messages using ANSI styles and colorsexceptionHandler- the function that can handle theParameterExceptionthrown when the command line arguments are invalidargs- the command line arguments- Returns:
- a list of results produced by the
IParseResultHandleror theIExceptionHandler, or an empty list if there are no results - Throws:
CommandLine.ExecutionException- if the command line arguments were parsed successfully but a problem occurred while processing the parse resultCommandLineobjects; useCommandLine.ExecutionException.getCommandLine()to get the command or subcommand where processing failed- Since:
- 2.0
- See Also:
CommandLine.RunLast,CommandLine.RunAll,CommandLine.DefaultExceptionHandler
-
usage
public static void usage(java.lang.Object command, java.io.PrintStream out)Equivalent tonew CommandLine(command).usage(out). Seeusage(PrintStream)for details.- Parameters:
command- the object annotated withCommandLine.Command,CommandLine.OptionandCommandLine.Parametersout- the print stream to print the help message to- Throws:
java.lang.IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public static void usage(java.lang.Object command, java.io.PrintStream out, CommandLine.Help.Ansi ansi)Equivalent tonew CommandLine(command).usage(out, ansi). Seeusage(PrintStream, Help.Ansi)for details.- Parameters:
command- the object annotated withCommandLine.Command,CommandLine.OptionandCommandLine.Parametersout- the print stream to print the help message toansi- whether the usage message should contain ANSI escape codes or not- Throws:
java.lang.IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public static void usage(java.lang.Object command, java.io.PrintStream out, CommandLine.Help.ColorScheme colorScheme)Equivalent tonew CommandLine(command).usage(out, colorScheme). Seeusage(PrintStream, Help.ColorScheme)for details.- Parameters:
command- the object annotated withCommandLine.Command,CommandLine.OptionandCommandLine.Parametersout- the print stream to print the help message tocolorScheme- theColorSchemedefining the styles for options, parameters and commands when ANSI is enabled- Throws:
java.lang.IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public void usage(java.io.PrintStream out)
Delegates tousage(PrintStream, Help.Ansi)with the platform default.- Parameters:
out- the printStream to print to- See Also:
usage(PrintStream, Help.ColorScheme)
-
usage
public void usage(java.io.PrintStream out, CommandLine.Help.Ansi ansi)Delegates tousage(PrintStream, Help.ColorScheme)with the default color scheme.- Parameters:
out- the printStream to print toansi- whether the usage message should include ANSI escape codes or not- See Also:
usage(PrintStream, Help.ColorScheme)
-
usage
public void usage(java.io.PrintStream out, CommandLine.Help.ColorScheme colorScheme)Prints a usage help message for the annotated command class to the specifiedPrintStream. Delegates construction of the usage help message to theCommandLine.Helpinner 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.Commandto 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.Helpobject and use aCommandLine.Help.TextTablewith 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.- Parameters:
out- thePrintStreamto print the usage help message tocolorScheme- theColorSchemedefining the styles for options, parameters and commands when ANSI is enabled
-
printVersionHelp
public void printVersionHelp(java.io.PrintStream out)
Delegates toprintVersionHelp(PrintStream, Help.Ansi)with the platform default.- Parameters:
out- the printStream to print to- Since:
- 0.9.8
- See Also:
printVersionHelp(PrintStream, Help.Ansi)
-
printVersionHelp
public void printVersionHelp(java.io.PrintStream out, CommandLine.Help.Ansi ansi)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream. Each element of the array of version strings is printed on a separate line. Version strings may contain markup for colors and style.- Parameters:
out- the printStream to print toansi- whether the usage message should include ANSI escape codes or not- Since:
- 0.9.8
- See Also:
CommandLine.Command.version(),CommandLine.Option.versionHelp(),isVersionHelpRequested()
-
printVersionHelp
public void printVersionHelp(java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.Object... params)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream. 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.- Parameters:
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 strings- Since:
- 1.0.0
- See Also:
CommandLine.Command.version(),CommandLine.Option.versionHelp(),isVersionHelpRequested()
-
call
public static <C extends java.util.concurrent.Callable<T>,T> T call(C callable, java.io.PrintStream out, java.lang.String... args)Delegates tocall(Callable, PrintStream, Help.Ansi, String...)withCommandLine.Help.Ansi.AUTO.From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the
Callableare caught and rethrown wrapped in anExecutionException.- Type Parameters:
C- the annotated object must implement CallableT- the return type of the most specific command (must implementCallable)- Parameters:
callable- the command to call when parsing succeeds.out- the printStream to print toargs- the command line arguments to parse- Returns:
nullif an error occurred while parsing the command line options, otherwise returns the result of calling the Callable- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- See Also:
call(Callable, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...),CommandLine.RunFirst
-
call
public static <C extends java.util.concurrent.Callable<T>,T> T call(C callable, java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.String... args)Convenience method to allow command line application authors to avoid some boilerplate code in their application. The annotated object needs to implementCallable. 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
parseWithHandlermethod with aCommandLine.RunAllhandler or a custom handler.From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the
Callableare caught and rethrown wrapped in anExecutionException.- Type Parameters:
C- the annotated object must implement CallableT- the return type of the specifiedCallable- Parameters:
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 parse- Returns:
nullif an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- See Also:
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...),CommandLine.RunLast
-
run
public static <R extends java.lang.Runnable> void run(R runnable, java.io.PrintStream out, java.lang.String... args)Delegates torun(Runnable, PrintStream, Help.Ansi, String...)withCommandLine.Help.Ansi.AUTO.From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the
Runnableare caught and rethrown wrapped in anExecutionException.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- the command to run when parsing succeeds.out- the printStream to print toargs- the command line arguments to parse- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- See Also:
run(Runnable, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...),CommandLine.RunFirst
-
run
public static <R extends java.lang.Runnable> void run(R runnable, java.io.PrintStream out, CommandLine.Help.Ansi ansi, java.lang.String... args)Convenience method to allow command line application authors to avoid some boilerplate code in their application. The annotated object needs to implementRunnable. 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
parseWithHandlermethod with aCommandLine.RunAllhandler or a custom handler.From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the
Runnableare caught and rethrown wrapped in anExecutionException.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- 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 parse- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- See Also:
parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...),CommandLine.RunLast
-
registerConverter
public <K> CommandLine registerConverter(java.lang.Class<K> cls, CommandLine.ITypeConverter<K> converter)
Registers the specified type converter for the specified class. When initializing fields annotated withCommandLine.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:
- all primitive types
- all primitive wrapper types: Boolean, Byte, Character, Double, Float, Integer, Long, Short
- any enum
- java.io.File
- java.math.BigDecimal
- java.math.BigInteger
- java.net.InetAddress
- java.net.URI
- java.net.URL
- java.nio.charset.Charset
- java.sql.Time
- java.util.Date
- java.util.UUID
- java.util.regex.Pattern
- StringBuilder
- CharSequence
- String
The specified converter will be registered with this
CommandLineand 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.- Type Parameters:
K- the target type- Parameters:
cls- the target class to convert parameter string values toconverter- the class capable of converting string values to the specified target type- Returns:
- this CommandLine object, to allow method chaining
- See Also:
addSubcommand(String, Object)
-
getSeparator
public java.lang.String getSeparator()
Returns the String that separates option names from option values when parsing command line options. "=" by default.- Returns:
- the String the parser uses to separate option names from option values
-
setSeparator
public CommandLine setSeparator(java.lang.String separator)
Sets the String the parser uses to separate option names from option values to the specified value. The separator may also be set declaratively with theCommandLine.Command.separator()annotation attribute.- Parameters:
separator- the String that separates option names from option values- Returns:
- this
CommandLineobject, to allow method chaining
-
getCommandName
public java.lang.String getCommandName()
Returns the command name (also called program name) displayed in the usage help synopsis. "<main class>" by default.- Returns:
- the command name (also called program name) displayed in the usage
-
setCommandName
public CommandLine setCommandName(java.lang.String commandName)
Sets the command name (also called program name) displayed in the usage help synopsis to the specified value. Note that this method only modifies the usage help message, it does not impact parsing behaviour. The command name may also be set declaratively with theCommandLine.Command.name()annotation attribute.- Parameters:
commandName- command name (also called program name) displayed in the usage help synopsis- Returns:
- this
CommandLineobject, to allow method chaining
-
empty
private static boolean empty(java.lang.String str)
-
empty
private static boolean empty(java.lang.Object[] array)
-
empty
private static boolean empty(CommandLine.Help.Ansi.Text txt)
-
str
private static java.lang.String str(java.lang.String[] arr, int i)
-
isBoolean
private static boolean isBoolean(java.lang.Class<?> type)
-
toCommandLine
private static CommandLine toCommandLine(java.lang.Object obj)
-
isMultiValue
private static boolean isMultiValue(java.lang.reflect.Field field)
-
isMultiValue
private static boolean isMultiValue(java.lang.Class<?> cls)
-
getTypeAttribute
private static java.lang.Class<?>[] getTypeAttribute(java.lang.reflect.Field field)
-
init
static void init(java.lang.Class<?> cls, java.util.List<java.lang.reflect.Field> requiredFields, java.util.Map<java.lang.String,java.lang.reflect.Field> optionName2Field, java.util.Map<java.lang.Character,java.lang.reflect.Field> singleCharOption2Field, java.util.List<java.lang.reflect.Field> positionalParametersFields)
-
validatePositionalParameters
static void validatePositionalParameters(java.util.List<java.lang.reflect.Field> positionalParametersFields)
-
reverse
private static <T> java.util.Stack<T> reverse(java.util.Stack<T> stack)
-
-