Command Line Subcommands in Groovy

Here’s the translation of the Go code to Groovy, with explanations in Markdown format suitable for Hugo:

Our example demonstrates how to create command-line subcommands in Groovy, similar to tools like git that have multiple subcommands (e.g., git commit, git push). We’ll use the CliBuilder class from Groovy to handle command-line parsing.

import groovy.cli.CliBuilder

def fooCommand = { args ->
    def cli = new CliBuilder(usage: 'foo [options]')
    cli.with {
        e longOpt: 'enable', 'enable option'
        n longOpt: 'name', args: 1, 'name option'
    }

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

    println "subcommand 'foo'"
    println "  enable: ${options.e}"
    println "  name: ${options.n}"
    println "  tail: ${options.arguments()}"
}

def barCommand = { args ->
    def cli = new CliBuilder(usage: 'bar [options]')
    cli.with {
        l longOpt: 'level', args: 1, type: Integer, 'level option'
    }

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

    println "subcommand 'bar'"
    println "  level: ${options.l}"
    println "  tail: ${options.arguments()}"
}

if (args.length < 1) {
    println "expected 'foo' or 'bar' subcommands"
    System.exit(1)
}

switch (args[0]) {
    case 'foo':
        fooCommand(args.tail())
        break
    case 'bar':
        barCommand(args.tail())
        break
    default:
        println "expected 'foo' or 'bar' subcommands"
        System.exit(1)
}

To run this Groovy script:

$ groovy command-line-subcommands.groovy foo -e -n=joe a1 a2
subcommand 'foo'
  enable: true
  name: joe
  tail: [a1, a2]

$ groovy command-line-subcommands.groovy bar -l 8 a1
subcommand 'bar'
  level: 8
  tail: [a1]

In this Groovy version:

  1. We define separate functions for each subcommand (fooCommand and barCommand).
  2. We use CliBuilder to define and parse command-line options for each subcommand.
  3. The main script checks the first argument to determine which subcommand to run.
  4. Each subcommand function handles its own argument parsing and execution.

This approach provides a flexible way to implement subcommands in Groovy, allowing each subcommand to have its own set of options and arguments.