Class CommandLine


  • public class CommandLine
    extends Object

    CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the command line arguments.

    Example

    import static picocli.CommandLine.*;
    
     @Command(header = "Encrypt FILE(s), or standard input, to standard output or to the output file.",
              version = "v1.2.3")
     public class Encrypt {
    
         @Parameters(type = File.class, description = "Any number of input files")
         private List<File> files = new ArrayList<File>();
    
         @Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
         private File outputFile;
    
         @Option(names = { "-v", "--verbose"}, description = "Verbosely list files processed")
         private boolean verbose;
    
         @Option(names = { "-h", "--help", "-?", "-help"}, usageHelp = true, description = "Display this help and exit")
         private boolean help;
    
         @Option(names = { "-V", "--version"}, versionHelp = true, description = "Display version info and exit")
         private boolean versionHelp;
     }
     

    Use CommandLine to initialize a domain object as follows:

     public static void main(String... args) {
         Encrypt encrypt = new Encrypt();
         try {
             List<CommandLine> parsedCommands = new CommandLine(encrypt).parse(args);
             if (!CommandLine.printHelpIfRequested(parsedCommands, System.err, Help.Ansi.AUTO)) {
                 runProgram(encrypt);
             }
         } catch (ParameterException ex) { // command line arguments could not be parsed
             System.err.println(ex.getMessage());
             ex.getCommandLine().usage(System.err);
         }
     }
     

    Invoke the above program with some command line arguments. The below are all equivalent:

     --verbose --out=outfile in1 in2
     --verbose --out outfile in1 in2
     -v --out=outfile in1 in2
     -v -o outfile in1 in2
     -v -o=outfile in1 in2
     -vo outfile in1 in2
     -vo=outfile in1 in2
     -v -ooutfile in1 in2
     -vooutfile in1 in2
     
    • Method Detail

      • addSubcommand

        public CommandLine addSubcommand​(String name,
                                         Object command)
        Registers a subcommand with the specified name. For example:
         CommandLine commandLine = new CommandLine(new Git())
                 .addSubcommand("status",   new GitStatus())
                 .addSubcommand("commit",   new GitCommit();
                 .addSubcommand("add",      new GitAdd())
                 .addSubcommand("branch",   new GitBranch())
                 .addSubcommand("checkout", new GitCheckout())
                 //...
                 ;
         

        The specified object can be an annotated object or a 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.

        See also the CommandLine.Command.subcommands() annotation to register subcommands declaratively.

        Parameters:
        name - the string to recognize on the command line as a subcommand
        command - the object to initialize with command line arguments following the subcommand name. This may be a CommandLine instance with its own (nested) subcommands
        Returns:
        this CommandLine object, to allow method chaining
        Since:
        0.9.7
        See Also:
        registerConverter(Class, ITypeConverter), CommandLine.Command.subcommands()
      • getSubcommands

        public Map<String,​CommandLine> getSubcommands()
        Returns a map with the subcommands registered on this instance.
        Returns:
        a map with the registered subcommands
        Since:
        0.9.7
      • getCommand

        public <T> T getCommand()
        Returns the annotated object that this CommandLine instance was constructed with.
        Type Parameters:
        T - the type of the variable that the return value is being assigned to
        Returns:
        the annotated object that this CommandLine instance was constructed with
        Since:
        0.9.7
      • isOverwrittenOptionsAllowed

        public boolean isOverwrittenOptionsAllowed()
        Returns whether options for single-value fields can be specified multiple times on the command line. The default is false and a CommandLine.OverwrittenOptionException is thrown if this happens. When true, the last specified value is retained.
        Returns:
        true if options for single-value fields can be specified multiple times on the command line, false otherwise
        Since:
        0.9.7
      • setOverwrittenOptionsAllowed

        public CommandLine setOverwrittenOptionsAllowed​(boolean newValue)
        Sets whether options for single-value fields can be specified multiple times on the command line without a 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.

        Parameters:
        newValue - the new setting
        Returns:
        this CommandLine object, to allow method chaining
        Since:
        0.9.7
      • isUnmatchedArgumentsAllowed

        public boolean isUnmatchedArgumentsAllowed()
        Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields. The default is false and a CommandLine.UnmatchedArgumentException is thrown if this happens. When true, the last unmatched arguments are available via the getUnmatchedArguments() method.
        Returns:
        true if the end use may specify unmatched arguments on the command line, false otherwise
        Since:
        0.9.7
        See Also:
        getUnmatchedArguments()
      • setUnmatchedArgumentsAllowed

        public CommandLine setUnmatchedArgumentsAllowed​(boolean newValue)
        Sets whether the end user may specify unmatched arguments on the command line without a 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.

        Parameters:
        newValue - the new setting. When true, the last unmatched arguments are available via the getUnmatchedArguments() method.
        Returns:
        this CommandLine object, to allow method chaining
        Since:
        0.9.7
        See Also:
        getUnmatchedArguments()
      • getUnmatchedArguments

        public List<String> getUnmatchedArguments()
        Returns the list of unmatched command line arguments, if any.
        Returns:
        the list of unmatched command line arguments or an empty list
        Since:
        0.9.7
        See Also:
        isUnmatchedArgumentsAllowed()
      • populateCommand

        public static <T> T populateCommand​(T command,
                                            String... args)

        Convenience method that initializes the specified annotated object from the specified command line arguments.

        This is equivalent to

         CommandLine cli = new CommandLine(command);
         cli.parse(args);
         return command;
         
        Type Parameters:
        T - the type of the annotated object
        Parameters:
        command - the object to initialize. This object contains fields annotated with @Option or @Parameters.
        args - the command line arguments to parse
        Returns:
        the specified annotated object
        Throws:
        CommandLine.InitializationException - if the specified command object does not have a CommandLine.Command, CommandLine.Option or CommandLine.Parameters annotation
        CommandLine.ParameterException - if the specified command line arguments are invalid
        Since:
        0.9.7
      • parse

        public List<CommandLine> parse​(String... args)
        Parses the specified command line arguments and returns a list of CommandLine objects representing the top-level command and any subcommands (if any) that were recognized and initialized during the parsing process.

        If parsing succeeds, the first element in the returned list is always this CommandLine object. The returned list may contain more elements if subcommands were registered and these subcommands were initialized by matching command line arguments. If parsing fails, a CommandLine.ParameterException is thrown.

        Parameters:
        args - the command line arguments to parse
        Returns:
        a list with the top-level command and any subcommands initialized by this method
        Throws:
        CommandLine.ParameterException - if the specified command line arguments are invalid; use CommandLine.ParameterException.getCommandLine() to get the command or subcommand whose user input was invalid
      • printHelpIfRequested

        public static boolean printHelpIfRequested​(List<CommandLine> parsedCommands,
                                                   PrintStream out,
                                                   CommandLine.Help.Ansi ansi)
        Helper method that may be useful when processing the list of CommandLine objects that result from successfully parsing command line arguments. This method prints out usage help if requested or version help if requested and returns true. Otherwise, if none of the specified CommandLine objects have help requested, this method returns false.

        Note that this method only looks at the usageHelp and versionHelp attributes. The help attribute is ignored.

        Parameters:
        parsedCommands - the list of CommandLine objects to check if help was requested
        out - the PrintStream to print help to if requested
        ansi - for printing help messages using ANSI styles and colors
        Returns:
        true if help was printed, false otherwise
        Since:
        2.0
      • parseWithHandler

        public List<Object> parseWithHandler​(CommandLine.IParseResultHandler handler,
                                             PrintStream out,
                                             String... args)
        Returns the result of calling parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) with Help.Ansi.AUTO and a new CommandLine.DefaultExceptionHandler in addition to the specified parse result handler, PrintStream, and the specified command line arguments.

        This is a convenience method intended to offer the same ease of use as the run and call methods, but with more flexibility and better support for nested subcommands.

        Calling this method roughly expands to:

         try {
             List<CommandLine> parsedCommands = parse(args);
             return parseResultsHandler.handleParseResult(parsedCommands, out, Help.Ansi.AUTO);
         } catch (ParameterException ex) {
             return new DefaultExceptionHandler().handleException(ex, out, ansi, args);
         }
         

        Picocli provides some default handlers that allow you to accomplish some common tasks with very little code. The following handlers are available:

        • CommandLine.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.
        • CommandLine.RunFirst handler prints help if requested, and otherwise executes the top-level command as a Runnable or Callable.
        • CommandLine.RunAll handler prints help if requested, and otherwise executes all recognized commands and subcommands as Runnable or Callable tasks.
        • CommandLine.DefaultExceptionHandler prints the error message followed by usage help
        Parameters:
        handler - the function that will process the result of successfully parsing the command line arguments
        out - the PrintStream to print help to if requested
        args - the command line arguments
        Returns:
        a list of results, or an empty list if there are no results
        Throws:
        CommandLine.ExecutionException - if the command line arguments were parsed successfully but a problem occurred while processing the parse results; use CommandLine.ExecutionException.getCommandLine() to get the command or subcommand where processing failed
        Since:
        2.0
        See Also:
        CommandLine.RunLast, CommandLine.RunAll
      • parseWithHandlers

        public List<Object> parseWithHandlers​(CommandLine.IParseResultHandler handler,
                                              PrintStream out,
                                              CommandLine.Help.Ansi ansi,
                                              CommandLine.IExceptionHandler exceptionHandler,
                                              String... args)
        Tries to parse the specified command line arguments, and if successful, delegates the processing of the resulting list of CommandLine objects to the specified handler. If the command line arguments were invalid, the ParameterException thrown from the parse method is caught and passed to the specified CommandLine.IExceptionHandler.

        This is a convenience method intended to offer the same ease of use as the run and call methods, but with more flexibility and better support for nested subcommands.

        Calling this method roughly expands to:

         try {
             List<CommandLine> parsedCommands = parse(args);
             return parseResultsHandler.handleParseResult(parsedCommands, out, ansi);
         } catch (ParameterException ex) {
             return new exceptionHandler.handleException(ex, out, ansi, args);
         }
         

        Picocli provides some default handlers that allow you to accomplish some common tasks with very little code. The following handlers are available:

        • CommandLine.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.
        • CommandLine.RunFirst handler prints help if requested, and otherwise executes the top-level command as a Runnable or Callable.
        • CommandLine.RunAll handler prints help if requested, and otherwise executes all recognized commands and subcommands as Runnable or Callable tasks.
        • CommandLine.DefaultExceptionHandler prints the error message followed by usage help
        Parameters:
        handler - the function that will process the result of successfully parsing the command line arguments
        out - the PrintStream to print help to if requested
        ansi - for printing help messages using ANSI styles and colors
        exceptionHandler - the function that can handle the ParameterException thrown when the command line arguments are invalid
        args - the command line arguments
        Returns:
        a list of results produced by the IParseResultHandler or the IExceptionHandler, or an empty list if there are no results
        Throws:
        CommandLine.ExecutionException - if the command line arguments were parsed successfully but a problem occurred while processing the parse result CommandLine objects; use CommandLine.ExecutionException.getCommandLine() to get the command or subcommand where processing failed
        Since:
        2.0
        See Also:
        CommandLine.RunLast, CommandLine.RunAll, CommandLine.DefaultExceptionHandler
      • usage

        public void usage​(PrintStream out,
                          CommandLine.Help.ColorScheme colorScheme)
        Prints a usage help message for the annotated command class to the specified 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.

        Parameters:
        out - the PrintStream to print the usage help message to
        colorScheme - the ColorScheme defining the styles for options, parameters and commands when ANSI is enabled
      • call

        public static <C extends Callable<T>,​T> T call​(C callable,
                                                             PrintStream out,
                                                             CommandLine.Help.Ansi ansi,
                                                             String... args)
        Convenience method to allow command line application authors to avoid some boilerplate code in their application. The annotated object needs to implement Callable. Calling this method is equivalent to:
         CommandLine cmd = new CommandLine(callable);
         List<CommandLine> parsedCommands;
         try {
             parsedCommands = cmd.parse(args);
         } catch (ParameterException ex) {
             out.println(ex.getMessage());
             cmd.usage(out, ansi);
             return null;
         }
         if (CommandLine.printHelpIfRequested(parsedCommands, out, ansi)) {
             return null;
         }
         CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
         try {
             Callable<Object> subcommand = last.getCommand();
             return subcommand.call();
         } catch (Exception ex) {
             throw new ExecutionException(last, "Error calling " + last.getCommand(), ex);
         }
         

        If the specified Callable command has subcommands, the last subcommand specified on the command line is executed. Commands with subcommands may be interested in calling the parseWithHandler method with a CommandLine.RunAll handler or a custom handler.

        From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the Callable are caught and rethrown wrapped in an ExecutionException.

        Type Parameters:
        C - the annotated object must implement Callable
        T - the return type of the specified Callable
        Parameters:
        callable - the command to call when parsing succeeds.
        out - the printStream to print to
        ansi - whether the usage message should include ANSI escape codes or not
        args - the command line arguments to parse
        Returns:
        null if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
        Throws:
        CommandLine.InitializationException - if the specified command object does not have a CommandLine.Command, CommandLine.Option or CommandLine.Parameters annotation
        CommandLine.ExecutionException - if the Callable throws an exception
        See Also:
        parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...), CommandLine.RunLast
      • run

        public static <R extends Runnable> void run​(R runnable,
                                                    PrintStream out,
                                                    CommandLine.Help.Ansi ansi,
                                                    String... args)
        Convenience method to allow command line application authors to avoid some boilerplate code in their application. The annotated object needs to implement Runnable. Calling this method is equivalent to:
         CommandLine cmd = new CommandLine(runnable);
         List<CommandLine> parsedCommands;
         try {
             parsedCommands = cmd.parse(args);
         } catch (ParameterException ex) {
             out.println(ex.getMessage());
             cmd.usage(out, ansi);
             return null;
         }
         if (CommandLine.printHelpIfRequested(parsedCommands, out, ansi)) {
             return null;
         }
         CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
         try {
             Runnable subcommand = last.getCommand();
             subcommand.run();
         } catch (Exception ex) {
             throw new ExecutionException(last, "Error running " + last.getCommand(), ex);
         }
         

        If the specified Runnable command has subcommands, the last subcommand specified on the command line is executed. Commands with subcommands may be interested in calling the parseWithHandler method with a CommandLine.RunAll handler or a custom handler.

        From picocli v2.0, this method prints usage help or version help if requested, and any exceptions thrown by the Runnable are caught and rethrown wrapped in an ExecutionException.

        Type Parameters:
        R - the annotated object must implement Runnable
        Parameters:
        runnable - the command to run when parsing succeeds.
        out - the printStream to print to
        ansi - whether the usage message should include ANSI escape codes or not
        args - the command line arguments to parse
        Throws:
        CommandLine.InitializationException - if the specified command object does not have a CommandLine.Command, CommandLine.Option or CommandLine.Parameters annotation
        CommandLine.ExecutionException - if the Runnable throws an exception
        See Also:
        parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...), CommandLine.RunLast
      • registerConverter

        public <K> CommandLine registerConverter​(Class<K> cls,
                                                 CommandLine.ITypeConverter<K> converter)
        Registers the specified type converter for the specified class. When initializing fields annotated with 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:

        • all primitive types
        • all primitive wrapper types: Boolean, Byte, Character, Double, Float, Integer, Long, Short
        • any enum
        • java.io.File
        • java.math.BigDecimal
        • java.math.BigInteger
        • java.net.InetAddress
        • java.net.URI
        • java.net.URL
        • java.nio.charset.Charset
        • java.sql.Time
        • java.util.Date
        • java.util.UUID
        • java.util.regex.Pattern
        • StringBuilder
        • CharSequence
        • String

        The specified converter will be registered with this 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.

        Type Parameters:
        K - the target type
        Parameters:
        cls - the target class to convert parameter string values to
        converter - the class capable of converting string values to the specified target type
        Returns:
        this CommandLine object, to allow method chaining
        See Also:
        addSubcommand(String, Object)
      • getSeparator

        public String getSeparator()
        Returns the String that separates option names from option values when parsing command line options. "=" by default.
        Returns:
        the String the parser uses to separate option names from option values
      • setSeparator

        public CommandLine setSeparator​(String separator)
        Sets the String the parser uses to separate option names from option values to the specified value. The separator may also be set declaratively with the CommandLine.Command.separator() annotation attribute.
        Parameters:
        separator - the String that separates option names from option values
        Returns:
        this CommandLine object, to allow method chaining
      • getCommandName

        public String getCommandName()
        Returns the command name (also called program name) displayed in the usage help synopsis. "<main class>" by default.
        Returns:
        the command name (also called program name) displayed in the usage
      • setCommandName

        public CommandLine setCommandName​(String commandName)
        Sets the command name (also called program name) displayed in the usage help synopsis to the specified value. Note that this method only modifies the usage help message, it does not impact parsing behaviour. The command name may also be set declaratively with the CommandLine.Command.name() annotation attribute.
        Parameters:
        commandName - command name (also called program name) displayed in the usage help synopsis
        Returns:
        this CommandLine object, to allow method chaining