Class CommandLine
- java.lang.Object
-
- picocli.CommandLine
-
public class CommandLine extends Object
CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the command line arguments.
Example
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(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 = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.") private boolean[] verbose; }Use
CommandLineto initialize a domain 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
Another example that implements
Callableand uses theCommandLine.callconvenience API to run in a single line of code:@Command(description = "Prints the checksum (MD5 by default) of a file to STDOUT.", name = "checksum", mixinStandardHelpOptions = true, version = "checksum 3.0") class CheckSum implements Callable<Void> { @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 = "MD5"; public static void main(String[] args) throws Exception { // 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. CommandLine.call(new CheckSum(), args); } @Override public Void call() throws Exception { // your business logic goes here... byte[] fileContents = Files.readAllBytes(file.toPath()); byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents); System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(digest)); return null; } }Classes and Interfaces for Defining a CommandSpec Model
Classes Related to Parsing Command Line Arguments
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classCommandLine.AbstractHandler<R,T extends CommandLine.AbstractHandler<R,T>>Abstract superclass forCommandLine.IParseResultHandler2andCommandLine.IExceptionHandler2implementations.static classCommandLine.AbstractParseResultHandler<R>Command line parse result handler that returns a value.static interfaceCommandLine.CommandAnnotate your class with@Commandwhen you want more control over the format of the generated help message.static classCommandLine.DefaultExceptionHandler<R>Default exception handler that handles invalid user input by printing the exception message, 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 classCommandLine.HelpCommandHelp command that can be installed as a subcommand on all application commands.static interfaceCommandLine.IDefaultValueProviderProvides default value for a command.static interfaceCommandLine.IExceptionHandlerDeprecated.UseCommandLine.IExceptionHandler2instead.static interfaceCommandLine.IExceptionHandler2<R>Classes implementing this interface know how to handleParameterExceptions(usually from invalid user input) andExecutionExceptionsthat occurred while executing theRunnableorCallablecommand.static interfaceCommandLine.IFactoryFactory for instantiating classes that are registered declaratively with annotation attributes, likeCommandLine.Command.subcommands(),CommandLine.Option.converter(),CommandLine.Parameters.converter()andCommandLine.Command.versionProvider().static interfaceCommandLine.IHelpCommandInitializableHelp commands that provide usage help for other commands can implement this interface to be initialized with the information they need.static interfaceCommandLine.IHelpFactoryCreates theCommandLine.Helpinstance used to render the usage help message.static interfaceCommandLine.IHelpSectionRendererRenders a section of the usage help message.static classCommandLine.InitializationExceptionException indicating a problem duringCommandLineinitialization.static interfaceCommandLine.IParseResultHandlerDeprecated.UseCommandLine.IParseResultHandler2instead.static interfaceCommandLine.IParseResultHandler2<R>Represents a function that can process theParseResultobject 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 interfaceCommandLine.IVersionProviderProvides version information for a command.static classCommandLine.MaxValuesExceededExceptionException 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.MixinFields annotated with@Mixinare "expanded" into the current command:@Optionand@Parametersin the mixin class are added to the options and positional parameters of this command.static classCommandLine.ModelThis class provides a namespace for classes and interfaces that model concepts and attributes of command line interfaces in picocli.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 interfaceCommandLine.ParentCommandFields annotated with@ParentCommandwill be initialized with the parent command of the current subcommand.static classCommandLine.ParseResultEncapsulates the result of parsing an array of command line arguments.static classCommandLine.PicocliExceptionBase class of all exceptions thrown bypicocli.CommandLine.static 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.static interfaceCommandLine.SpecFields annotated with@Specwill be initialized with theCommandSpecfor the command the field is part of.static classCommandLine.TypeConversionExceptionException thrown byCommandLine.ITypeConverterimplementations to indicate a String could not be converted.static interfaceCommandLine.UnmatchedFields annotated with@Unmatchedwill be initialized with the list of unmatched command line arguments, if any.static classCommandLine.UnmatchedArgumentExceptionException indicating that a command line argument could not be mapped to any of the fields annotated withCommandLine.OptionorCommandLine.Parameters.
-
Constructor Summary
Constructors Constructor Description CommandLine(Object command)Constructs a newCommandLineinterpreter with the specified object (which may be an annotated user object or aCommandSpec) and a default subcommand factory.CommandLine(Object command, CommandLine.IFactory factory)Constructs a newCommandLineinterpreter with the specified object (which may be an annotated user object or aCommandSpec) and object factory.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description CommandLineaddMixin(String name, Object mixin)Adds the options and positional parameters in the specified mixin to this command.CommandLineaddSubcommand(String name, Object command)Registers a subcommand with the specified name.CommandLineaddSubcommand(String name, Object command, String... aliases)Registers a subcommand with the specified name and all specified aliases.static <C extends Callable<T>,T>
Tcall(C callable, PrintStream out, PrintStream err, 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>
Tcall(C callable, PrintStream out, String... args)Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages andCommandLine.Help.Ansi.AUTO.static <C extends Callable<T>,T>
Tcall(C callable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.static <C extends Callable<T>,T>
Tcall(C callable, String... args)Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static <C extends Callable<T>,T>
Tcall(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, PrintStream err, 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>
Tcall(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, String... args)Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static <C extends Callable<T>,T>
Tcall(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.static <C extends Callable<T>,T>
Tcall(Class<C> callableClass, CommandLine.IFactory factory, String... args)Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static CommandLine.DefaultExceptionHandler<List<Object>>defaultExceptionHandler()Convenience method that returnsnew DefaultExceptionHandler<List<Object>>().CharactergetAtFileCommentChar()Returns the character that starts a single-line comment ornullif all content of argument files should be interpreted as arguments (without comments).<T> TgetCommand()Returns the annotated user object that thisCommandLineinstance was constructed with.static List<Method>getCommandMethods(Class<?> cls, String methodName)Helper to get methods of a class annotated with@Commandvia reflection, optionally filtered by method name (not@Command.name).StringgetCommandName()Returns the command name (also called program name) displayed in the usage help synopsis.CommandLine.Model.CommandSpecgetCommandSpec()Returns theCommandSpecmodel that thisCommandLinewas constructed with.CommandLine.IDefaultValueProvidergetDefaultValueProvider()Returns the default value provider for the command, ornullif none has been set.StringgetEndOfOptionsDelimiter()Returns the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.CommandLine.IHelpFactorygetHelpFactory()Returns theIHelpFactorythat 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.CommandLinegetParent()Returns the command that this is a subcommand of, ornullif this is a top-level command.CommandLine.ParseResultgetParseResult()ResourceBundlegetResourceBundle()Returns the ResourceBundle of this command ornullif no resource bundle is set.StringgetSeparator()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.intgetUsageHelpWidth()Returns the maximum width of the usage help message.StringgetUsageMessage()Similar tousage(PrintStream), but returns the usage help message as a String instead of printing it to thePrintStream.StringgetUsageMessage(CommandLine.Help.Ansi ansi)Similar tousage(PrintStream, Help.Ansi), but returns the usage help message as a String instead of printing it to thePrintStream.StringgetUsageMessage(CommandLine.Help.ColorScheme colorScheme)Similar tousage(PrintStream, Help.ColorScheme), but returns the usage help message as a String instead of printing it to thePrintStream.static Objectinvoke(String methodName, Class<?> cls, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)Convenience method to allow command line application authors to avoid some boilerplate code in their application.static Objectinvoke(String methodName, Class<?> cls, PrintStream out, String... args)Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)with the specified stream for requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static Objectinvoke(String methodName, Class<?> cls, PrintStream out, CommandLine.Help.Ansi ansi, String... args)Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)with the specified stream for requested usage help messages,System.errfor diagnostic error messages, and the specified Ansi mode.static Objectinvoke(String methodName, Class<?> cls, String... args)Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.booleanisCaseInsensitiveEnumValuesAllowed()Returns whether the parser should ignore case when converting arguments toenumvalues.booleanisExpandAtFiles()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.booleanisOverwrittenOptionsAllowed()Returns whether options for single-value fields can be specified multiple times on the command line.booleanisPosixClusteredShortOptionsAllowed()Returns whether the parser accepts clustered short options.booleanisSplitQuotedStrings()Returns whether the parser is allowed to split quoted Strings or not.booleanisStopAtPositional()Returns whether the parser interprets the first positional parameter as "end of options" so the remaining arguments are all treated as positional parameters.booleanisStopAtUnmatched()Returns whether the parser should stop interpreting options and positional parameters as soon as it encounters an unmatched option.booleanisToggleBooleanFlags()Returns whether the value of boolean flag options should be "toggled" when the option is matched.booleanisTrimQuotes()Returns whether the parser should trim quotes from command line arguments before processing them.booleanisUnmatchedArgumentsAllowed()Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.booleanisUnmatchedOptionsArePositionalParams()Returns whether arguments on the command line that resemble an option should be treated as positional parameters.booleanisUsageHelpRequested()Returnstrueif an option annotated withCommandLine.Option.usageHelp()was specified on the command line.booleanisUseSimplifiedAtFiles()Returns whether to use a simplified argument file format that is compatible with JCommander.booleanisVersionHelpRequested()Returnstrueif an option annotated withCommandLine.Option.versionHelp()was specified on the command line.List<CommandLine>parse(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.CommandLine.ParseResultparseArgs(String... args)Parses the specified command line arguments and returns a list ofParseResultwith the options, positional parameters, and subcommands (if any) that were recognized and initialized during the parsing process.<R> RparseWithHandler(CommandLine.IParseResultHandler2<R> handler, String[] args)Returns the result of callingparseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)with a newCommandLine.DefaultExceptionHandlerin addition to the specified parse result handler and the specified command line arguments.List<Object>parseWithHandler(CommandLine.IParseResultHandler handler, PrintStream out, String... args)Deprecated.useparseWithHandler(IParseResultHandler2, String[])instead<R> RparseWithHandlers(CommandLine.IParseResultHandler2<R> handler, CommandLine.IExceptionHandler2<R> exceptionHandler, String... args)List<Object>parseWithHandlers(CommandLine.IParseResultHandler handler, PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, String... args)Deprecated.static <T> TpopulateCommand(T command, String... args)Convenience method that initializes the specified annotated object from the specified command line arguments.static <T> TpopulateSpec(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 booleanprintHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi)Helper method that may be useful when processing the list ofCommandLineobjects that result from successfully parsing command line arguments.static booleanprintHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, CommandLine.Help.ColorScheme colorScheme)Helper method that may be useful when processing the list ofCommandLineobjects that result from successfully parsing command line arguments.static booleanprintHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, CommandLine.Help.Ansi ansi)Deprecated.static booleanprintHelpIfRequested(CommandLine.ParseResult parseResult)Delegates toprintHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)withparseResult.asCommandLineList(), System.out, System.err, Help.Ansi.AUTO.voidprintVersionHelp(PrintStream out)Delegates toprintVersionHelp(PrintStream, Help.Ansi)with the platform default.voidprintVersionHelp(PrintStream out, CommandLine.Help.Ansi ansi)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream.voidprintVersionHelp(PrintStream out, CommandLine.Help.Ansi ansi, Object... params)Prints version information from theCommandLine.Command.version()annotation to the specifiedPrintStream.<K> CommandLineregisterConverter(Class<K> cls, CommandLine.ITypeConverter<K> converter)Registers the specified type converter for the specified class.static <R extends Runnable>
voidrun(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, PrintStream err, 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>
voidrun(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, String... args)Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static <R extends Runnable>
voidrun(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.static <R extends Runnable>
voidrun(Class<R> runnableClass, CommandLine.IFactory factory, String... args)Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.static <R extends Runnable>
voidrun(R runnable, PrintStream out, PrintStream err, 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>
voidrun(R runnable, PrintStream out, String... args)Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages andCommandLine.Help.Ansi.AUTO.static <R extends Runnable>
voidrun(R runnable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.static <R extends Runnable>
voidrun(R runnable, String... args)Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.CommandLinesetAtFileCommentChar(Character atFileCommentChar)Sets the character that starts a single-line comment ornullif all content of argument files should be interpreted as arguments (without comments).CommandLinesetCaseInsensitiveEnumValuesAllowed(boolean newValue)Sets whether the parser should ignore case when converting arguments toenumvalues.CommandLinesetCommandName(String commandName)Sets the command name (also called program name) displayed in the usage help synopsis to the specified value.CommandLinesetDefaultValueProvider(CommandLine.IDefaultValueProvider newValue)Sets a default value provider for the command and sub-commandsCommandLinesetEndOfOptionsDelimiter(String delimiter)Sets the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.CommandLinesetExpandAtFiles(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.CommandLinesetHelpFactory(CommandLine.IHelpFactory helpFactory)Sets a newIHelpFactoryto customize the usage help message.CommandLinesetHelpSectionKeys(List<String> keys)Sets the section keys in the order that the usage help message should render the sections.CommandLinesetHelpSectionMap(Map<String,CommandLine.IHelpSectionRenderer> map)Sets the map of section keys and renderers used to construct the usage help message.CommandLinesetOverwrittenOptionsAllowed(boolean newValue)Sets whether options for single-value fields can be specified multiple times on the command line without aCommandLine.OverwrittenOptionExceptionbeing thrown.CommandLinesetPosixClusteredShortOptionsAllowed(boolean newValue)Sets whether short options like-x -v -f SomeFilecan be clustered together like-xvfSomeFile.CommandLinesetResourceBundle(ResourceBundle bundle)Sets the ResourceBundle containing usage help message strings.CommandLinesetSeparator(String separator)Sets the String the parser uses to separate option names from option values to the specified value.CommandLinesetSplitQuotedStrings(boolean newValue)Sets whether the parser is allowed to split quoted Strings.CommandLinesetStopAtPositional(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.CommandLinesetStopAtUnmatched(boolean newValue)Sets whether the parser should stop interpreting options and positional parameters as soon as it encounters an unmatched option.CommandLinesetToggleBooleanFlags(boolean newValue)Sets whether the value of boolean flag options should be "toggled" when the option is matched.CommandLinesetTrimQuotes(boolean newValue)Sets whether the parser should trim quotes from command line arguments before processing them.CommandLinesetUnmatchedArgumentsAllowed(boolean newValue)Sets whether the end user may specify unmatched arguments on the command line without aCommandLine.UnmatchedArgumentExceptionbeing thrown.CommandLinesetUnmatchedOptionsArePositionalParams(boolean newValue)Sets whether arguments on the command line that resemble an option should be treated as positional parameters.CommandLinesetUsageHelpWidth(int width)Sets the maximum width of the usage help message.CommandLinesetUseSimplifiedAtFiles(boolean simplifiedAtFiles)Sets whether to use a simplified argument file format that is compatible with JCommander.voidusage(PrintStream out)Delegates tousage(PrintStream, Help.Ansi)with the platform default.voidusage(PrintStream out, CommandLine.Help.Ansi ansi)Delegates tousage(PrintStream, Help.ColorScheme)with the default color scheme.voidusage(PrintStream out, CommandLine.Help.ColorScheme colorScheme)Prints a usage help message for the annotated command class to the specifiedPrintStream.voidusage(PrintWriter writer)Delegates tousage(PrintWriter, Help.Ansi)with the platform default.voidusage(PrintWriter writer, CommandLine.Help.Ansi ansi)Similar tousage(PrintStream, Help.Ansi)but with the specifiedPrintWriterinstead of aPrintStream.voidusage(PrintWriter writer, CommandLine.Help.ColorScheme colorScheme)Similar tousage(PrintStream, Help.ColorScheme), but with the specifiedPrintWriterinstead of aPrintStream.static voidusage(Object command, PrintStream out)Equivalent tonew CommandLine(command).usage(out).static voidusage(Object command, PrintStream out, CommandLine.Help.Ansi ansi)Equivalent tonew CommandLine(command).usage(out, ansi).static voidusage(Object command, PrintStream out, CommandLine.Help.ColorScheme colorScheme)Equivalent tonew CommandLine(command).usage(out, colorScheme).
-
-
-
Field Detail
-
VERSION
public static final String VERSION
This is picocli version "3.9.6".- See Also:
- Constant Field Values
-
-
Constructor Detail
-
CommandLine
public CommandLine(Object command)
Constructs a newCommandLineinterpreter with the specified object (which may be an annotated user object or aCommandSpec) and a default subcommand factory.The specified object may be a
CommandSpecobject, or it may be a@Command-annotated user object with@Optionand@Parameters-annotated fields, in which case picocli automatically constructs aCommandSpecfrom this user object.When the
parse(String...)method is called, theCommandSpecobject 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.- Parameters:
command- an annotated user object or aCommandSpecobject to initialize from the command line arguments- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
CommandLine
public CommandLine(Object command, CommandLine.IFactory factory)
Constructs a newCommandLineinterpreter with the specified object (which may be an annotated user object or aCommandSpec) and object factory.The specified object may be a
CommandSpecobject, or it may be a@Command-annotated user object with@Optionand@Parameters-annotated fields, in which case picocli automatically constructs aCommandSpecfrom this user object.If the specified command object is an interface
Classwith@Optionand@Parameters-annotated methods, picocli creates aProxywhose methods return the matched command line values. If the specified command object is a concreteClass, picocli delegates to the factory to get an instance.When the
parse(String...)method is called, theCommandSpecobject 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.- Parameters:
command- an annotated user object or aCommandSpecobject to initialize from the command line argumentsfactory- the factory used to create instances of subcommands, converters, etc., that are registered declaratively with annotation attributes- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation- Since:
- 2.2
-
-
Method Detail
-
getCommandSpec
public CommandLine.Model.CommandSpec getCommandSpec()
Returns theCommandSpecmodel that thisCommandLinewas constructed with.- Returns:
- the
CommandSpecmodel - Since:
- 3.0
-
addMixin
public CommandLine addMixin(String name, Object mixin)
Adds the options and positional parameters in the specified mixin to this command.The specified object may be a
CommandSpecobject, or it may be a user object with@Optionand@Parameters-annotated fields, in which case picocli automatically constructs aCommandSpecfrom this user object.- Parameters:
name- the name by which the mixin object may later be retrievedmixin- an annotated user object or aCommandSpecobject whose options and positional parameters to add to this command- Returns:
- this CommandLine object, to allow method chaining
- Since:
- 3.0
-
getMixins
public Map<String,Object> getMixins()
Returns a map of user objects whose options and positional parameters were added to ("mixed in" with) this command.- Returns:
- a new Map containing the user objects mixed in with this command. If
CommandSpecobjects without user objects were programmatically added, use theunderlying modeldirectly. - Since:
- 3.0
-
addSubcommand
public CommandLine addSubcommand(String name, 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()
-
addSubcommand
public CommandLine addSubcommand(String name, Object command, String... aliases)
Registers a subcommand with the specified name and all specified aliases. See alsoaddSubcommand(String, Object).- 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) subcommandsaliases- zero or more alias names that are also recognized on the command line as this subcommand- Returns:
- this CommandLine object, to allow method chaining
- Since:
- 3.1
- See Also:
addSubcommand(String, Object)
-
getSubcommands
public Map<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 user 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
-
getHelpFactory
public CommandLine.IHelpFactory getHelpFactory()
Returns theIHelpFactorythat is used to construct the usage help message.- Since:
- 3.9
- See Also:
setHelpFactory(IHelpFactory)
-
setHelpFactory
public CommandLine setHelpFactory(CommandLine.IHelpFactory helpFactory)
Sets a newIHelpFactoryto customize the usage help message.- Parameters:
helpFactory- the new help factory. Must be non-null.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.- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.9
-
getHelpSectionKeys
public List<String> getHelpSectionKeys()
Returns the section keys in the order that the usage help message should render the sections. This ordering may be modified withsetSectionKeys. The default keys are (in order):SECTION_KEY_HEADER_HEADINGSECTION_KEY_HEADERSECTION_KEY_SYNOPSIS_HEADINGSECTION_KEY_SYNOPSISSECTION_KEY_DESCRIPTION_HEADINGSECTION_KEY_DESCRIPTIONSECTION_KEY_PARAMETER_LIST_HEADINGSECTION_KEY_PARAMETER_LISTSECTION_KEY_OPTION_LIST_HEADINGSECTION_KEY_OPTION_LISTSECTION_KEY_COMMAND_LIST_HEADINGSECTION_KEY_COMMAND_LISTSECTION_KEY_FOOTER_HEADINGSECTION_KEY_FOOTER
- Since:
- 3.9
-
setHelpSectionKeys
public CommandLine setHelpSectionKeys(List<String> keys)
Sets the section keys in the order that the usage help message should render the sections.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.Use
CommandLine.Model.UsageMessageSpec.sectionKeys(List)to customize a command without affecting its subcommands.- Since:
- 3.9
- See Also:
getHelpSectionKeys()
-
getHelpSectionMap
public Map<String,CommandLine.IHelpSectionRenderer> getHelpSectionMap()
Returns the map of section keys and renderers used to construct the usage help message. The usage help message can be customized by adding, replacing and removing section renderers from this map. Sections can be reordered withsetSectionKeys. Sections that are either not in this map or not in the list returned bygetSectionKeysare omitted.NOTE: By modifying the returned
Map, only the usage help message of this command is affected. UsesetHelpSectionMap(Map)to customize the usage help message for this command and all subcommands.- Since:
- 3.9
-
setHelpSectionMap
public CommandLine setHelpSectionMap(Map<String,CommandLine.IHelpSectionRenderer> map)
Sets the map of section keys and renderers used to construct the usage help message.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.Use
CommandLine.Model.UsageMessageSpec.sectionMap(Map)to customize a command without affecting its subcommands.- Since:
- 3.9
- See Also:
getHelpSectionMap()
-
isToggleBooleanFlags
public boolean isToggleBooleanFlags()
Returns whether the value of boolean flag options should be "toggled" when the option is matched. By default, flags are toggled, so if the value istrueit is set tofalse, and when the value isfalseit is set totrue. If toggling is off, flags are simply set totrue.- Returns:
truethe value of boolean flag options should be "toggled" when the option is matched,falseotherwise- Since:
- 3.0
-
setToggleBooleanFlags
public CommandLine setToggleBooleanFlags(boolean newValue)
Sets whether the value of boolean flag options should be "toggled" when the option is matched. The default istrue.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:
- 3.0
-
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 default isfalse.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
-
isPosixClusteredShortOptionsAllowed
public boolean isPosixClusteredShortOptionsAllowed()
Returns whether the parser accepts clustered short options. The default istrue.- Returns:
trueif short options like-x -v -f SomeFilecan be clustered together like-xvfSomeFile,falseotherwise- Since:
- 3.0
-
setPosixClusteredShortOptionsAllowed
public CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue)
Sets whether short options like-x -v -f SomeFilecan be clustered together like-xvfSomeFile. The default istrue.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:
- 3.0
-
isCaseInsensitiveEnumValuesAllowed
public boolean isCaseInsensitiveEnumValuesAllowed()
Returns whether the parser should ignore case when converting arguments toenumvalues. The default isfalse.- Returns:
trueif enum values can be specified that don't match thetoString()value of the enum constant,falseotherwise; e.g., for an option of type java.time.DayOfWeek, valuesMonDaY,mondayandMONDAYare all recognized iftrue.- Since:
- 3.4
-
setCaseInsensitiveEnumValuesAllowed
public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue)
Sets whether the parser should ignore case when converting arguments toenumvalues. The default isfalse. When set to true, for example, for an option of type java.time.DayOfWeek, valuesMonDaY,mondayandMONDAYare all recognized iftrue.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:
- 3.4
-
isTrimQuotes
public boolean isTrimQuotes()
Returns whether the parser should trim quotes from command line arguments before processing them. The default is read from the system property "picocli.trimQuotes" and will betrueif the property is present and empty, or if its value is "true".- Returns:
trueif the parser should trim quotes from command line arguments before processing them,falseotherwise;- Since:
- 3.7
-
setTrimQuotes
public CommandLine setTrimQuotes(boolean newValue)
Sets whether the parser should trim quotes from command line arguments before processing them. The default is read from the system property "picocli.trimQuotes" and will betrueif the property is set and empty, or if its value is "true".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.Calling this method will cause the "picocli.trimQuotes" property to have no effect.
- Parameters:
newValue- the new setting- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.7
-
isSplitQuotedStrings
public boolean isSplitQuotedStrings()
Returns whether the parser is allowed to split quoted Strings or not. The default isfalse, so quoted strings are treated as a single value that cannot be split.- Returns:
trueif the parser is allowed to split quoted Strings,falseotherwise;- Since:
- 3.7
- See Also:
CommandLine.Model.ArgSpec.splitRegex()
-
setSplitQuotedStrings
public CommandLine setSplitQuotedStrings(boolean newValue)
Sets whether the parser is allowed to split quoted Strings. The default isfalse.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:
- 3.7
- See Also:
CommandLine.Model.ArgSpec.splitRegex()
-
getEndOfOptionsDelimiter
public String getEndOfOptionsDelimiter()
Returns the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.- Returns:
- the end-of-options delimiter. The default is
"--". - Since:
- 3.5
-
setEndOfOptionsDelimiter
public CommandLine setEndOfOptionsDelimiter(String delimiter)
Sets the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.- Parameters:
delimiter- the end-of-options delimiter; must not benull. The default is"--".- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.5
-
getDefaultValueProvider
public CommandLine.IDefaultValueProvider getDefaultValueProvider()
Returns the default value provider for the command, ornullif none has been set.- Returns:
- the default value provider for this command, or
null - Since:
- 3.6
- See Also:
CommandLine.Command.defaultValueProvider(),CommandLine.Model.CommandSpec.defaultValueProvider(),CommandLine.Model.ArgSpec.defaultValueString()
-
setDefaultValueProvider
public CommandLine setDefaultValueProvider(CommandLine.IDefaultValueProvider newValue)
Sets a default value provider for the command and sub-commandsThe specified setting will be registered with this
CommandLineand 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.- Parameters:
newValue- the default value provider to use- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.6
-
isStopAtPositional
public 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. The default isfalse.- Returns:
trueif all values following the first positional parameter should be treated as positional parameters,falseotherwise- Since:
- 2.3
-
setStopAtPositional
public 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. The default isfalse.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-trueif all values following the first positional parameter should be treated as positional parameters,falseotherwise- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 2.3
-
isStopAtUnmatched
public boolean isStopAtUnmatched()
Returns whether the parser should stop interpreting options and positional parameters as soon as it encounters an unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or positional arguments for which there is no available slots (the command has no positional parameters or their size is limited). The default isfalse.Setting this flag to
trueautomatically sets the unmatchedArgumentsAllowed flag totruealso.- Returns:
truewhen an unmatched option should result in the remaining command line arguments to be added to the unmatchedArguments list- Since:
- 2.3
-
setStopAtUnmatched
public CommandLine setStopAtUnmatched(boolean newValue)
Sets whether the parser should stop interpreting options and positional parameters as soon as it encounters an unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or positional arguments for which there is no available slots (the command has no positional parameters or their size is limited). The default isfalse.Setting this flag to
trueautomatically sets the unmatchedArgumentsAllowed flag totruealso.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-truewhen an unmatched option should result in the remaining command line arguments to be added to the unmatchedArguments list- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 2.3
-
isUnmatchedOptionsArePositionalParams
public boolean isUnmatchedOptionsArePositionalParams()
Returns whether arguments on the command line that resemble an option should be treated as positional parameters. The default isfalseand the parser behaviour depends onisUnmatchedArgumentsAllowed().- Returns:
truearguments on the command line that resemble an option should be treated as positional parameters,falseotherwise- Since:
- 3.0
- See Also:
getUnmatchedArguments()
-
setUnmatchedOptionsArePositionalParams
public CommandLine setUnmatchedOptionsArePositionalParams(boolean newValue)
Sets whether arguments on the command line that resemble an option should be treated as positional parameters. The default isfalse.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, arguments on the command line that resemble an option should be treated as positional parameters.- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.0
- See Also:
getUnmatchedArguments(),isUnmatchedArgumentsAllowed()
-
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 default isfalse.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 List<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, 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
-
populateSpec
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();
- Type Parameters:
T- the type of the annotated object- Parameters:
spec- the interface that defines the command specification. This object contains getter methods annotated with@Optionor@Parameters.args- the command line arguments to parse- Returns:
- an instance of the specified annotated interface
- 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:
- 3.1
-
parse
public List<CommandLine> parse(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
-
parseArgs
public CommandLine.ParseResult parseArgs(String... args)
Parses the specified command line arguments and returns a list ofParseResultwith the options, positional parameters, and subcommands (if any) that were recognized and initialized during the parsing process.If parsing fails, a
CommandLine.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
-
getParseResult
public CommandLine.ParseResult getParseResult()
-
defaultExceptionHandler
public static CommandLine.DefaultExceptionHandler<List<Object>> defaultExceptionHandler()
Convenience method that returnsnew DefaultExceptionHandler<List<Object>>().
-
printHelpIfRequested
@Deprecated public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, CommandLine.Help.Ansi ansi)
Deprecated.- Since:
- 2.0
-
printHelpIfRequested
public static boolean printHelpIfRequested(CommandLine.ParseResult parseResult)
Delegates toprintHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)withparseResult.asCommandLineList(), System.out, System.err, Help.Ansi.AUTO.- Since:
- 3.0
-
printHelpIfRequested
public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, 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. If the command is aCommandLine.Command.helpCommand()andrunnableorcallable, that command is executed and this method 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.Implementation note:
When an error occurs while processing the help request, it is recommended custom Help commands throw a
CommandLine.ParameterExceptionwith 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.- Parameters:
parsedCommands- the list ofCommandLineobjects to check if help was requestedout- thePrintStreamto 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 colors- Returns:
trueif help was printed,falseotherwise- Since:
- 3.0
- See Also:
CommandLine.IHelpCommandInitializable
-
printHelpIfRequested
public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, CommandLine.Help.ColorScheme colorScheme)
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. If the command is aCommandLine.Command.helpCommand()andrunnableorcallable, that command is executed and this method 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.Implementation note:
When an error occurs while processing the help request, it is recommended custom Help commands throw a
CommandLine.ParameterExceptionwith 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.- Parameters:
parsedCommands- the list ofCommandLineobjects to check if help was requestedout- thePrintStreamto 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 colors- Returns:
trueif help was printed,falseotherwise- Since:
- 3.6
- See Also:
CommandLine.IHelpCommandInitializable
-
parseWithHandler
@Deprecated public List<Object> parseWithHandler(CommandLine.IParseResultHandler handler, PrintStream out, String... args)
Deprecated.useparseWithHandler(IParseResultHandler2, String[])instead- Since:
- 2.0
-
parseWithHandler
public <R> R parseWithHandler(CommandLine.IParseResultHandler2<R> handler, String[] args)
Returns the result of callingparseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)with a newCommandLine.DefaultExceptionHandlerin 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
runandcallmethods, 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.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
- Type Parameters:
R- the return type of this handler- Parameters:
handler- the function that will handle the result of successfully parsing the command line argumentsargs- the command line arguments- Returns:
- an object resulting from handling the parse result or the exception that occurred while parsing the input
- 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:
- 3.0
- See Also:
CommandLine.RunLast,CommandLine.RunAll
-
parseWithHandlers
@Deprecated public List<Object> parseWithHandlers(CommandLine.IParseResultHandler handler, PrintStream out, CommandLine.Help.Ansi ansi, CommandLine.IExceptionHandler exceptionHandler, String... args)
Deprecated.- Since:
- 2.0
-
parseWithHandlers
public <R> R parseWithHandlers(CommandLine.IParseResultHandler2<R> handler, CommandLine.IExceptionHandler2<R> exceptionHandler, String... args)
Tries to parse the specified command line arguments, and if successful, delegates the processing of the resultingParseResultobject to the specified handler. If the command line arguments were invalid, theParameterExceptionthrown from theparsemethod is caught and passed to the specifiedCommandLine.IExceptionHandler2.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:
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.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
- Type Parameters:
R- the return type of the result handler and exception handler- Parameters:
handler- the function that will handle the result of successfully parsing the command line argumentsexceptionHandler- the function that can handle theParameterExceptionthrown when the command line arguments are invalidargs- the command line arguments- Returns:
- an object resulting from handling the parse result or the exception that occurred while parsing the input
- Throws:
CommandLine.ExecutionException- if the command line arguments were parsed successfully but a problem occurred while processing the parse resultParseResultobject; useCommandLine.ExecutionException.getCommandLine()to get the command or subcommand where processing failed- Since:
- 3.0
- See Also:
CommandLine.RunLast,CommandLine.RunAll,CommandLine.DefaultExceptionHandler
-
usage
public static void usage(Object command, 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:
IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public static void usage(Object command, 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:
IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public static void usage(Object command, 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:
IllegalArgumentException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.Parametersannotation
-
usage
public void usage(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(PrintWriter writer)
Delegates tousage(PrintWriter, Help.Ansi)with the platform default.- Parameters:
writer- the PrintWriter to print to- Since:
- 3.0
- See Also:
usage(PrintWriter, Help.ColorScheme)
-
usage
public void usage(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(PrintWriter writer, CommandLine.Help.Ansi ansi)
Similar tousage(PrintStream, Help.Ansi)but with the specifiedPrintWriterinstead of aPrintStream.- Since:
- 3.0
-
usage
public void usage(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.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.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- See Also:
CommandLine.Model.UsageMessageSpec
-
usage
public void usage(PrintWriter writer, CommandLine.Help.ColorScheme colorScheme)
Similar tousage(PrintStream, Help.ColorScheme), but with the specifiedPrintWriterinstead of aPrintStream.- Since:
- 3.0
-
getUsageMessage
public String getUsageMessage()
Similar tousage(PrintStream), but returns the usage help message as a String instead of printing it to thePrintStream.- Since:
- 3.2
-
getUsageMessage
public String getUsageMessage(CommandLine.Help.Ansi ansi)
Similar tousage(PrintStream, Help.Ansi), but returns the usage help message as a String instead of printing it to thePrintStream.- Since:
- 3.2
-
getUsageMessage
public String getUsageMessage(CommandLine.Help.ColorScheme colorScheme)
Similar tousage(PrintStream, Help.ColorScheme), but returns the usage help message as a String instead of printing it to thePrintStream.- Since:
- 3.2
-
printVersionHelp
public void printVersionHelp(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(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(PrintStream out, CommandLine.Help.Ansi ansi, 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 Callable<T>,T> T call(C callable, String... args)
Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- 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.args- 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- Since:
- 3.0
- See Also:
call(Callable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
call
public static <C extends Callable<T>,T> T call(C callable, PrintStream out, String... args)
Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages andCommandLine.Help.Ansi.AUTO.- 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 the usage help message to when the user requested helpargs- 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:
call(Callable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
call
public static <C extends Callable<T>,T> T call(C callable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Delegates tocall(Callable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.- 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 the usage help message to when the user requested helpansi- the ANSI style to useargs- 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:
call(Callable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
call
public static <C extends Callable<T>,T> T call(C callable, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, 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<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler().useErr(err).useAnsi(ansi), args); T result = results == null || results.isEmpty() ? null : (T) results.get(0); return result;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 theCommandLine.RunAllhandler or a custom handler.Use
call(Class, IFactory, ...)instead of this method if you want to use a factory that performs Dependency Injection.- 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 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- 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- Since:
- 3.0
- See Also:
call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
call
public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, String... args)
Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Type Parameters:
C- the annotated class must implement CallableT- the return type of the most specific command (must implementCallable)- Parameters:
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 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 class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- Since:
- 3.2
- See Also:
call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
call
public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, String... args)
Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Type Parameters:
C- the annotated class must implement CallableT- the return type of the most specific command (must implementCallable)- Parameters:
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 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 class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- Since:
- 3.2
- See Also:
call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
call
public static <C extends Callable<T>,T> T call(Class<C> callableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Delegates tocall(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.- Type Parameters:
C- the annotated class must implement CallableT- the return type of the most specific command (must implementCallable)- Parameters:
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 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 class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- Since:
- 3.2
- See Also:
call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
call
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)
Convenience method to allow command line application authors to avoid some boilerplate code in their application. The specified factory will create an instance of the specifiedcallableClass; use this method instead ofcall(Callable, ...)if you want to use a factory that performs Dependency Injection. The annotated class needs to implementCallable. Calling this method is equivalent to:CommandLine cmd = new CommandLine(callableClass, factory); List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler().useErr(err).useAnsi(ansi), args); T result = results == null || results.isEmpty() ? null : (T) results.get(0); return result;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 theCommandLine.RunAllhandler or a custom handler.- Type Parameters:
C- the annotated class must implement CallableT- the return type of the most specific command (must implementCallable)- Parameters:
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 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 class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Callable throws an exception- Since:
- 3.2
- See Also:
call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),call(Callable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
run
public static <R extends Runnable> void run(R runnable, String... args)
Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- the command to run when parsing succeeds.args- 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- Since:
- 3.0
- See Also:
run(Runnable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(R runnable, PrintStream out, String... args)
Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages andCommandLine.Help.Ansi.AUTO.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- 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 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, PrintStream, Help.Ansi, String...),parseWithHandler(IParseResultHandler2, String[]),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(R runnable, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Delegates torun(Runnable, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- 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 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, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(R runnable, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, 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); cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler().useErr(err).useAnsi(ansi), args);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 theCommandLine.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.Use
run(Class, IFactory, ...)instead of this method if you want to use a factory that performs Dependency Injection.- Type Parameters:
R- the annotated object must implement Runnable- Parameters:
runnable- 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 parse- Throws:
CommandLine.InitializationException- if the specified command object does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.0
- See Also:
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast,run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
-
run
public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, String... args)
Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Type Parameters:
R- the annotated class must implement Runnable- Parameters:
runnableClass- 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 parse- Throws:
CommandLine.InitializationException- if the specified class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.2
- See Also:
run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, String... args)
Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Type Parameters:
R- the annotated class must implement Runnable- Parameters:
runnableClass- 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 parse- Throws:
CommandLine.InitializationException- if the specified class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.2
- See Also:
run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Delegates torun(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)withSystem.errfor diagnostic error messages.- Type Parameters:
R- the annotated class must implement Runnable- Parameters:
runnableClass- 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 parse- Throws:
CommandLine.InitializationException- if the specified class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.2
- See Also:
run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
run
public static <R extends Runnable> void run(Class<R> runnableClass, CommandLine.IFactory factory, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application. The specified factory will create an instance of the specifiedrunnableClass; use this method instead ofrun(Runnable, ...)if you want to use a factory that performs Dependency Injection. The annotated class needs to implementRunnable. Calling this method is equivalent to:CommandLine cmd = new CommandLine(runnableClass, factory); cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler().useErr(err).useAnsi(ansi), args);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 theCommandLine.RunAllhandler or a custom handler.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 class must implement Runnable- Parameters:
runnableClass- 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- Throws:
CommandLine.InitializationException- if the specified class cannot be instantiated by the factory, or does not have aCommandLine.Command,CommandLine.OptionorCommandLine.ParametersannotationCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.2
- See Also:
run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...),run(Runnable, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...),CommandLine.RunLast
-
invoke
public static Object invoke(String methodName, Class<?> cls, String... args)
Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)withSystem.outfor requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Parameters:
methodName- the@Command-annotated method to build aCommandLine.Model.CommandSpecmodel from, and run when parsing succeeds.cls- the class where the@Command-annotated method is declared, or a subclassargs- the command line arguments to parse- Throws:
CommandLine.InitializationException- if the specified method does not have aCommandLine.Commandannotation, or if the specified class contains multiple@Command-annotated methods with the specified nameCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.6
- See Also:
invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
invoke
public static Object invoke(String methodName, Class<?> cls, PrintStream out, String... args)
Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)with the specified stream for requested usage help messages,System.errfor diagnostic error messages, andCommandLine.Help.Ansi.AUTO.- Parameters:
methodName- the@Command-annotated method to build aCommandLine.Model.CommandSpecmodel 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 parse- Throws:
CommandLine.InitializationException- if the specified method does not have aCommandLine.Commandannotation, or if the specified class contains multiple@Command-annotated methods with the specified nameCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.6
- See Also:
invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
invoke
public static Object invoke(String methodName, Class<?> cls, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Delegates toinvoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)with the specified stream for requested usage help messages,System.errfor diagnostic error messages, and the specified Ansi mode.- Parameters:
methodName- the@Command-annotated method to build aCommandLine.Model.CommandSpecmodel 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 parse- Throws:
CommandLine.InitializationException- if the specified method does not have aCommandLine.Commandannotation, or if the specified class contains multiple@Command-annotated methods with the specified nameCommandLine.ExecutionException- if the Runnable throws an exception- Since:
- 3.6
- See Also:
invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...),parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
invoke
public static Object invoke(String methodName, Class<?> cls, PrintStream out, PrintStream err, CommandLine.Help.Ansi ansi, String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application. Constructs aCommandLine.Model.CommandSpecmodel from the@Optionand@Parameters-annotated method parameters of the@Command-annotated method, parses the specified command line arguments and invokes the specified method. Calling this method is equivalent to:Method commandMethod = getCommandMethods(cls, methodName).get(0); CommandLine cmd = new CommandLine(commandMethod); List<Object> list = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler().useErr(err).useAnsi(ansi), args); return list == null ? null : list.get(0);- Parameters:
methodName- the@Command-annotated method to build aCommandLine.Model.CommandSpecmodel 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 parse- Throws:
CommandLine.InitializationException- if the specified method does not have aCommandLine.Commandannotation, or if the specified class contains multiple@Command-annotated methods with the specified nameCommandLine.ExecutionException- if the method throws an exception- Since:
- 3.6
- See Also:
parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
-
getCommandMethods
public static List<Method> getCommandMethods(Class<?> cls, String methodName)
Helper to get methods of a class annotated with@Commandvia reflection, optionally filtered by method name (not@Command.name). Methods have to be either public (inherited) members or be declared bycls, that is "inherited" static or protected methods will not be picked up.- Parameters:
cls- the class to search for methods annotated with@CommandmethodName- if notnull, return only methods whose method name (not@Command.name) equals this string. Ignored ifnull.- Returns:
- the matching command methods, or an empty list
- Since:
- 3.6.0
- See Also:
invoke(String, Class, String...)
-
registerConverter
public <K> CommandLine registerConverter(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 String getSeparator()
Returns the String that separates option names from option values when parsing command line options.- Returns:
- the String the parser uses to separate option names from option values
- See Also:
CommandLine.Model.ParserSpec.separator()
-
setSeparator
public CommandLine setSeparator(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.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:
separator- the String that separates option names from option values- Returns:
- this
CommandLineobject, to allow method chaining - See Also:
CommandLine.Model.ParserSpec.separator(String)
-
getResourceBundle
public ResourceBundle getResourceBundle()
Returns the ResourceBundle of this command ornullif no resource bundle is set.- Since:
- 3.6
- See Also:
CommandLine.Command.resourceBundle(),CommandLine.Model.CommandSpec.resourceBundle()
-
setResourceBundle
public CommandLine setResourceBundle(ResourceBundle bundle)
Sets the ResourceBundle containing usage help message strings.The specified bundle 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 not be impacted. To ensure a setting is applied to all subcommands, call the setter last, after adding subcommands.- Parameters:
bundle- the ResourceBundle containing usage help message strings- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.6
- See Also:
CommandLine.Command.resourceBundle(),CommandLine.Model.CommandSpec.resourceBundle(ResourceBundle)
-
getUsageHelpWidth
public int getUsageHelpWidth()
Returns the maximum width of the usage help message. The default is 80.
-
setUsageHelpWidth
public CommandLine setUsageHelpWidth(int width)
Sets the maximum width of the usage help message. Longer lines are wrapped.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:
width- the maximum width of the usage help message- Returns:
- this
CommandLineobject, to allow method chaining - See Also:
CommandLine.Model.UsageMessageSpec.width(int)
-
getCommandName
public String getCommandName()
Returns the command name (also called program name) displayed in the usage help synopsis.- Returns:
- the command name (also called program name) displayed in the usage
- Since:
- 2.0
- See Also:
CommandLine.Model.CommandSpec.name()
-
setCommandName
public CommandLine setCommandName(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 - Since:
- 2.0
- See Also:
CommandLine.Model.CommandSpec.name(String)
-
isExpandAtFiles
public 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. This property istrueby default.- Returns:
- whether "argument files" or
@filesshould be expanded into their content - Since:
- 2.1
-
setExpandAtFiles
public 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. (trueby default.)- Parameters:
expandAtFiles- whether "argument files" or@filesshould be expanded into their content- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 2.1
-
getAtFileCommentChar
public Character getAtFileCommentChar()
Returns the character that starts a single-line comment ornullif 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.- Returns:
- the character that starts a single-line comment or
null. The default is'#'. - Since:
- 3.5
-
setAtFileCommentChar
public CommandLine setAtFileCommentChar(Character atFileCommentChar)
Sets the character that starts a single-line comment ornullif 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.- Parameters:
atFileCommentChar- the character that starts a single-line comment ornull. The default is'#'.- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.5
-
isUseSimplifiedAtFiles
public boolean isUseSimplifiedAtFiles()
Returns whether to use a simplified argument file format that is compatible with JCommander. In this format, every line (except empty lines and comment lines) is interpreted as a single argument. Arguments containing whitespace do not need to be quoted. When system property"picocli.useSimplifiedAtFiles"is defined, the system property value overrides the programmatically set value.- Returns:
- whether to use a simplified argument file format. The default is
false. - Since:
- 3.9
-
setUseSimplifiedAtFiles
public CommandLine setUseSimplifiedAtFiles(boolean simplifiedAtFiles)
Sets whether to use a simplified argument file format that is compatible with JCommander. In this format, every line (except empty lines and comment lines) is interpreted as a single argument. Arguments containing whitespace do not need to be quoted. When system property"picocli.useSimplifiedAtFiles"is defined, the system property value overrides the programmatically set value.- Parameters:
simplifiedAtFiles- whether to use a simplified argument file format. The default isfalse.- Returns:
- this
CommandLineobject, to allow method chaining - Since:
- 3.9
-
-