Command line parsing example in Groovy

Here is an example using CliBuilder. I wrote it as an example for my stackoverflow question.

[sourcecode language=”groovy”]
def cli = new CliBuilder(usage: ‘cliTest -s sdkdir {projectName}’,
header: ‘Command line parameter parsing test in Groovy’)
cli.s longOpt: ‘sdkdir’, args: 1, ‘sdkdir usage info, REQUIRED’
cli.h longOpt: ‘help’, ‘print usage information’
def opt = cli.parse(args)
def errMsg = "Invalid arguments.\nusage: ${cli.usage}\n" +
"Try `cliTest –help’ for more information."
if (!opt) {
//should never happen, since I don’t have required parameters in CliBuilder
println "error processing arguments\n"
} else if (opt.h) {
} else if (!opt.s) {
println errMsg
} else if (opt.arguments().size() != 1) {
println errMsg
} else {
println "Creating project ${opt.arguments()[0]}, sdkdir ${opt.s.value}"

The key is that opt.arguments() contains all arguments or options that I didn’t test yet, as explained in GROOVY 3272 issue (thanks @rodion for spotting it).

Leave a Reply




You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">