Command-Line Tools and Configuration

38.1 CliBuilder

Annotation-based options: interface/class with @Option/@Unparsed and cli.parseFromSpec(MyOptions, args). Or use picocli directly (excellent Groovy support, including @Command scripts with @picocli.groovy.PicocliScript).

import groovy.cli.picocli.CliBuilder      // picocli-based (recommended); groovy.cli.commons also exists

def cli = new CliBuilder(name: 'greet', usage: 'greet [options] <names>')
cli.with {
    h longOpt: 'help', 'Show usage'
    n longOpt: 'times', args: 1, type: Integer, defaultValue: '1', 'Repetitions'
    l longOpt: 'loud', 'Shout'
}
def opts = cli.parse(args)
if (!opts || opts.h) { cli.usage(); return }
opts.arguments().each { name ->
    opts.n.times { println(opts.l ? "HELLO ${name.toUpperCase()}!" : "Hello $name") }
}

38.2 ConfigSlurper

def config = new ConfigSlurper('production').parse('''
app {
    name = "MyApp"
    port = 8080
}
environments {
    development { app.port = 9090 }
    production { app.port = 80 }
}
''')
println config.app.name, config.app.port      // MyApp 80
def props = config.toProperties()

38.3 Logging and Console Utilities

@Slf4j/@Log annotations, java.util.logging, Logback config in Groovy (logback.groovy is deprecated in newer Logback versions, so prefer XML).

ANSI colors with Jansi or escape codes. System.console() for passwords (readPassword).