1. What is picocli

Picocli is a Java library and mini-framework for creating command line applications with almost no code.

Picocli supports a variety of command line syntax styles including POSIX, GNU, MS-DOS and more.
It 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.

Example usage help message

2. How to Use it

Create a class and annotate its fields or methods with @Option or @Parameters to declare what options and positional parameters your application expects.
While parsing the command line, picocli will initialize these fields based on the command line arguments.
If your class implements Runnable or Callable, you can let picocli kick off your application after parsing is successfully completed.

For applications that cannot use the annotations, there is also a programmatic API for defining what options and positional parameters to expect, and a programmatic API for handling parse results. The programmatic API is not covered in this Quick Guide.

2.1. Example

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
adds usage help and version help options your application.

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 ‘-’ dash.

For example, for the Tar example above, the following command line invocations are equivalent:

3.2. Interactive (Password) Options

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.

3.3. Positional Parameters

Any command line arguments that are not subcommands, options or option parameters are interpreted as positional parameters.

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.

4. 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.

4.1. Type Conversion

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

See the user manual for the full list of built-in types, but in general all primitive types and their Object equivalent,
any enum, and common classes like File, Date, URL, BigDecimal, regex Pattern etc. can be used as is.
Applications running on Java 7 can use Path, and on Java 8 the new java.time classes can be used.

4.2. Collections and Maps

If an option or positional parameter can have multiple values, the field type must be an array, a Collection or a Map.
Any Collection subclass like List, Set, or Queue can be used.

A common requirement is to have options with key-value pairs similar to Java’s system properties, like -Dkey=value.
To achieve this, all you need to do is use a Map field.

Map fields may have any type for their key and value
as long as a type 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:

The following command line would result in four key-value entries in the map:

<command> -uDAYS=3 -u HOURS=23 -u=MINUTES=59 --timeUnit=SECONDS=13

5. Required Arguments

5.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:

5.2. Required Parameters

6. Multiple Values

Multi-valued options and positional parameters are annotated fields that can capture multiple values from the command line.

6.1. Repeated Options

The simplest way to create a multi-valued option is to declare an annotated field whose type is an array, collection or a map.

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

Users may specify the same option multiple times. For example:

<command> -option 111 -option 222 -option 333

Each value is appended to the array or collection.

6.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 Collections and Maps.

@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:

-option 111,222,333

6.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:

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.

7.2. Custom Help Options

Applications can define custom 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.

The markup will be rendered as ANSI escape codes on supported systems.

8.2. Dynamic Version Information

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.

The GitHub project has an
example
implementation that gets the version from the manifest file and another
example
that gets version information from a build-generated version properties file.

9. Usage Help

9.1. Example Usage Message

Picocli makes it easy for your application to generate a usage help message like this:

9.2. Usage Help Message Elements

The various elements of the usage help message are easily customized with annotations.

9.2.1. 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...]

9.2.2. 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:

9.2.6. 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.

9.2.7. 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 in the user manual.

9.2.8. 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 = ":")

9.2.9. Hidden Options and Parameters

Options and Parameters with the hidden attribute set to true will not be shown in the usage help message.
See the user manual for details.

9.2.10. Show Default Values

The default value for an option or positional parameter
can be embedded in the description by specifying the variable ${DEFAULT-VALUE} in the description text.
See the user manual for details.

Similarly, it is possible to embed the completion candidates in the description for an option or positional parameter by
specifying the variable ${COMPLETION-CANDIDATES} in the description text.
See the user manual for details.

9.2.11. Required-Option Marker

Required options can be marked in the option list by the character specified with the requiredOptionMarker attribute.
See the user manual for details.

9.2.12. 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.

The width can also be set programmatically via the CommandLine::setUsageHelpWidth and UsageMessageSpec::width methods.

10. ANSI Colors and Styles

10.1. Colorized Example

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

10.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 1. 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.

10.2.1. More Colors

There are only eight pre-defined named colors, but most terminals support a 256 color indexed palette.

See the More Colors section of the user manual for using these colors as foreground or background colors.

10.2.2. Color Scheme for Fixed Elements

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 and with system properties.
For details, see the Color Scheme section of the user manual.

10.3. Supported Platforms

Picocli will only emit ANSI escape codes on supported platforms.
This includes most Unix and Linux platforms.
See the Windows section of the user manual for the various options available to add coloring support to the Windows command console.

10.4. 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:

11. Subcommands

11.1. Registering Subcommands

Subcommands can be registered programmatically or declaratively

11.1.1. 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());

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.

11.1.2. Declaratively

Subcommands can be registered declaratively with the @Command annotation’s subcommands attribute.

11.3. @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.
The @ParentCommand annotation 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.
The user manual has an example showing how to use the @ParentCommand annotation.

11.4. Usage Help for Subcommands

After registering subcommands, calling the commandLine.usage method will show a usage help message that includes all subcommands in the order they were registered. For example:

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 description for the subcommand in the list is taken from the subcommand’s first header line, or, if the subcommand does not have a header annotation, from the description.

11.4.1. Hidden Subcommands

Commands with the hidden attribute set to true will not be shown in the usage help message of their parent command.
See the Hidden Subcommands section of the user manual for details.

11.4.2. Help Subcommands

12. 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.

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.

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:

13.1. Runnable and Callable

You can omit some of the boilerplate code from your application when the annotated object implements Runnable or Callable:

After

Object result = CommandLine.call(new MyCallable(), args);

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);

13.2. Convenience Methods for Subcommands

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.

The CommandLine::parseWithHandler and CommandLine::parseWithHandlers convenience 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

13.3. Parser Configuration

The picocli parser can be configured to be more strict or lenient.
You can instruct the parser to allow unknown options and other unmatched arguments, disallow POSIX clustered short options, and stop looking for options once a positional parameter or unmatched argument is found.
See the Parser Configuration section of the user manual for details.

14. Tracing

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).