Command Line Flags in Groovy

Here’s the translation of the Go code example to Groovy, formatted in Markdown suitable for Hugo:

import groovy.cli.picocli.CliBuilder

def cli = new CliBuilder(usage: 'groovy command-line-flags.groovy [options]')
cli.with {
    h longOpt: 'help', 'Show usage information'
    w longOpt: 'word', args: 1, argName: 'WORD', 'A string option'
    n longOpt: 'numb', args: 1, argName: 'NUMBER', type: Integer, 'An integer option'
    f longOpt: 'fork', 'A boolean option'
    s longOpt: 'svar', args: 1, argName: 'SVAR', 'Another string option'
}

def options = cli.parse(args)
if (!options) {
    return
}

if (options.h) {
    cli.usage()
    return
}

println "word: ${options.w ?: 'foo'}"
println "numb: ${options.n ?: 42}"
println "fork: ${options.f}"
println "svar: ${options.s ?: 'bar'}"
println "tail: ${options.arguments()}"

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Groovy provides the CliBuilder class from the groovy.cli.picocli package for parsing command-line options. We’ll use this class to implement our example command-line program.

In this example, we create a CliBuilder instance and define our command-line options:

  • word: A string option with a default value of “foo”
  • numb: An integer option with a default value of 42
  • fork: A boolean option
  • svar: Another string option with a default value of “bar”

After defining the options, we parse the command-line arguments using cli.parse(args). We then check if the help option was specified, and if so, we print the usage information and exit.

Finally, we print out the parsed options and any trailing positional arguments.

To experiment with the command-line flags program, save it as command-line-flags.groovy and run it using the groovy command:

$ groovy command-line-flags.groovy -w opt -n 7 -f -s flag
word: opt
numb: 7
fork: true
svar: flag
tail: []

Note that if you omit flags, they automatically take their default values:

$ groovy command-line-flags.groovy -w opt
word: opt
numb: 42
fork: false
svar: bar
tail: []

Trailing positional arguments can be provided after any flags:

$ groovy command-line-flags.groovy -w opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: [a1, a2, a3]

Use the -h or --help flag to get automatically generated help text for the command-line program:

$ groovy command-line-flags.groovy -h
Usage: groovy command-line-flags.groovy [options]
  -h, --help                 Show usage information
  -w, --word=WORD            A string option
  -n, --numb=NUMBER          An integer option
  -f, --fork                 A boolean option
  -s, --svar=SVAR            Another string option

If you provide a flag that wasn’t specified, the program will print an error message and show the help text.