tags:

views:

378

answers:

3

Is there a standard or recommended getopts library for Groovy that will allow me to quickly process long and short command line arguements in Groovy?

groovy foo.groovy --fname=foo.txt --output=foo.html --verbose

+1  A: 

One of the major strengths of Groovy is interoperability with Java. Therefore, when looking for libraries to use in Groovy, my first instinct is to look for existing Java libraries.

Args4j is a concise and elegant library for parsing command line options and it works perfectly with Groovy classes. I've rewritten parts of the tutorial to work with Groovy.

Consider the following Groovy class:

import org.kohsuke.args4j.Option;

class Business {

        @Option(name="-name",usage="Sets a name")
        String name

        public void run() {

                println("Business-Logic")
                println("-name: " + name)
        }
}

Compile it with:

groovyc -classpath .:args4j-2.0.12/args4j-2.0.12.jar Business.groovy

and run it with

java -cp .:args4j-2.0.12/args4j-2.0.12.jar:/usr/share/java/groovy/embeddable/groovy-all-1.6.4.jar -Dmainclass=Business org.kohsuke.args4j.Starter -name sample

To get the output

Business-Logic
-name: sample
Robert Munteanu
A: 

Apache Commons CLI is another Java library that you could use in Groovy

Don
+4  A: 

You could also simply use Groovy CliBuilder (which internally uses Apache Commons Cli).

You will find a good example of how it works here=> http://www.reverttoconsole.com/blog/codesnippets/groovy-clibuilder-in-practice/

def cli = new CliBuilder()
cli.with {
     usage: 'Self'
     h longOpt:'help', 'usage information'
     i longOpt:'input', 'input file', args:1
     o longOpt:'output', 'output file',args:1
     a longOpt:'action', 'action to invoke',args:1
     d longOpt:'directory','process all files of directory', args:1
}
def opt = cli.parse(args)
def action
if( args.length == 0) {
    cli.usage()
    return
}
if( opt.h ) {
    cli.usage()
    return
}
if( opt.i ) {
input = opt.i
}
...
Christophe Furmaniak