I Just Want to Execute a Groovy Script Using the Project CLASSPATH From a Gradle Task: Is That So Wrong?

I’ve been using Gradle for my Groovy builds recently. I consider myself a Build Diletteante, having done complex builds in days of yore using Ant, and having done the bulk of my recent builds in Grails, which is to say I haven’t really done a lot of complex builds in a while. Anyway, from my vantage point, Gradle seems to do everything right, and I’m excited to be seeing its rise to prominence.

It has just about everything it needs, but what it lacks is a convenient and well-documented means of executing a Groovy script inside a task with the project’s classes and compile-time JARs on the script’s CLASSPATH. Because, I mean, who doesn’t want that? Well, I do; I frequently find myself developing a small collection of classes which I want to exercise both through unit tests and through an integration-test-like script. I don’t want to push all of the script code into the build file, but I want the script to run as a first-class citizen of the build. “groovy -cp build/classes/main:foo.jar:monkey.jar… script.groovy” is only tolerable for so long.

And we need tolerate it no longer! Herewith my solution, entirely in the build file:

The classname passed to the Java task is simply the script’s package followed by the name of the script. In this example, we would want a file called script.groovy in the Groovy source tree that looks like this:

I have to believe this is a slightly unconventional need of mine, but I keep bumping into it, so I’m pretty happy to have solved it. Hope this helps! Thanks go to Adam Murdoch on the Gradle User list for pointing me to sourceSets.main.runtimeClasspath, which helped me find classesDir and a whole lot more.

Leave a Comment