Ok, it doesn’t get much easier than this to build a CLI:
class ContentUpdaterMain {
static void main(args) {
def cli = new CliBuilder(usage: 'java -jar contentupdater.jar -su[dh] "update name"')
cli.h(longOpt: 'help', 'usage information')
cli.u(longOpt: 'update', 'update the provided table', args: 1)
cli.s(longOpt: 'stage', 'stage the provided table', args: 1)
cli.d(longOpt: 'debug', 'run the process with debugging enabled')
def opt = cli.parse(args)
if(!opt) return
if(opt.h) cli.usage()
if( opt.d ) {
//turn on debug
}
if(opt.u) {
//do updates
}
if( opt.s ) {
// run against staging db
}
}
}
This produces the following usage output:
usage: java -jar contentupdater.jar -su[dh] "update name" -d,--debug run the process with debugging enabled -h,--help usage information -s,--stage stage the provided table -u,--update update the provided table
And all that remains is to validate the input and invoke the processes!
6 Comments
You may make it a tiny bit groovier with using “with()”:
cli.with {
h longOpt: ‘…’, ‘…’
u longOpt: ‘…’, ‘…’
}
Thanks for the pointer Guillaume. By the way I’ve been reading about Gaelyk recently. I think it’s a very timely addition! I’m looking forward to writing about it here in the future.
How do you allow for options that can appear more than once? This means that you have to be able to iterate through the provided options in some way.
I’d have to say that the CliBuilder doc is less than informative.
Each option is of type org.apache.commons.cli.Option. This class contains an arg property, which allows you to set the maximum number of args a given property can accept. Take a look here:
http://commons.apache.org/cli/api-1.2/org/apache/commons/cli/Option.html
I have yet to find a way to handle the -foo=bar option. Does the CLIBuilder do this? If it does, where can I find an example of this syntax? right now I have written it myself using a for loop and making it in the format of -f bar…but I am sure there is a better way to do this.
Hey Steve,
I think what you’re looking for is the args property.
Check out the examples here: http://groovy.codehaus.org/gapi/groovy/util/CliBuilder.html
In particular look at the example provided emulating the ant command line:
cli.logfile(args:1, argName:’file’, ‘use given file for log’)
cli.D(args:2, valueSeparator:’=', argName:’property=value’,
‘use value for given property’)
One Trackback/Pingback
[...] are three problems, I chose the middle one to start with. I wrote it in groovy and used the very groovy clibuilder M. Laforge recommended in his comment. I mavenized it to make it easier to [...]
Post a Comment