@Grab and command line scripts

A Groovy script can download a library for itself: @Grab asks Grape, the dependency resolver of the language, for a coordinate, and the annotation adds the jar to the class path before the class is compiled. The same script can take options from the command line with CliBuilder, which turns it into a tool.

A dependency that is local

grab.groovy

@Grab('org.apache.commons:commons-lang3:3.14.0') import org.apache.commons.lang3.StringUtils println StringUtils.capitalize('groovy')

groovy grab.groovy

Groovy

The jar came from the local Maven repository in the home folder, which already holds commons-lang3 at several versions. A machine with the network would fetch it from Maven Central instead; the script does not change.

A dependency that is not there

Guava is not in that repository, and this image cannot reach Maven Central, so the resolver fails before the script runs. The message is the real one:

guava.groovy

@Grab('com.google.guava:guava:33.0.0-jre') import com.google.common.collect.ImmutableList println ImmutableList.of(1, 2, 3)

groovy guava.groovy

General error during conversion: Error grabbing Grapes -- [unresolved dependency: com.google.guava#guava;33.0.0-jre: not found]
java.lang.RuntimeException: Error grabbing Grapes -- [unresolved dependency: com.google.guava#guava;33.0.0-jre: not found]
exit status: 1

The error names the artifact Grape could not resolve, and the script exits with status 1. That is why a project that is built rather than scripted declares its dependencies in the build file: a build resolves them once, and a failure names the repository and the module. A @Grab in a script is a convenience for a small tool, not a dependency policy.

Options with CliBuilder

greet.groovy

import groovy.cli.commons.CliBuilder def cli = new CliBuilder(usage: 'greet.groovy -n name') cli.n(longOpt: 'name', args: 1, required: true, 'the name to greet') cli.v(longOpt: 'verbose', 'print the greeting twice') def options = cli.parse(args) if (options) { def greeting = "Hello, ${options.n}" println greeting if (options.v) { println greeting } }

groovy greet.groovy -n Ada -v

error: Missing required option: n
usage: greet.groovy -n name
 -n,--name <arg> the name to greet
 -v,--verbose print the greeting twice

Every option is one declaration: the short name, the long name, how many arguments it takes, whether it is required, and the text of the help. parse returns an object whose properties are the options, or null when the command line was wrong.

Groovy 5 also ships groovy.cli.picocli.CliBuilder, the same idea on the newer parser. This image has the Groovy adapter but not the picocli jar itself, so the examples use the commons variant, whose jar is in the distribution. A script that runs without its required option prints the usage, and this launcher still exits with status 0, so a script that must fail on a bad command line calls System.exit(1) itself.

Related

Автор статьи: Arthur Isaev