Gradle and the Groovy Shell

I wrote before that I prefer the groovy shell to the Groovy console. I found a way to print the classpath with Gradle to make a script to run code in your Gradle project from the Groovy shell. It was kind of cumbersome.

There is still no out-of-the-box way to run the Groovy shell from a Gradle project. The way I came up with was a bit cumbersome. I have found another way that might be a bit easier.

Gradle has a built-in application plugin. You tell it the name of your main class. For the purposes of this technique, you can pretty much put in anything you want; we really won’t be using it.

Then you run

gradle distZip

This will create a zip file in build/distributions. Unzip this file, and go into the bin/ directory. There you will find a shell script for your application. Copy it to another file.

Find the line for the classpath, and take out the groovy-all jar file. Then down at the bottom, change the line with the command. It will look something like this:

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH"  org.codehaus.groovy.tools.shell.Main "$@"

Change that line to this:

exec groovysh "${JVM_OPTS[@]}" -classpath "$CLASSPATH"

You need to take the groovy-all jar file out of the classpath since we are going to run groovysh. If there are two groovy-all jar files on the classpath, there will be problems.

Then take this file, and put it in src/dist/bin. If you put it there, then every time you run distZip, then the shell script you created will show up in the bin/ directory of the zip file.

There is a groovy-groovysh archive in the central Maven repository. I tried that, but then when I tried to run the shell script Gradle produced, it complained that it could not find some class in org.jansi. So I tried to add that, and then it complained about commons-cli. I had no idea when that would end, so I just decided to do it by hand.

I realize that every time I add a jar file I have to redo this process. But at least I have a process.

I will probably cover this when I give my talk on ActiveJDBC.

Image from “Evangelia [Évangiles de Noailles ou de Charles le Chauve]”, a 9th century manuscript housed at the Bibliothèque nationale de France. Source gallica.bnf.fr / BnF; image assumed allowed under Fair Use.