Skip to content

Instantly share code, notes, and snippets.

@duckpuppy
Forked from UnquietCode/GroovyCLI.groovy
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duckpuppy/a9fe87762d8d84783ce0 to your computer and use it in GitHub Desktop.
Save duckpuppy/a9fe87762d8d84783ce0 to your computer and use it in GitHub Desktop.
/**
* Base class for command line applications.
*
* Children can provide functionality in the form of
* <command name> <arguments...>
*
* @author Ben Fagin
* @author Patrick Aikens
*/
class GroovyCLI implements Runnable {
private String[] args;
// invoked at the command line
GroovyCLI(String[] args) {
this.args = args
}
void run() {
if (args) {
def cmd = args[0].toLowerCase().capitalize()
// run the command
try {
"_do${cmd}"(args.tail())
} catch (MissingMethodException ex) {
throw new RuntimeException("Command '${cmd}' not recognized.")
}
} else {
throw new RuntimeException("usage <command name :: 1> <args :: 0+>")
}
}
}
import groovy.transform.InheritConstructors
/**
* Example application. Pass this as the main class, and Groovy will
* construct the object with the arguments, and then invoke the
* specified command as per the run() method in {@link GroovyCLI}.
*
* @author Ben Fagin
*/
@InheritConstructors
class MyApp extends GroovyCLI {
// a single command called 'test'
// expects any number of arguments
void _doTest(def args) {
println("${args.size()} arguments")
println(args)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment