1. Introduction

Picocli is a one-file framework for creating Java command line applications with almost zero code.
Supports a variety of command line syntax styles including POSIX, GNU, MS-DOS and more.
Generates highly customizable usage help messages with ANSI colors and styles.
Picocli-based applications can have command line TAB completion showing available options, option parameters and subcommands, for any level of nested subcommands.

A distinguishing feature of picocli is how it aims
to let users run picocli-based applications without requiring picocli as an external dependency:
all the source code lives in a single file, to encourage application authors to include it in source form.

How it works: annotate your class and picocli initializes it from the command line arguments,
converting the input to strongly typed values in the fields of your class.

Here is a small example application that uses the CommandLine.callconvenience method
to do parsing and error handling in one line of code. The mixinStandardHelpOptions attribute is all
that is needed to give your application usage help and version help.

2.2. Interactive (Password) Options

Picocli 3.5 introduced password support: for options and positional parameters marked as interactive, the user is prompted to enter a value on the console.
When running on Java 6 or higher, picocli will use the Console.readPassword API so that user input is not echoed to the console.

2.3. Short Options

Picocli supports POSIX clustered short options:
one or more single-character options without option-arguments, followed by at most one option with an option-argument, can be grouped behind one '-' delimiter.

2.4. Positional Parameters

Any command line arguments that are not subcommands or options (or option parameters) are interpreted as positional parameters.
Positional parameters generally follow the options but from picocli v2.0, positional parameters can be mixed with options on the command line.

Use the (zero-based) index attribute to specify exactly which parameters to capture.
Omitting the index attribute means the field captures all positional parameters.
Array or collection fields can capture multiple values.

The index attribute accepts range values, so an annotation like @Parameters(index="2..4") captures the arguments at index 2, 3 and 4. Range values can be open-ended. For example, @Parameters(index="3..*") captures all arguments from index 3 and up.

2.6. Double dash (--)

When one of the command line arguments is just two dashes without any characters attached (--),
picocli interprets all following arguments as positional parameters, even arguments that match an option name.

A custom delimiter can be configured with CommandLine.setEndOfOptionsDelimiter(String).

2.7. @-files

Users sometimes run into system limitations on the length of a command line when creating a
command line with lots of options or with long arguments for options.

