Shebang! Birth of a Groovy script
For a few days I have been browsing through Groovy in Action and wanted to give Groovy a try. So what should I code? I was busy with other stuff and while I was setting up a wicket project at home I wondered….what was the mvn wicket-quickstart syntax again?! I could have just pasted the command from the wicket site, but I decided to let Groovy handle this one. My first Groovy script was born. Nothing fancy, the script reads an artifactId and groupId from standard input and prods maven to create a quickstart project. It’s really nothing but a thin wrapper around the maven command. Anyway, it’s a nice opportunity to play with Groovy. Read the script below and I’ll comment right after:
<br> #!/usr/bin/env groovy</p> <p>System.in.withReader { reader -><br> println "[Wicket Quickstart Script]"<br> print "groupId: "<br> def groupId = reader.readLine()<br> print "artifactId: "<br> def artifactId = reader.readLine()</p> <p>def command = """/usr/bin/mvn archetype:create<br> -DarchetypeGroupId=org.apache.wicket<br> -DarchetypeArtifactId=wicket-archetype-quickstart<br> -DarchetypeVersion=1.4-rc4<br> -DgroupId=${groupId} -DartifactId=${artifactId}"""</p> <p>def proc = command.execute()<br> proc.in.newReader().eachLine {<br> line -> println line<br> }<br> }<br>
One thing I didn’t know earlier is that you can’t shebang a Groovy script as usual on a *NIX machine. Instead you put #!/usr/bin/env groovy at the top which fires up Groovy indirectly. Now the actual script. Reading the input uses a closure, similar to anonymous inner classes in Java, but way more powerful. Next, the script creates the maven command string. This part uses multi line strings, created with “”” and GStrings, which allow $variable interpolation. See Strings and GStrings. Quite useful. The final part does process management with execute(), again using a closure to loop through the maven output and print each line.
It seems that Groovy makes these scripting tasks easy to do, with very little code. From what I’ve seen so far Groovy has the familiar OO foundation of Java and the shortcut power features of scripting languages like perl and ruby. I’ll definitely use Groovy for similar scripts in the future and I am curious about using Groovy along with Java. This is really scratching the surface of what you can do with Groovy, there is a whole lot to explore!