PicocliBaseScript (picocli 2.3.0 API)
Date: 2018-02-13

picocli.groovy

## Class PicocliBaseScript

- java.lang.Object
- - groovy.lang.GroovyObjectSupport
  - - groovy.lang.Script
    - - picocli.groovy.PicocliBaseScript

- All Implemented Interfaces:
    groovy.lang.GroovyObject

      public abstract class PicocliBaseScript
      extends groovy.lang.Script

  Base script class that provides picocli declarative (annotation-based) command line argument processing for Groovy scripts.

  Scripts may install this base script via the `PicocliScript` annotation or via the standard Groovy `@groovy.transform.BaseScript(picocli.groovy.PicocliBaseScript)` annotation, but the `@PicocliScript` annotation is preferred since it enables scripts to use the `@Command` annotation. Example usage:

       @Command(name = "myCommand", description = "does something special")
       @PicocliScript
       import picocli.groovy.PicocliScript
       import picocli.CommandLine.Command
       ...

  Before the script body is executed, the `PicocliBaseScript` base class parses the command line and initializes `@Field` variables annotated with `@Option` or `@Parameters`. It also takes care of error handling and common use cases like requests for usage help.

  See the `run()` method for a detailed break-down of the steps the base class takes before the statements in the script body are executed.

  Since:
    2.0

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `static java.lang.String` | `COMMAND_LINE` Name of the property that holds the CommandLine instance for this script ("commandLine").

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `PicocliBaseScript()`

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `CommandLine` | `createCommandLine()` Create and returns a new CommandLine instance.
    `protected CommandLine` | `getOrCreateCommandLine()` Return the CommandLine for this script.
    `java.lang.String[]` | `getScriptArguments()` Return the script arguments as an array of strings.
    `java.lang.Object` | `handleExecutionException(CommandLine commandLine, java.lang.String[] args, java.lang.Exception ex)` If an Exception occurs during `runRunnableSubcommand(List)`, or `runScriptBody()` then this gets called to report the problem.
    `java.lang.Object` | `handleParameterException(CommandLine.ParameterException pe, java.lang.String[] args)` If a ParameterException occurs during `parseScriptArguments(CommandLine, String[])` then this method gets called to report the problem.
    `java.util.List<CommandLine>` | `parseScriptArguments(CommandLine commandLine, java.lang.String[] args)` Returns the result of calling `CommandLine.parse(String...)` with the given arguments.
    `void` | `printErrorMessage(java.lang.String message)` Error messages that arise from command line processing call this.
    `java.lang.Object` | `printHelpMessage(CommandLine commandLine)` If an @Option whose `usageHelp` attribute is annotated as true appears in the arguments.
    `java.lang.Object` | `printVersionHelpMessage(CommandLine commandLine)` If an @Option whose `versionHelp` attribute is annotated as true appears in the arguments.
    `java.lang.Object` | `run()` Parses the command line and initializes `@Field` variables annotated with `@Option` or `@Parameters` before executing the script body.
    `void` | `runRunnableSubcommand(java.util.List<CommandLine> parsedCommands)` If the most specific subcommand (the last `CommandLine` object in the list) implements Runnable or Callable, then run it.
    `protected abstract java.lang.Object` | `runScriptBody()` The script body.

    - ### Methods inherited from class groovy.lang.Script

      `evaluate, evaluate, getBinding, getProperty, invokeMethod, print, printf, printf, println, println, run, setBinding, setProperty`

    - ### Methods inherited from class groovy.lang.GroovyObjectSupport

      `getMetaClass, setMetaClass`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### COMMAND_LINE

          public static final java.lang.String COMMAND_LINE

      Name of the property that holds the CommandLine instance for this script ("commandLine").
      See Also:
        Constant Field Values

  - ### Constructor Detail

    - #### PicocliBaseScript

          public PicocliBaseScript()

  - ### Method Detail

    - #### runScriptBody

          protected abstract java.lang.Object runScriptBody()

      The script body.
      Returns:
        The result of the script evaluation.

    - #### run

          public java.lang.Object run()

      Parses the command line and initializes `@Field` variables annotated with `@Option` or `@Parameters` before executing the script body. Also takes care of error handling and common use cases like requests for usage help.

      Here is a break-down of the steps the base class takes before the statements in the script body are executed:

      1. A new `CommandLine` is created with this script instance as the annotated command object. The `CommandLine` instance is cached in the `commandLine` property (so it can be referred to in script code with `this.commandLine`). `CommandLine` creation and initialization may be customized by overriding `createCommandLine()`.
      2. The `parseScriptArguments(CommandLine, String[])` method is called with the script arguments. This initialises all `@Field` variables annotated with `CommandLine.Option` or `CommandLine.Parameters`, unless the user input was invalid.
      3. If the user input was invalid, an error message and the usage message are printed to standard err and the script exits. This may be customized by overriding `handleParameterException(CommandLine.ParameterException, String[])`.
      4. Otherwise, if the user input requested version help or usage help, the version string or usage help message is printed to standard err and the script exits.
      5. If the script implements `Runnable` or `Callable`, its `run` (or `call`) method is called. The script may support subcommands. In that case only the last specified subcommand is run or called if it implements `Runnable` or `Callable`. This may be customized by overriding `runRunnableSubcommand(List)`.
      6. Finally, the script body is executed.
      Specified by:
        `run` in class `groovy.lang.Script`
      Returns:
        The result of the script evaluation.

    - #### getScriptArguments

          public java.lang.String[] getScriptArguments()

      Return the script arguments as an array of strings. The default implementation is to get the "args" property.
      Returns:
        the script arguments as an array of strings.

    - #### getOrCreateCommandLine

          protected CommandLine getOrCreateCommandLine()

      Return the CommandLine for this script. If there isn't one already, then create it using `createCommandLine()`.
      Returns:
        the CommandLine for this script.

    - #### createCommandLine

          public CommandLine createCommandLine()

      Create and returns a new CommandLine instance. This method sets the command name in the usage help message to the script's class simple name (unless annotated with some other command name with the `@Command(name = "...")` annotation).

      Subclasses may override to register custom type converters or programmatically add subcommands.

      Returns:
        A CommandLine instance.

    - #### parseScriptArguments

          public java.util.List<CommandLine> parseScriptArguments(CommandLine commandLine,
                                                         java.lang.String[] args)

      Returns the result of calling `CommandLine.parse(String...)` with the given arguments.

      Subclasses may override if any action should be taken immediately before or after parsing.

      Parameters:
        `commandLine` - The CommandLine instance for this script instance.
        `args` - The argument array.
      Returns:
        the list of `CommandLine` objects that result from parsing the user input

    - #### runRunnableSubcommand

          public void runRunnableSubcommand(java.util.List<CommandLine> parsedCommands)
                                     throws java.lang.Exception

      If the most specific subcommand (the last `CommandLine` object in the list) implements Runnable or Callable, then run it. This method will not run the main script `runScriptBody()` method; that will be called from `{@link #run()}`.
      Parameters:
        `parsedCommands` - the list of `CommandLine` objects returns from the `CommandLine.parse` method
      Throws:
        `java.lang.Exception` - if the Callable throws an exception

    - #### printErrorMessage

          public void printErrorMessage(java.lang.String message)

      Error messages that arise from command line processing call this. The default is to print to System.err. If you want to use System.out, a logger, or something else, this is the method to override.
      Parameters:
        `message` - the error message to print

    - #### handleParameterException

          public java.lang.Object handleParameterException(CommandLine.ParameterException pe,
                                                  java.lang.String[] args)

      If a ParameterException occurs during `parseScriptArguments(CommandLine, String[])` then this method gets called to report the problem. The default behavior is to show the exception message using `printErrorMessage(String)`, then call `printHelpMessage(CommandLine)`. The return value becomes the return value for the Script.run which will be the exit code if we've been called from the command line.
      Parameters:
        `pe` - The ParameterException that occurred
        `args` - The argument array
      Returns:
        The value that Script.run should return. This implementation returns 1, subclasses may override.

    - #### handleExecutionException

          public java.lang.Object handleExecutionException(CommandLine commandLine,
                                                  java.lang.String[] args,
                                                  java.lang.Exception ex)

      If an Exception occurs during `runRunnableSubcommand(List)`, or `runScriptBody()` then this gets called to report the problem. The default behavior is to throw a new `ExecutionException` wrapping the specified exception.
      Parameters:
        `commandLine` - The CommandLine instance
        `args` - The argument array
        `ex` - The Exception that occurred
      Returns:
        The value that Script.run should return when overriding this method
      Throws:
        `CommandLine.ExecutionException` - wrapping the specified exception by default

    - #### printHelpMessage

          public java.lang.Object printHelpMessage(CommandLine commandLine)

      If an @Option whose `usageHelp` attribute is annotated as true appears in the arguments. then the script body is not run and this `printHelpMessage` method is called instead. The default behavior is to print the `CommandLine.usage(PrintStream)` to `System.err`. The return value becomes the return value for the Script.run which will be the exit code if we've been called from the command line.
      Parameters:
        `commandLine` - The CommandLine instance
      Returns:
        The value that Script.run should return (`null` by default).

    - #### printVersionHelpMessage

          public java.lang.Object printVersionHelpMessage(CommandLine commandLine)

      If an @Option whose `versionHelp` attribute is annotated as true appears in the arguments. then the script body is not run and this printVersionHelpMessage method is called instead. The default behavior is to print the `CommandLine.printVersionHelp(PrintStream)` to `System.err`. The return value becomes the return value for the Script.run which will be the exit code if we've been called from the command line.
      Parameters:
        `commandLine` - The CommandLine instance
      Returns:
        The value that Script.run should return (`null` by default).