Starting from v2.1.0, picocli supports "argument files" or "@-files".
Argument files are files that themselves contain arguments to the command.
When picocli encounters an argument beginning with the character `@',
it expands the contents of that file into the argument list.

An argument file can include options and positional parameters in any combination.
The arguments within a file can be space-separated or newline-separated.
If an argument contains embedded whitespace, put the whole argument in double or single quotes
("-f=My Files\Stuff.java").

Lines starting with # are comments and are ignored.
The comment character can be configured with CommandLine.setAtFileCommentChar(Character),
and comments can be switched off by setting the comment character to null.

The file may itself contain additional @-file arguments; any such arguments will be processed recursively.

If the file does not exist, or cannot be read, then the argument will be treated literally, and not removed.
Multiple @-files may be specified on the command line. The specified path may be relative (to the current directory) or absolute.

For example, suppose a file with arguments exists at /home/foo/args, with these contents:

# This line is a comment and is ignored.
ABC -option=123
'X Y Z'

A command may be invoked with the @file argument, like this:

java MyCommand @/home/foo/args

The above will be expanded to the contents of the file:

java MyCommand ABC -option=123 "X Y Z"

@-file expansion can be switched off by calling CommandLine::setExpandAtFiles with false.
If turned on, you can still pass a real parameter with an initial '@' character by escaping it
with an additional '@' symbol, e.g. '@@somearg' will become '@somearg' and not be subject to expansion.

This feature is similar to the 'Command Line Argument File' processing supported by gcc, javadoc and javac.
The documentation for these tools shows further examples.

3. Strongly Typed Everything

When command line options and positional parameters are mapped to the annotated fields,
the text value is converted to the type of the annotated field.

3.1. Built-in Types

Out of the box, picocli can convert command line argument strings to a number of common data types.

Most of the built-in types work with Java 5, but picocli also has some default converters for Java 7 types like Path and Java 8 types like Duration, etc. These converters are only available when running on a Java version that supports them. See the below list for details.

any Java primitive type or their wrapper

any enum

String, StringBuilder, CharSequence

java.math.BigDecimal, java.math.BigInteger

java.nio.Charset

java.io.File

java.nio.file.Path (from picocli 2.2, requires Java 7 or higher)

java.net.InetAddress

java.util.regex.Pattern

java.util.Date (for values in "yyyy-MM-dd" format)

java.sql.Time (for values in any of the "HH:mm", "HH:mm:ss", "HH:mm:ss.SSS", or "HH:mm:ss,SSS" formats)

Custom type converters can be registered with the CommandLine.registerConverter(Class<K> cls, ITypeConverter<K> converter) method. All options and positional parameters with the specified type will be converted by the specified converter.

Note on subcommands: the specified converter will be registered with the CommandLine object
and all subcommands (and nested sub-subcommands) that were added before the converter was registered.
Subcommands added later will not have the converter added automatically.
To ensure a custom type converter is available to all subcommands, register the type converter last, after adding subcommands.

3.3. Option-specific Type Converters

Picocli 2.2 added a converter attribute to the @Option and @Parameter annotations. This allows a specific option or positional parameter to use a different converter than would be used by default based on the type of the field.

For example, for a specific field you may want to use a converter that maps the constant names defined in java.sql.Types to the int value of these constants, but any other int fields should not be affected by this and should continue to use the standard int converter that parses numeric values.

This may also be useful for applications that need a custom type converter but want to use the static convenience methods (populateCommand, run, call). The converter annotation does not require a CommandLine instance so it can be used with the static convenience methods.

Type converters declared with the converter attribute need to have a public no-argument constructor to be instantiated, unless a Custom Factory is installed to instantiate classes.

3.4. Arrays, Collections, Maps

Starting from picocli v2.0, the type attribute is no longer necessary for Collection and Map fields:
picocli will infer the collection element type from the generic type.
(The type attribute still works as before, it is just optional in most cases.)

3.4.1. Arrays and Collections

Multiple parameters can be captured together in a single array or Collection field.
The array or collection elements can be any type for which a converter is registered.
For example:

If a collection is returned from a type converter, the contents of the collection are added to the field, not the collection itself.

If the field is null, picocli will instantiate it when the option or positional parameter is matched.
If the Collection type is not a concrete class, picocli will make a best effort to instantiate it based on the field type:
List → ArrayList, OrderedSet → TreeSet, Set → LinkedHashSet, Queue → LinkedList, otherwise, ArrayList.

3.4.2. Maps

Picocli v1.0 introduced support for Map fields similar to Java’s system properties -Dkey=value or Gradle’s project properties -Pmyprop=myvalue.

Map fields may have any type for their key and value
as long as a converter is registered for both the key and the value type.
Key and value types are inferred from the map’s generic type parameters.
For example:

If the field is null, picocli will instantiate it when the option or positional parameter is matched.
If the type is not a concrete class, picocli will instantiate a LinkedHashMap to preserve the input ordering.

On the command line, the key and the value must be separated by a = character.

3.5. Abstract Field Types

The field’s type can be an interface or an abstract class.
The type attribute can be used to control for each field what concrete class the string value should be converted to.
For example:

3.5.1. Maps and Collections with Abstract Elements

For raw maps and collections, or when using generics with unbounded wildcards like Map<?, ?>, or when the type parameters are themselves abstract classes like List<CharSequence> or Map<? extends Number, ? super Number>, there is not enough information to convert to a stronger type. By default, the raw String values are added as is to such collections.

The type attribute can be specified to convert to a stronger type than String. For example:

The above example results in six true values being added to the verbosity array.

5.2. Split Regex

Options and parameters may also specify a split regular expression used to split each option parameter into smaller substrings.
Each of these substrings is converted to the type of the collection or array. See Arrays and Collections.

@Option(names = "-option", split = ",")
int[] values;

A single command line argument like the following will be split up and three int values are added to the array:

5.3. Arity

Sometimes you want to define an option that requires more than one option parameter for each option occurrence on the command line.

The arity attribute lets you control exactly how many parameters to consume for each option occurrence.

The arity attribute can specify an exact number of required parameters, or a range with a minimum and a maximum number of parameters.
The maximum can be an exact upper bound, or it can be "*" to denote any number of parameters. For example:

A MissingParameterException is thrown when fewer than the miminum number of parameters is specified on the command line.

Once the minimum number of parameters is consumed, picocli will check each subsequent command line argument to see whether it is an additional parameter, or a new option. For example:

ArityDemo -s A B C -f 1.0 2.0 /file1 /file2

Option -s has arity "1..*" but instead of consuming all parameters,
the -f argument is recognized as a separate option.

5.4. Default Arity

If no arity is specified, the number of parameters depends on the field’s type.

5.4.1. Option Arity

Table 1. Default arity for @Option fields

@Option Field Type

Default Arity

Notes

boolean

0

Boolean options by default don’t require an option parameter. The field is toggled to its logical negative when the option name is recognized. (This can be switched off.)

Single-valued type (e.g., int, String, File)

1

The option name must be followed by a value.

Multi-valued type (arrays, collections or maps)

1

The option name must be followed by a value.

Prior to picocli v2.0, multi-valued options used to greedily consume as many arguments as possible until
encountering another option or subcommand.
If your application relies on the previous behaviour, you need to explicitly specify an option arity of 0..* when migrating to picocli v2.0.

5.4.2. Positional Parameter Arity

Table 2. Default arity for @Parameters fields

@Parameters Field Type

Default Arity

Notes

boolean

1

Positional parameters of type boolean or Boolean require a value. Only true or false (case insensitive) are valid values.

Single-valued type (e.g., int, String, File)

1

One parameter required for each position.

Multi-valued type (arrays, collections or maps)

0..1

For multi-valued positional parameters (arrays, collections or maps), values are optional, not required.

@Parameters fields are applied to a command line argument if their index matches the argument’s position.
The default index is *, meaning all positions.
A @Parameters field with index = "*" is applied multiple times: once for each positional parameter on the command line.

When a @Parameters field is applied (because its index matches the index of the positional parameter), the field may consume zero, one or more arguments, depending on its arity.

5.5. Optional Values

If an option is defined with arity = "0..1", it may or not have a parameter value.
If such an option is specified without a value on the command line, it is assigned an empty String (starting from picocli 2.3).
If the option is not specified, it keeps its default value. For example:

From picocli 3.0, options with non-String types can specify a type converter to convert the empty String to a strongly typed value when the option is specified without a value.

6. Required Arguments

6.1. Required Options

Options can be marked required to make it mandatory for the user to specify them on the command line. When a required option is not specified, a MissingParameterException is thrown from the parse method. For example:

The following command line arguments would result in an exception complaining that files are missing:

// invalid: missing file parameters
<command> -n 123

The following command line arguments would be accepted:

// valid: both required fields have a value
<command> -n 123 file1

7. Parser Configuration

7.1. Overwriting Single Options

When a single-value option is specified multiple times on the command line, the default parser behaviour is
to throw an OverwrittenOptionException. For example:

@Option(name = "-p") int port;

The following input results in an OverwrittenOptionException:

<command> -p 80 -p 8080

Applications can change this by calling CommandLine.setOverwrittenOptionsAllowed(true) before parsing the input.
When overwritten options are allowed, the last specified value takes effect (the above input will set the port field to 8080)
and a WARN level message is printed to the console. (See Tracing for how to switch off the warnings.)

7.2. Stop At Positional

By default, positional parameters can be mixed with options on the command line, but this is not always desirable.
From picocli 2.3, applications can call CommandLine.setStopAtPositional(true)
to force the parser to treat all values following the first positional parameter as positional parameters.

When this flag is set, the first positional parameter effectively serves as an "end of options" marker.

7.3. Unmatched Input

By default, an UnmatchedArgumentException is thrown when a command line argument cannot be assigned to
an option or positional parameter. For example:

classOnlyThree {
@Parameters(arity = "3") String[] values;
}

The command has only one annotated field, values, and it expects exactly three arguments,
so the following input results in an UnmatchedArgumentException:

java OnlyThree 1 2 3 4 5

Applications can change this by calling CommandLine.setUnmatchedArgumentsAllowed(true) before parsing the input.
When unmatched arguments are allowed, the above input will be accepted and a WARN level message is printed to the console.
(See Tracing for how to switch off the warnings.)

The unmatched argument values can be obtained with the CommandLine.getUnmatchedArguments() method.

7.4. @Unmatched annotation

From picocli 3.0, fields annotated with @Unmatched will be populated with the unmatched arguments.
The field must be of type String[] or List<String>.

If picocli finds a field annotated with @Unmatched, it automatically sets unmatchedArgumentsAllowed to true
so no UnmatchedArgumentException is thrown when a command line argument cannot be assigned to an option or positional parameter.

7.5. Unknown Options

A special case of unmatched input are arguments that resemble options but don’t match any of the defined options.
For example:

The above defines options -a and -b, but what should the parser do with input like this?

<command> -x -a AAA

The -x argument "looks like" an option but there is no -x option defined…​

One possibility is to silently accept such values as positional parameters but this is often not desirable.
From version 1.0, picocli determines if the unmatched argument "resembles an option"
by comparing its leading characters to the prefix characters of the known options.

When the unmatched value is similar to the known options, picocli throws an UnmatchedArgumentException
rather than treating it as a positional parameter.

As usual, CommandLine.setUnmatchedArgumentsAllowed(true) will accept unmatched input and
display a WARN-level message on the console.

Arguments that are not considered similar to the known options are interpreted as positional parameters:

<command> x -a AAA

The above input is treated by the parser as one positional parameter (x) followed by the -a option and its value.

Picocli 3.0 introduced a CommandLine.setUnmatchedOptionsArePositionalParams(boolean) method that can be used to
force the parser to treat arguments resembling an option as positional parameters. For example:

<command> -x -a AAA

When unmatchedOptionsArePositionalParams is set to true, the unknown option -x is treated as a positional parameter.
The next argument -a is recognized and processed as a known option like you would expect.

7.6. Stop At Unmatched

From picocli 2.3, applications can call CommandLine.setStopAtUnmatched(true) to force the parser to stop interpreting
options and positional parameters as soon as it encounters an unmatched argument.

When this flag is set, the first unmatched argument and all subsequent command line arguments are added to the
unmatched arguments list returned by CommandLine.getUnmatchedArguments().

7.7. Toggle Boolean Flags

By default, boolean flag options without a parameter are "toggled" when the option is matched on the command line:
if the previous value was true it is set to false, and when the value was false it is set to true.
From picocli 3.0, applications can call CommandLine.setToggleBooleanFlags(false) to switch this behaviour off.
If toggling is off, flags are simply set to true when the option is matched on the command line.

7.8. POSIX Clustered Short Options

By default, the picocli parser allows POSIX clustered short options, so short options like -x -v -f SomeFile can be clustered together like -xvfSomeFile.
From picocli 3.0, applications can call CommandLine.setPosixClusteredShortOptionsAllowed(false) to enforce that options must be separated with whitespace on the command line.

7.9. Lenient Mode (Incubating)

From picocli 3.2, the parser can be configured to continue parsing invalid input to the end.
When collectErrors is set to true, and a problem occurs during parsing, an Exception is added to the ParseResult.errors() list and parsing continues. The default behaviour (when collectErrors is false) is to abort parsing by throwing the Exception.

This is useful when generating completion candidates on partial input, and is also useful when using picocli in
languages like Clojure where idiomatic error handling does not involve throwing and catching exceptions.

When using this feature, applications are responsible for actively verifying that no errors occurred before executing the business logic. Use with care!

8. Help

8.1. Help Options

Applications can define help options by setting attribute versionHelp = true, usageHelp = true or help = true.
If one of the arguments specified on the command line is a "help" option, picocli will not throw a MissingParameterException when required options are missing.

8.2. Mixin Standard Help Options

Picocli 3.0 introduced the mixinStandardHelpOptions command attribute. When this attribute is set to true, picocli adds a mixin to the
command that adds usageHelp and versionHelp options to the command. For example:

Commands with mixinStandardHelpOptions do not need to explicitly declare fields annotated with @Option(usageHelp = true) and @Option(versionHelp = true) any more.
The usage help message for the above example looks like this:

Usage: <main class> [-hV] [--option=<option>]
--option=<option> Some option.
-h, --help Show this help message and exit.
-V, --version Print version information and exit.

8.3. Built-in Help Subcommand

From 3.0, picocli provides a help subcommand (picocli.CommandLine.HelpCommand) that can be installed as a subcommand
on any application command. It prints usage help for the parent command or sibling subcommands. For example:

For example, the following command prints usage help for a subcommand:

myapp help subcommand

To print usage help for the main command:

myapp help

8.4. Custom Help Subcommands

Custom help subcommands should mark themselves as a help command to tell picocli not to throw a MissingParameterException when required options are missing.

@Command(helpCommand = true)

Picocli 3.0 introduced a new interface picocli.CommandLine.IHelpCommandInitializable that provides custom help
commands with access to the parent command and sibling commands, whether to use Ansi colors or not, and the streams to print the usage help message to.

publicinterfaceIHelpCommandInitializable {
/**
* Initializes this object with the information needed to implement a help command that
* provides usage help for other commands.
*
* @param helpCommandLine provides access to this command's parent and sibling commands
* @param ansi whether to use Ansi colors or not
* @param out the stream to print the usage help message to
* @param err the error stream to print any error messages to
*/void init(CommandLine helpCommandLine, Help.Ansi ansi, PrintStream out, PrintStream err);
}

8.5. Printing Help Automatically

From picocli v2.0, the convenience methods will automatically print usage help and version information
when a help option was specified on the command line (options annotated with the versionHelp or usageHelp attribute - but not the help attribute).

The same holds for the mixinStandardHelpOptions attribute, the built-in HelpCommand and any custom help subcommands marked as a help command.

When using the last three methods, applications need to query the parse result to detect whether usage help or version help
was requested, and invoke CommandLine::usage or CommandLine::printVersionHelp to actually print the requested help message.

9. Version Help

9.1. Static Version Information

Since v0.9.8, applications can specify version information in the version attribute of the @Command annotation.

9.2. Dynamic Version Information

From picocli 2.2, the @Command annotation supports a versionProvider attribute.
Applications may specify a IVersionProvider implementation in this attribute, and picocli will instantiate this class
and invoke it to collect version information.

This is useful when the version of an application should be detected dynamically at runtime.
For example, an implementation may return version information obtained from the JAR manifest, a properties file or some other source.

Custom version providers need to implement the picocli.CommandLine.IVersionProvider interface:

publicinterfaceIVersionProvider {
/**
* Returns version information for a command.
* @return version information (each string in the array is displayed on a separate line)
* @throws Exception an exception detailing what went wrong when obtaining version information
*/String[] getVersion() throwsException;
}

Version providers declared with the versionProvider attribute need to have a public no-argument constructor to be instantiated, unless a Custom Factory is installed to instantiate classes.

The GitHub project has a manifest file-based
example
and a build-generated version properties file-based
example version provider implementation.

10.2. Command Name

In the above example, the program name is taken from the name attribute of the Command annotation:

@Command(name = "cat")

Without a name attribute, picocli will show a generic <main class> in the synopsis:

Usage: <main class> [-AbeEnstTuv] [--help] [--version] [FILE...]

10.3. Parameter Labels

Non-boolean options require a value. The usage help should explain this, and picocli shows the option parameter
in the synopsis and in the option list. By default, the field name is shown in < and > fish brackets.
Use the paramLabel attribute to display a different name. For example:

For demonstration purposes the above example mixes the all-uppercase (e.g., NUM) style label and the fish bracket (e.g., <number>) style labels. For real applications, mixing these label styles should be avoided. An application should consistently use only one style.

10.4. Unsorted Option List

By default the options list displays options in alphabetical order. Use the sortOptions = false attribute to display options in the order they are declared in your class.

@Command(sortOptions = false)

10.5. Abbreviated Synopsis

If a command is very complex and has many options, it is sometimes desirable to suppress details from the synopsis with the abbreviateSynopsis attribute. For example:

10.7. Header and Footer

The header will be shown at the top of the usage help message (before the synopsis). The first header line is also the line shown in the subcommand list if your command has subcommands (see Usage Help for Subcommands).

Use the footer attribute to specify one or more lines to show below the generated usage help message.
Each element of the attribute String array is displayed on a separate line.

The headerHeading and footerHeading may contain format specifiers. See Section Headings.

10.8. Section Headings

Section headers can be used to make usage message layout appear more spacious. Section headings may contain embedded line separator (%n) format specifiers:

The usage help message generated from this class is shown below in Expanded Example.

10.9. Expanded Example

The below example demonstrates what a customized usage message can look like.
Note how section headings with line separators can create a more spacious usage message,
and also that options are listed in declaration order (instead of in alphabetic order).

Usage:
Record changes to the repository.
git commit [-ap] [--fixup=<commit>] [--squash=<commit>] [-c=<commit>]
[-C=<commit>] [-F=<file>] [-m[=<msg>...]] [<files>...]
Description:
Stores the current contents of the index in a new commit along with a log
message from the user describing the changes.
Parameters:
<files> the files to commit
Options:
-a, --all Tell the command to automatically stage files
that have been modified and deleted, but new
files you have not told Git about are not
affected.
-p, --patch Use the interactive patch selection interface to
chose which changes to commit
-C, --reuse-message=<commit>
Take an existing commit object, and reuse the log
message and the authorship information
(including the timestamp) when creating the
commit.
-c, --reedit-message=<commit>
Like -C, but with -c the editor is invoked, so
that the user canfurther edit the commit
message.
--fixup=<commit> Construct a commit message for use with rebase
--autosquash.
--squash=<commit> Construct a commit message for use with rebase
--autosquash. The commitmessage subject line is
taken from the specified commit with a prefix
of "squash! ". Can be used with additional
commit message options (-m/-c/-C/-F).
-F, --file=<file> Take the commit message from the given file. Use
- to read the message from the standard input.
-m, --message[=<msg>...] Use the given <msg> as the commit message. If
multiple -m options are given, their values are
concatenated as separate paragraphs.

The annotated class that this usage help message is generated from is shown in Section Headings.

10.10. Option-Parameter Separators

The separator displayed between options and option parameters (= by default)
in the synopsis and the option list can be configured with the separator attribute.

@Command(separator = "")

the @Command(separator = " ") annotation also affects how picocli parses the command line. See also Custom Separators.

10.11. Hidden Options and Parameters

Options and Parameters with the hidden attribute set to true will not be shown in the usage help message.
This is useful for example when a parameter at some index is captured into multiple fields:
by default each of these fields would be shown in the usage message, which would be confusing for users.

10.12. Show Default Values

10.12.1. ${DEFAULT-VALUE} Variable

From picocli 3.2, it is possible to embed the default values in the description for an option or positional parameter by
specifying the variable ${DEFAULT-VALUE} in the description text.
Picocli uses reflection to get the default values from the annotated fields.

The variable is replaced with the default value regardless of the @Command(showDefaultValues) attribute
and regardless of the @Option(showDefaultValues) or @Parameters(showDefaultValues) attribute.

10.12.3. Legacy Configuration for Displaying Default Values

Prior to picocli 3.2, you need to use the @Command(showDefaultValues = true) attribute to append the default value of
all non-null options and positional parameters to the description column.

Additionally, picocli 3.0 introduced a showDefaultValue attribute to the @Option and @Parameters annotation.
This allows you to specify for each individual option and positional parameter whether its default value should be shown in the usage help.
This attribute accepts three values:

ALWAYS - always display the default value of this option or positional parameter, even null values, regardless what value of showDefaultValues was specified on the command

NEVER - don’t show the default value for this option or positional parameter, regardless what value of showDefaultValues was specified on the command

ON_DEMAND - (this is the default) only show the default value for this option or positional parameter if showDefaultValues was specified on the command

These legacy mechanisms still work but for maximum flexibility use the variables explained above.

10.13. Required-Option Marker

Required options can be marked in the option list by the character specified with the requiredOptionMarker attribute. By default options are not marked because the synopsis shows users which options are required and which are optional. This feature may be useful in combination with abbreviatedSynopsis. For example:

10.14. Usage Width

The default width of the usage help message is 80 characters.
System property picocli.usage.width can be used to specify a custom width.
The minimum width that can be configured is 55 characters.

Picocli 3.0 also introduced programmatic API for this via the CommandLine::setUsageHelpWidth and UsageMessageSpec::width methods.

11. ANSI Colors and Styles

11.1. Colorized Example

Below shows the same usage help message as shown in Expanded Example, with ANSI escape codes enabled.

11.2. Usage Help with Styles and Colors

You can use colors and styles in the descriptions, header and footer
of the usage help message.

Picocli supports a custom markup notation for mixing colors and styles in text,
following a convention introduced by Jansi, where
@| starts a styled section, and |@ ends it.
Immediately following the @| is a comma-separated list of colors and styles, so @|STYLE1[,STYLE2]…​ text|@.
For example:

Table 3. Pre-defined styles and colors that can be used in descriptions and headers using the @|STYLE1[,STYLE2]…​ text|@ notation

Pre-defined Styles

Pre-defined Colors

bold

black

faint

red

underline

green

italic

yellow

blink

blue

reverse

magenta

reset

cyan

white

Colors are applied as foreground colors by default.
You can set background colors by specifying bg(<color>).
For example, @|bg(red) text with red background|@.
Similarly, fg(<color>) explicitly sets the foreground color.

The example below shows how this markup can be used to add colors and styles to the headings and descriptions of a usage help message:

Markup styles cannot be nested, for example: @|bold this @|underline that|@|@ will not work. You can achieve the same by combining styles, for example: @|bold this|@ @|bold,underline that|@ will work fine.

Colors from the 256 color palette can be specified by their index values or by their RGB components.
RGB components must be separated by a semicolon ; and each component must be between 0 and 5, inclusive.

For example, @|bg(0;5;0) text with red=0, green=5, blue=0 background|@,
or @|fg(46) the same color by index, as foreground color|@.

11.4. Configuring Fixed Elements

11.4.1. Color Scheme

Picocli uses a default color scheme for options, parameters and commands.
There are no annotations to modify this color scheme, but it can be changed programmatically.

The below code snippet shows how a custom color scheme can be specified to configure the usage help message style:

11.5. Supported Platforms

Picocli will only emit ANSI escape codes on supported platforms.

11.5.1. Unix and Linux

Most Unix and Linux platforms support ANSI colors natively.
On Windows, when picocli detects it is running under a Unix variant like Cygwin or MSYS(2) on Windows
it will display ANSI colors and styles, otherwise it will not emit ANSI codes.

For Windows version below 10, the Windows command console doesn’t support output coloring by default. One option is to install either Cmder, ConEmu, ANSICON or Mintty (used by default in GitBash and Cygwin) to add coloring support to their Windows command console.

None of the above is mandatory. If not supported, picocli will simply not emit ANSI escape codes, and everything will work without colors.

11.6. Forcing ANSI On/Off

You can force picocli to either always use ANSI codes or never use ANSI codes regardless of the platform:

Setting system property picocli.ansi to true forces picocli to use ANSI codes; setting picocli.ansi to false forces picocli to not use ANSI codes. This may be a useful facility for users of your command line application.

You can decide to force disable or force enable ANSI escape codes programmatically by specifying Ansi.ON or Ansi.OFF when invoking CommandLine.usage.
This overrides the value of system property picocli.ansi. For example:

12. Usage Help API

For further customization of the usage help message, picocli has a Help API.
The Help class provides a number of high-level operations, and a set of components like Layout, TextTable, IOptionRenderer, etc., that can be used to build custom help messages.
Details of the Help API are out of scope for this document, but the following sections give some idea of what is possible.

12.1. Reordering Sections

One thing you may want to do is reorder sections of the usage message or add custom sections.

To reorder sections, you need to use the CommandLine.Help class directly. The CommandLine.usage method implementation looks like this:

In your application, instead of calling CommandLine.usage(new MainClass(), System.err), you can alter the above code to, for example, list subcommands first, then global options and finally the parameters.

12.2. Custom Layout

Picocli also supports unconventional option list layouts. An example of an unconventional layout is the zip application, which shows multiple options per row:

This can be achieved in picocli by subclassing the Help.Layout class.
See the picocli tests for how to achieve this.

13. Subcommands

13.1. Registering Subcommands Programmatically

Subcommands can be registered with the CommandLine.addSubcommand method.
You pass in the name of the command and the annotated object to populate with the subcommand options.
The specified name is used by the parser to recognize subcommands in the command line arguments.

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())
.addSubcommand("clone", new GitClone())
.addSubcommand("diff", new GitDiff())
.addSubcommand("merge", new GitMerge())
.addSubcommand("push", new GitPush())
.addSubcommand("rebase", new GitRebase())
.addSubcommand("tag", new GitTag());

It is strongly recommended that subcommands have a @Command annotation with name and description attributes.

From picocli 3.1, the usage help synopsis of the subcommand shows not only the subcommand name but also the parent command name.
For example, if the git command has a commit subcommand, the usage help for the commit subcommand shows Usage: git commit <options>.

Note on custom type converters: custom type converters are registered only with the subcommands and nested
sub-subcommands that were added before the custom type was registered.
To ensure a custom type converter is available to all subcommands, register the type converter last, after
adding subcommands.

The declared subcommands are automatically instantiated and added when the new CommandLine(new Git()) instance is constructed. The result is the same as if subcommands were added programmatically.

Subcommands referenced in a subcommands attribute must have a @Command annotation with a name attribute, or an exception is thrown from the CommandLine constructor. This name will be used both for generating usage help and for recognizing subcommands when parsing the command line.

Custom type converters registered on a CommandLine instance will apply to all subcommands that were declared on the main command with the subcommands annotation.

Subcommands referenced in a subcommands attribute need to have a public no-argument constructor to be instantiated, unless a Custom Factory is installed to instantiate classes.

13.3. Parsing Subcommands

For this example, we assume we created an alias git that invokes our Java application. This could also be a script or a function that calls our Java program:

alias git='java picocli.Demo$Git'

Next, we call our command with some arguments like this:

git --git-dir=/home/rpopma/picocli status -sb -uno

Where git (actually java picocli.Demo$Git) is the top-level command, followed by a global option and a subcommand status with its own options.

Setting up the parser and parsing the command line could look like this:

13.4. @ParentCommand Annotation

In command line applications with subcommands, options of the top level command are often intended as "global" options that apply to all the subcommands. Prior to picocli 2.2, subcommands had no easy way to access their parent command options unless the parent command made these values available in a global variable.

The @ParentCommand annotation introduced in picocli 2.2 makes it easy for subcommands to access their parent command options: subcommand fields annotated with @ParentCommand are initialized with a reference to the parent command. For example:

The above top-level command has a --directory option that applies to its subcommands.
The List subcommand can use the @ParentCommand annotation to get a reference to the parent command, so it can easily access the parent command options.

The usage help message shows the commands in the order they were registered:

Usage: git [-hV] [--git-dir=<gitDir>]
Git is a fast, scalable, distributed revision control system with an unusually
rich command set that provides both high-level operations and full access to
internals.
--git-dir=<gitDir> Set the path to the repository.
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
Commands:
The most commonly used git commands are:
help Displays help information about the specified command
status Show the working tree status.
commit Record changes to the repository.
add Add file contents to the index.
branch List, create, or delete branches.
checkout Checkout a branch or paths to the working tree.
clone Clone a repository into a new directory.
diff Show changes between commits, commit and working tree, etc.
merge Join two or more development histories together.
push Update remote refs along with associated objects.
rebase Forward-port local commits to the updated upstream head.
tag Create, list, delete or verify a tag object signed with GPG.

The above usage help message is produced from the annotations on the class below:

The usage help message for each subcommand is produced by calling CommandLine.usage(new SubCommand(), out).
For example, see Section Headings for an example subcommand (git commit), which produces the help message shown
in Expanded Example.

From picocli 3.1, the usage help synopsis of the subcommand shows not only the subcommand name but also the parent command name.
For example, if the git command has a commit subcommand, the usage help for the commit subcommand shows Usage: git commit <options>.

13.6. Hidden Subcommands

Commands with the hidden attribute set to true will not be shown in the usage help message of their parent command.

The usage help message for App looks like the below. Note that the bar subcommand is not shown:

Usage: app
Commands:
foo This is a visible subcommand

13.7. Help Subcommands

Commands with the helpCommand attribute set to true are treated as help commands.
When picocli encounters a help command on the command line, required options and required positional parameters of the parent command
are not validated (similar to help options).

14. Reuse

You may find yourself defining the same options, parameters or command attributes in many command line applications.
To reduce duplication, picocli supports both subclassing and mixins as ways to reuse such options and attributes.

For both mechanisms, the first step is to extract these options, parameters and command attributes into a separate class. Below is an example class, ReusableOptions, that we will use in example scenarios in this chapter:

This defines some usage help attributes that give a spacious layout, and a verbosity option that makes the operation more talkative.

14.1. Subclassing

One way to reuse the above option and attributes is to extend the class. Picocli will walk the class hierarchy to check for annotations, so @Options, @Parameters and @Command attributes declared on a superclass are available in all subclasses.

For example, all commands that extend the above sampleReusableOptions class will inherit the --verbose option, and generate a usage help message in the same spacious style. Example code:

14.2. Mixins

Picocli 3.0 introduces the concept of "mixins". Mixins are a convenient alternative to subclassing:
picocli annotations from any class can be added to ("mixed in" with) another command.
This includes options, positional parameters, subcommands and command attributes.
Picocli mixinStandardHelpOptions internally uses a mixin.

A mixin is a separate class with options, positional parameters, subcommands and command attributes
that you want to reuse in other commands.
Mixins can be installed by calling the CommandLine.addMixin method with an object of this class, or annotating a field in your command with @Mixin.

14.2.1. Adding Mixins Programmatically

The below example shows how a mixin can be added programmatically with the CommandLine.addMixin method.
We use the sample ReusableOptions class defined above as the mixin:

14.2.2. @Mixin Annotation

A command can also include a mixin by annotating a field with @Mixin. All picocli annotations found in the mixin class
are added to the command that has a field annotated with @Mixin. For example, again using the sample ReusableOptions class defined above:

In addition to adding the options, subcommands and command attributes of the mixed-in object to the command,
the mixed-in object is also injected into the field annotated with @Mixin, making it trival for the command to reference the mixed-in object if necessary.

Mixins added with the @Mixin annotation can also be accessed via the map returned by CommandLine.getMixins.

14.3. Reuse Combinations

The above mechanisms can be combined in any way. Mixins can be nested, and there is no limitation to how deeply mixins can be nested. A mixin may also inherit options, positional parameters and command attributes from a super class.

An option with the same name should not be defined multiple times or a DuplicateOptionAnnotationsException is thrown during initialization. Positional parameters for the same position may be defined multiple times, they can co-exist.

Command attributes may be defined multiple times, but only one value is preserved. In case a command attribute is defined multiple times, the definition earlier in the following list takes priority over later in the list:

@Command attributes of the command itself

Attributes on the @Mixin commands

Attributes on a @Mixin nested in a @Mixin of the command

Attributes on superclass of nested @Mixin

Attributes on superclass of @Mixin

Attributes on superclass of the command

Attributes on programmatically added mixins

15. Tips & Tricks

15.1. Annotated Methods

From version 3.2, @Option and @Parameter annotations can be added to methods as well as fields of a class.

For concrete classes, annotate "setter" methods (methods that accept a parameter) and when the option is specified on the command line, picocli will invoke the method with the value specified on the command line, converted to the type of the method parameter.

Alternatively, you may annotate "getter-like" methods (methods that return a value) on an interface, and picocli will create an instance of the interface that returns the values specified on the command line, converted to the method return type.

15.1.1. Annotating Methods of an Interface

The @Option and @Parameters annotations can be used on methods of an interface that return a value. For example:

The CommandLine.call method returns the result of the Callable, or null if the command line options were invalid. An error message and a usage help message are printed when the command line options were invalid. Exceptions thrown from the Callable.call method are caught, wrapped in an ExecutionException and rethrown.

When the annotated object implements Runnable, use the run method. For example:

CommandLine.run(new MyRunnable(), args);

If the command class has subcommands, the CommandLine::call and CommandLine::run convenience methods will execute the most specific subcommand on the command line. For example:

In the above example, the subsubcommand is the most specific subcommand, and only the Runnable or Callable associated with that subcommand will be executed by the CommandLine::call and CommandLine::run convenience methods.

15.3. Convenience Methods for Subcommands

Picocli v2.0 introduced the CommandLine::parseWithHandler and CommandLine::parseWithHandlers convenience methods.
These methods are intended to offer the same ease of use as the run and call methods, but with more flexibility and better support for nested subcommands.

The CommandLine::parseWithHandler method will take care of the following:

parse the specified command line arguments

if the input was invalid, delegate to DefaultExceptionHandler, which will print the error message followed by the usage help message

otherwise, if the command line arguments were parsed successfully, let the specified IParseResultHandler2 handle the parse result

Picocli provides some default IParseResultHandler2 implementations for common tasks:

the RunLast handler prints help if requested, and otherwise gets the last specified command or subcommand and tries to execute it as a Runnable or Callable

the RunFirst handler prints help if requested, and otherwise executes the top-level command as a Runnable or Callable

the RunAll handler prints help if requested, and otherwise executes all commands and subcommands that the user specified on the command line as Runnable or Callable tasks

15.4. Stdout or Stderr

From picocli v3.0, the run and call convenience methods follow unix conventions:
print to stdout when the user requested help, and print to stderr when the input was invalid or an unexpected error occurred.

Custom handlers can extend AbstractHandler to facilitate following this convention.
AbstractHandler also provides useOut and useErr methods to allow customizing the target output streams,
and useAnsi to customize the Ansi style to use:

15.5. Exit Code

From picocli v3.0, the built-in parse result handlers (RunFirst, RunLast and RunAll) and exception handler
(DefaultExceptionHandler) can specify an exit code.
If an exit code was specified, the handler terminates the JVM with the specified status code when finished.

Running this command prints the following to stderr and exits the JVM with status code 456.

exit code demo
Usage: <main class>

Custom handlers can extend AbstractHandler to inherit this behaviour.

15.6. @Spec Annotation

Picocli 3.2 introduces a @Spec annotation for injecting the CommandSpec model of the command into a command field.

This is useful when a command needs to use the picocli API, for example to walk the command hierarchy and iterate over its sibling commands.
This complements the @ParentCommand annotation; the @ParentCommand annotation injects a user-defined command object, whereas this annotation injects a picocli class.

15.7. Custom Factory

Declaratively registered subcommands, type converters and version providers must be instantiated somehow. From picocli 2.2, a custom factory can be specified when constructing a CommandLine instance. This allows full control over object creation and opens possibilities for Inversion of Control and Dependency Injection (see next section). For example:

If no factory is specified, a default factory is used. The default factory requires that the classes to instantiate have a public no-argument constructor: it instantiates the class by calling first calling clazz.newInstance(), and if that fails, clazz.getDeclaredConstructor().newInstance().

15.8. Dependency Injection

You can specify a Custom Factory to integrate with a Dependency Injection container.

The below example shows how to create an IFactory implementation with a Guice Injector:

15.9. Boolean Options with Parameters

By default the value of a boolean field is toggled to its logical negative when the field’s option is specified on the command line.

It is possible to let end users explicitly specify "true" or "false" as a parameter for a boolean option by defining an explicit Arity attribute. A boolean option with arity = "0..1" accepts zero to one parameters, arity = "1" means the option must have one parameter. For example:

But trying to specify the -x option without a parameter, or with a value other than "true" or "false" (case insensitive) will result in a ParameterException.

15.10. Hexadecimal Values

Numeric values are interpreted as decimal numbers by default. If you want picocli to be more flexible, you can
register a custom type converter that delegates to the decode method to convert strings to numbers.

The decode method looks at the prefix to determine the radix, so numbers
starting with 0x, 0X or # are interpreted as hexadecimal numbers, numbers starting with 0 are interpreted
as octal numbers, and otherwise the number is interpreted as a decimal number.

15.11. Option-Parameter Separators

15.11.1. Default Separators

Options may take an option parameter (also called option-argument).
For POSIX-style short options (like -f or -c), the option parameter may be attached to the option,
or it may be separated by a space or the separator string (= by default).
That is, all of the below are equivalent:

Long option names (like --file) must be separated from their option parameter by a space or the
separator string (= by default). That is, the first two below examples are valid but the last example is invalid:

// valid (separator between --file and its parameter)
<command> --file output.txt
<command> --file=output.txt
// invalid (picocli will not recognize the --file option when attached to its parameter)
<command> --fileoutput.txt

15.11.2. Custom Separators

The separator string can be customized programmatically or declaratively.

Use the separator attribute of the @Command annotation to declaratively set a separator string:

Specifying system property -Dpicocli.trace without a value will set the trace level to INFO.

DEBUG: Shows details of the decisions made by the parser during command line parsing.

INFO: Shows a high-level overview of what happens during command line parsing.

WARN: The default. Shows warnings instead of errors when lenient parsing is enabled:
when single-value options were specified multiple times (and CommandLine.overwrittenOptionsAllowed is true),
or when command line arguments could not be matched as an option or positional parameter
(and CommandLine.unmatchedArgumentsAllowed is true).

Scripts annotated with @picocli.groovy.PicocliScript are automatically transformed to use
picocli.groovy.PicocliBaseScript as their base class and can also use the @Command annotation to
customize parts of the usage message like command name, description, headers, footers etc.

Before the script body is executed, the PicocliBaseScript base class parses the command line and initializes
@Field variables annotated with @Option or @Parameters.
The script body is executed if the user input was valid and did not request usage help or version information.

When using a Groovy version older than 2.4.7, use this workaround for the Grape bug that causes this error:
java.lang.ClassNotFoundException: # Licensed to the Apache Software Foundation (ASF) under one or more.

22. License

23. Releases

24. Download

You can add picocli as an external dependency to your project, or you can include it as source.
See the source code below. Copy and paste it into a file called CommandLine.java, add it to your project, and enjoy!