public class CommandLine extends Object
CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the command line arguments.
import static picocli.CommandLine.*; @Command(header = "Encrypt FILE(s), or standard input, to standard output or to the output file.") public class Encrypt { @Parameters(type = File.class, description = "Any number of input files") private List<File> files = new ArrayList<File>(); @Option(names = { "-o", "--out" }, description = "Output file (default: print to console)") private File outputFile; @Option(names = { "-v", "--verbose"}, description = "Verbosely list files processed") private boolean verbose; @Option(names = { "-h", "--help", "-?", "-help"}, help = true, description = "Display this help and exit") private boolean help; }
Use CommandLine
to initialize a domain object as follows:
public static void main(String... args) { try { Encrypt encrypt = CommandLine.populateCommand(new Encrypt(), args); if (encrypt.help) { CommandLine.usage(encrypt, System.out); } else { runProgram(encrypt); } } catch (ParameterException ex) { // command line arguments could not be parsed System.err.println(ex.getMessage()); CommandLine.usage(new Encrypt(), 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
Copied and modified from picocli.
Modifier and Type | Class and Description |
---|---|
static interface |
CommandLine.Command
Annotate your class with
@Command when you want more control over the format of the generated help
message. |
static class |
CommandLine.DuplicateOptionAnnotationsException
Exception indicating that multiple fields have been annotated with the same Option name.
|
static class |
CommandLine.Help
A collection of methods and inner classes that provide fine-grained control over the contents and layout of
the usage help message to display to end users when help is requested or invalid input values were specified.
|
static interface |
CommandLine.ITypeConverter<K>
When parsing command line arguments and initializing
fields annotated with
@Option or @Parameters ,
String values can be converted to any type for which a ITypeConverter is registered. |
static class |
CommandLine.MissingParameterException
Exception indicating that a required parameter was not specified.
|
static class |
CommandLine.MissingTypeConverterException
Exception indicating that an annotated field had a type for which no
CommandLine.ITypeConverter was
registered. |
static interface |
CommandLine.Option
Annotate fields in your class with
@Option and picocli will initialize these fields when matching
arguments are specified on the command line. |
static class |
CommandLine.OverwrittenOptionException
Exception indicating that an option for a single-value field has been specified multiple times on the command line.
|
static class |
CommandLine.ParameterException
Exception indicating something went wrong while parsing command line options.
|
static class |
CommandLine.ParameterIndexGapException
Exception indicating that there was a gap in the indices of the fields annotated with
CommandLine.Parameters . |
static interface |
CommandLine.Parameters
Fields annotated with
@Parameters will be initialized with positional parameters. |
static class |
CommandLine.Range
Describes the number of parameters required and accepted by an option or a positional parameter.
|
static class |
CommandLine.UnmatchedArgumentException
Exception indicating that a command line argument could not be mapped to any of the fields annotated with
CommandLine.Option or CommandLine.Parameters . |
Modifier and Type | Field and Description |
---|---|
static String |
VERSION
This is picocli version "0.9.8".
|
Constructor and Description |
---|
CommandLine(Object command)
Constructs a new
CommandLine interpreter with the specified annotated object. |
Modifier and Type | Method and Description |
---|---|
CommandLine |
addSubcommand(String name,
Object command)
Registers a subcommand with the specified name.
|
Object |
getCommand()
Returns the annotated object that this
CommandLine instance was constructed with. |
CommandLine |
getParent()
Returns the command that this is a subcommand of, or
null if this is a top-level command. |
String |
getSeparator()
Returns the String that separates option names from option values when parsing command line options.
|
Map<String,CommandLine> |
getSubcommands()
Returns a map with the subcommands registered on this instance.
|
List<String> |
getUnmatchedArguments()
Returns the list of unmatched command line arguments, if any.
|
boolean |
isOverwrittenOptionsAllowed()
Returns whether options for single-value fields can be specified multiple times on the command line.
|
boolean |
isUnmatchedArgumentsAllowed()
Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.
|
boolean |
isUsageHelpRequested()
Returns
true if an option annotated with CommandLine.Option.usageHelp() was specified on the command line. |
boolean |
isVersionHelpRequested()
Returns
true if an option annotated with CommandLine.Option.versionHelp() was specified on the command line. |
List<CommandLine> |
parse(String... args)
Initializes the annotated object that this
CommandLine was constructed with as well as
possibly any registered commands, based on the specified command line arguments,
and returns a list of all commands and subcommands that were initialized by this method. |
static <T> T |
populateCommand(T command,
String... args)
Convenience method that initializes the specified annotated object from the specified command line arguments.
|
void |
printVersionHelp(PrintStream out)
Delegates to
printVersionHelp(PrintStream, Help.Ansi) with the platform default. |
void |
printVersionHelp(PrintStream out,
CommandLine.Help.Ansi ansi)
Prints version information from the
CommandLine.Command.version() annotation to the specified PrintStream . |
<K> CommandLine |
registerConverter(Class<K> cls,
CommandLine.ITypeConverter<K> converter)
Registers the specified type converter for the specified class.
|
static <R extends Runnable> |
run(R command,
PrintStream out,
CommandLine.Help.Ansi ansi,
String... args)
Convenience method to allow command line application authors to avoid some boilerplate code in their application.
|
static <R extends Runnable> |
run(R command,
PrintStream out,
String... args)
Delegates to
run(Runnable, PrintStream, Help.Ansi, String...) with CommandLine.Help.Ansi.AUTO . |
CommandLine |
setOverwrittenOptionsAllowed(boolean newValue)
Sets whether options for single-value fields can be specified multiple times on the command line without a
CommandLine.OverwrittenOptionException being thrown. |
void |
setSeparator(String separator)
Sets the String the parser uses to separate option names from option values to the specified value.
|
CommandLine |
setUnmatchedArgumentsAllowed(boolean newValue)
Sets whether the end user may specify unmatched arguments on the command line without a
CommandLine.UnmatchedArgumentException being thrown. |
static void |
usage(Object command,
PrintStream out)
Equivalent to
new CommandLine(command).usage(out) . |
static void |
usage(Object command,
PrintStream out,
CommandLine.Help.Ansi ansi)
Equivalent to
new CommandLine(command).usage(out, ansi) . |
static void |
usage(Object command,
PrintStream out,
CommandLine.Help.ColorScheme colorScheme)
Equivalent to
new CommandLine(command).usage(out, colorScheme) . |
void |
usage(PrintStream out)
Delegates to
usage(PrintStream, Help.Ansi) with the platform default. |
void |
usage(PrintStream out,
CommandLine.Help.Ansi ansi)
Delegates to
usage(PrintStream, Help.ColorScheme) with the default color scheme. |
void |
usage(PrintStream out,
CommandLine.Help.ColorScheme colorScheme)
Prints a usage help message for the annotated command class to the specified
PrintStream . |
public static final String VERSION
public CommandLine(Object command)
CommandLine
interpreter with the specified annotated object.
When the parse(String...)
method is called, fields of the specified object that are annotated
with @Option
or @Parameters
will be initialized based on command line arguments.command
- the object to initialize from the command line argumentsIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic CommandLine addSubcommand(String name, Object command)
CommandLine commandLine = new CommandLine(new Git()) .addSubcommand("status", new GitStatus()) .addSubcommand("commit", new GitCommit(); .addSubcommand("add", new GitAdd()) .addSubcommand("branch", new GitBranch()) .addSubcommand("checkout", new GitCheckout()) //... ;
The specified object can be an annotated object or a
CommandLine
instance with its own nested subcommands. For example:
CommandLine commandLine = new CommandLine(new MainCommand()) .addSubcommand("cmd1", new ChildCommand1()) // subcommand .addSubcommand("cmd2", new ChildCommand2()) .addSubcommand("cmd3", new CommandLine(new ChildCommand3()) // subcommand with nested sub-subcommands .addSubcommand("cmd3sub1", new GrandChild3Command1()) .addSubcommand("cmd3sub2", new GrandChild3Command2()) .addSubcommand("cmd3sub3", new CommandLine(new GrandChild3Command3()) // deeper nesting .addSubcommand("cmd3sub3sub1", new GreatGrandChild3Command3_1()) .addSubcommand("cmd3sub3sub2", new GreatGrandChild3Command3_2()) ) );
The default type converters are available on all subcommands and nested sub-subcommands, but custom type converters are registered only with the subcommand hierarchy as it existed when the custom type was registered. To ensure a custom type converter is available to all subcommands, register the type converter last, after adding subcommands.
name
- the string to recognize on the command line as a subcommandcommand
- the object to initialize with command line arguments following the subcommand name.
This may be a CommandLine
instance with its own (nested) subcommandsregisterConverter(Class, ITypeConverter)
public Map<String,CommandLine> getSubcommands()
public CommandLine getParent()
null
if this is a top-level command.null
if this is a top-level commandaddSubcommand(String, Object)
,
CommandLine.Command.subcommands()
public Object getCommand()
CommandLine
instance was constructed with.CommandLine
instance was constructed withpublic boolean isUsageHelpRequested()
true
if an option annotated with CommandLine.Option.usageHelp()
was specified on the command line.CommandLine.Option.usageHelp()
public boolean isVersionHelpRequested()
true
if an option annotated with CommandLine.Option.versionHelp()
was specified on the command line.CommandLine.Option.versionHelp()
public boolean isOverwrittenOptionsAllowed()
false
and a CommandLine.OverwrittenOptionException
is thrown if this happens.
When true
, the last specified value is retained.true
if options for single-value fields can be specified multiple times on the command line, false
otherwisepublic CommandLine setOverwrittenOptionsAllowed(boolean newValue)
CommandLine.OverwrittenOptionException
being thrown.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic boolean isUnmatchedArgumentsAllowed()
false
and a CommandLine.UnmatchedArgumentException
is thrown if this happens.
When true
, the last unmatched arguments are available via the getUnmatchedArguments()
method.true
if the end use may specify unmatched arguments on the command line, false
otherwisegetUnmatchedArguments()
public CommandLine setUnmatchedArgumentsAllowed(boolean newValue)
CommandLine.UnmatchedArgumentException
being thrown.
The specified setting will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
later will have the default setting. To ensure a setting is applied to all
subcommands, call the setter last, after adding subcommands.
newValue
- the new settingCommandLine
object, to allow method chainingpublic List<String> getUnmatchedArguments()
isUnmatchedArgumentsAllowed()
public static <T> T populateCommand(T command, String... args)
Convenience method that initializes the specified annotated object from the specified command line arguments.
This is equivalent to
CommandLine cli = new CommandLine(command); cli.parse(args); return command;
T
- the type of the annotated objectcommand
- the object to initialize. This object contains fields annotated with
@Option
or @Parameters
.args
- the command line arguments to parseIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationCommandLine.ParameterException
- if the specified command line arguments are invalidpublic List<CommandLine> parse(String... args)
Initializes the annotated object that this CommandLine
was constructed with as well as
possibly any registered commands, based on the specified command line arguments,
and returns a list of all commands and subcommands that were initialized by this method.
args
- the command line arguments to parseCommandLine.ParameterException
- if the specified command line arguments are invalidpublic static void usage(Object command, PrintStream out)
new CommandLine(command).usage(out)
. See usage(PrintStream)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message toIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic static void usage(Object command, PrintStream out, CommandLine.Help.Ansi ansi)
new CommandLine(command).usage(out, ansi)
.
See usage(PrintStream, Help.Ansi)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message toansi
- whether the usage message should contain ANSI escape codes or notIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic static void usage(Object command, PrintStream out, CommandLine.Help.ColorScheme colorScheme)
new CommandLine(command).usage(out, colorScheme)
.
See usage(PrintStream, Help.ColorScheme)
for details.command
- the object annotated with CommandLine.Command
, CommandLine.Option
and CommandLine.Parameters
out
- the print stream to print the help message tocolorScheme
- the ColorScheme
defining the styles for options, parameters and commands when ANSI is enabledIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic void usage(PrintStream out)
usage(PrintStream, Help.Ansi)
with the platform default.out
- the printStream to print tousage(PrintStream, Help.ColorScheme)
public void usage(PrintStream out, CommandLine.Help.Ansi ansi)
usage(PrintStream, Help.ColorScheme)
with the default color scheme.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notusage(PrintStream, Help.ColorScheme)
public void usage(PrintStream out, CommandLine.Help.ColorScheme colorScheme)
PrintStream
.
Delegates construction of the usage help message to the CommandLine.Help
inner class and is equivalent to:
Help help = new Help(command).addAllSubcommands(getSubcommands()); StringBuilder sb = new StringBuilder() .append(help.headerHeading()) .append(help.header()) .append(help.synopsisHeading()) //e.g. Usage: .append(help.synopsis()) //e.g. <main class> [OPTIONS] <command> [COMMAND-OPTIONS] [ARGUMENTS] .append(help.descriptionHeading()) //e.g. %nDescription:%n%n .append(help.description()) //e.g. {"Converts foos to bars.", "Use options to control conversion mode."} .append(help.parameterListHeading()) //e.g. %nPositional parameters:%n%n .append(help.parameterList()) //e.g. [FILE...] the files to convert .append(help.optionListHeading()) //e.g. %nOptions:%n%n .append(help.optionList()) //e.g. -h, --help displays this help and exits .append(help.commandListHeading()) //e.g. %nCommands:%n%n .append(help.commandList()) //e.g. add adds the frup to the frooble .append(help.footerHeading()) .append(help.footer()); out.print(sb);
Annotate your class with CommandLine.Command
to control many aspects of the usage help message, including
the program name, text of section headings and section contents, and some aspects of the auto-generated sections
of the usage help message.
To customize the auto-generated sections of the usage help message, like how option details are displayed,
instantiate a CommandLine.Help
object and use a CommandLine.Help.TextTable
with more of fewer columns, a custom
layout, and/or a custom option renderer
for ultimate control over which aspects of an Option or Field are displayed where.
out
- the PrintStream
to print the usage help message tocolorScheme
- the ColorScheme
defining the styles for options, parameters and commands when ANSI is enabledpublic void printVersionHelp(PrintStream out)
printVersionHelp(PrintStream, Help.Ansi)
with the platform default.out
- the printStream to print toprintVersionHelp(PrintStream, Help.Ansi)
public void printVersionHelp(PrintStream out, CommandLine.Help.Ansi ansi)
CommandLine.Command.version()
annotation to the specified PrintStream
.
Each element of the array of version strings is printed on a separate line. Version strings may contain
markup for colors and style.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notCommandLine.Command.version()
,
CommandLine.Option.versionHelp()
,
isVersionHelpRequested()
public static <R extends Runnable> void run(R command, PrintStream out, String... args)
run(Runnable, PrintStream, Help.Ansi, String...)
with CommandLine.Help.Ansi.AUTO
.R
- the annotated object must implement Runnablecommand
- the command to run when parsing succeeds.out
- the printStream to print toargs
- the command line arguments to parseIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationrun(Runnable, PrintStream, Help.Ansi, String...)
public static <R extends Runnable> void run(R command, PrintStream out, CommandLine.Help.Ansi ansi, String... args)
Runnable
. Calling this method is equivalent to:
CommandLine cmd = new CommandLine(command); try { cmd.parse(args); } catch (Exception ex) { System.err.println(ex.getMessage()); cmd.usage(out, ansi); return; } command.run();Note that this method is not suitable for commands with subcommands.
R
- the annotated object must implement Runnablecommand
- the command to run when parsing succeeds.out
- the printStream to print toansi
- whether the usage message should include ANSI escape codes or notargs
- the command line arguments to parseIllegalArgumentException
- if the specified command object does not have a CommandLine.Command
, CommandLine.Option
or CommandLine.Parameters
annotationpublic <K> CommandLine registerConverter(Class<K> cls, CommandLine.ITypeConverter<K> converter)
CommandLine.Option
, the field's type is used as a lookup key to find the associated type converter, and this
type converter converts the original command line argument string value to the correct type.
Java 8 lambdas make it easy to register custom type converters:
commandLine.registerConverter(java.nio.file.Path.class, s -> java.nio.file.Paths.get(s)); commandLine.registerConverter(java.time.Duration.class, s -> java.time.Duration.parse(s));
Built-in type converters are pre-registered for the following java 1.5 types:
The specified converter will be registered with this CommandLine
and the full hierarchy of its
subcommands and nested sub-subcommands at the moment the converter is registered. Subcommands added
later will not have this converter added automatically. To ensure a custom type converter is available to all
subcommands, register the type converter last, after adding subcommands.
K
- the target typecls
- the target class to convert parameter string values toconverter
- the class capable of converting string values to the specified target typeaddSubcommand(String, Object)
public String getSeparator()
'='
by default.public void setSeparator(String separator)
separator
- the String that separates option names from option valuesCopyright © 1999-2018 The Apache Software Foundation. All Rights Reserved.
Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, the Apache Logging project logo, and the Apache Log4j logo are trademarks of The Apache Software Foundation.