javagroovycommand-line-interfacecommand-line-argumentspicocli

How to use CliBuilder in groovy without options?


I am writing a simple groovy script for which I want a command line as simple as-

./someTask.groovy task-profile

Also, the script should have a --help or -h option which specifies all the different values task-profile can take.


task-profile can take the following values-

And the --help option should tell the users about all available task-profile values and also how to use them.

I searched a lot but only found examples that had options (eg -a, -b, -c, etc.)

How to write a script that has no option, but only positional parameters, I can hardcode it using switch statements, but I want to learn to use CliBuilder. Any help will be appreciated.


Solution

  • CliBuilder was updated in Groovy 2.5 by adding support for a picocli-backed implementation (groovy.cli.picocli.CliBuilder). This article shows many details of the new features that are now available in CliBuilder.

    However, even in this version of CliBuilder, the public API only supports a list of positional parameters, with a single description for that list.

    @Unparsed(description = 'positional parameters')
    List positionals
    

    Unfortunately, the CliBuilder API currently does not provide a way to show separate positional parameters, with individual descriptions, in the usage help message of your application.

    If your goal is to have separate positional parameters, perhaps with separate types, separate default values, etc., and let the usage help message show separate descriptions for each positional parameter, then you may want to consider using picocli directly (without CliBuilder) in your Groovy script or in your Groovy application.

    The picocli user manual has many Groovy examples and has a dedicated section on using picocli in Groovy applications and Groovy scripts. This article (Groovy Scripts on Steroids) may also be useful.

    Here is an example task-profile Groovy script with three positional parameters:

    // task-profile.groovy
    @Grab('info.picocli:picocli-groovy:4.6.3')
    @GrabConfig(systemClassLoader=true)
    @Command(name = "task-profile", version = "task-profile 1.0",
            mixinStandardHelpOptions = true, // add --help and --version options
            description = "Task Profile")
    @picocli.groovy.PicocliScript2
    import groovy.transform.Field
    import static picocli.CommandLine.*
    
    @Parameters(index = "0", description = "The first task")
    @Field String task1;
    
    @Parameters(index = "1", description = "The second task")
    @Field String task2;
    
    @Parameters(index = "2", description = "The third task")
    @Field String task3;
    
    // PicocliBaseScript2 prints usage help or version if requested by the user
    
    println "hi, the selected tasks are $task1, $task2 and $task3"