picocli.groovy

## Class PicocliBaseScript

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

-     public abstract class PicocliBaseScript
      extends 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
  Author:
    Jim White, Remko Popma

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `static 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

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

    - ### 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 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 Object runScriptBody()

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

    - #### run

          public 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.
      Returns:
        The result of the script evaluation.

    - #### getScriptArguments

          public 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 List<CommandLine> parseScriptArguments(CommandLine commandLine,
                                                        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(List<CommandLine> parsedCommands)
                                     throws 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:
        `Exception` - if the Callable throws an exception

    - #### printErrorMessage

          public void printErrorMessage(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 Object handleParameterException(CommandLine.ParameterException pe,
                                                 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 Object handleExecutionException(CommandLine commandLine,
                                                 String[] args,
                                                 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 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).

    - #### printHelpMessage

          public Object printHelpMessage(CommandLine commandLine,
                                         PrintStream stream)

      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 the specified stream. 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
        `stream` - the stream to print the usage help message to
      Returns:
        The value that Script.run should return (`null` by default).
      Since:
        3.0

    - #### printVersionHelpMessage

          public 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.out`. 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).

Copyright © 2019. All rights reserved.