Last active
July 13, 2018 06:52
-
-
Save UnquietCode/5027726 to your computer and use it in GitHub Desktop.
A simple command line utility template for Groovy. Functionality can be implemented by declaring new methods of the form "_doXYZ" where XYZ is the name of the command to run.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Base class for command line applications. | |
* | |
* Children can provide functionality in the form of | |
* <command name> <arguments...> | |
* | |
* @author Ben Fagin | |
*/ | |
class GroovyCLI implements Runnable { | |
private String[] args; | |
// invoked at the command line | |
GroovyCLI(String[] args) { | |
this.args = args | |
} | |
void run() { | |
// argument parsing | |
def newArgs | |
if (args.length < 1) { | |
throw new RuntimeException("usage <command name :: 1> <args :: 0+>") | |
} else if (args.length == 1) { | |
newArgs = {} | |
} else { | |
newArgs = args[1..args.length-1] | |
} | |
// make the command name | |
def cmd = args[0].toLowerCase() | |
if (cmd.length() > 0) { | |
def firstChar = Character.toUpperCase(cmd.charAt(0)) | |
firstChar = Character.toString(firstChar) | |
cmd = firstChar + cmd.substring(1) | |
} | |
// run the command | |
try { | |
"_do${cmd}"(newArgs) | |
} catch (MissingMethodException ex) { | |
throw new RuntimeException("Command '${cmd}' not recognized.") | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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