Wednesday, March 26, 2008

Parsing command line args

I love the way it's done in Gant!!

def cli = new CliBuilder ( usage : 'gant [option]* [target]*' , parser : new GnuParser ( ) )
cli.c ( longOpt : 'usecache' , 'Whether to cache the generated class and perform modified checks on the file before re-compilation.' )
cli.d ( longOpt : 'cachedir' , args : 1 , argName : 'cache-file' , 'The directory where to cache generated classes to.' )
cli.f ( longOpt : 'gantfile' , args : 1 , argName : 'build-file' , 'Use the named build file instead of the default, build.gant.' )
cli.h ( longOpt : 'help' , 'Print out this message.' )

cli.l ( longOpt : 'gantlib' , args : 1 , argName : 'library' , 'A directory that contains classes to be used as extra Gant modules,' )
cli.n ( longOpt : 'dry-run' , 'Do not actually action any tasks.' )
cli.p ( longOpt : 'projecthelp' , 'Print out a list of the possible targets.' )
cli.q ( longOpt : 'quiet' , 'Do not print out much when executing.' )
cli.s ( longOpt : 'silent' , 'Print out nothing when executing.' )
cli.v ( longOpt : 'verbose' , 'Print lots of extra information.' )

cli.D ( argName : 'name>=<value' , args : 1 , 'Define <name> to have value <value>.  Creates a variable named <name> for use in the scripts and a property named <name> for the Ant tasks.' )
cli.L ( longOpt : 'lib' , args : 1 , argName : 'path' , 'Add a directory to search for jars and classes.' )
cli.P ( longOpt : 'classpath' , args : 1 , argName : 'path' , 'Specify a path to search for jars and classes.' )
cli.T ( longOpt : 'targets' , 'Print out a list of the possible targets.' )
cli.V ( longOpt : 'version' , 'Print the version number and exit.' )

def options = cli.parse ( args )

parse(args) returns a map you use like so...


if ( options.h ) { cli.usage ( ) ; return 0 }
if ( options.l ) { gantLib << options.l.split ( System.properties.'path.separator' ) }
if ( options.n ) { GantState.dryRun = true }
def function = ( options.p || options.T ) ? 'targetList' : 'dispatch'
if ( options.q ) { GantState.verbosity = GantState.QUIET }
if ( options.s ) { GantState.verbosity = GantState.SILENT }
if ( options.v ) { GantState.verbosity = GantState.VERBOSE }

PS. I'll try to clean this up later... pygments.org looks neat!

No comments: