18

What's the best way to create a gradle task, which runs a groovy script? I realize that gradle build files are groovy, so I would think it would be possible to do something like this:

task run << {
    Script app = new GroovyShell().parse(new File("examples/foo.groovy"))
    // or replace .parse() w/ a .evalulate()?
    app.run()
}

I get all kinds of whacky errors when I try this if bar.groovy is using @Grab annotations or even doing simple imports. I want to create a gradle task to handle this, so that I can hopefully reuse the classpath definition.

Would it be better to move the examples directory into the src directory somewhere? What's a best practice?

macattack
  • 181
  • 1
  • 3

4 Answers4

13

Or you could do:

new GroovyShell().run(file('somePath'))
rekire
  • 47,260
  • 30
  • 167
  • 264
Hans Dockter
  • 529
  • 4
  • 3
7

You could try using GroovyScriptEngine instead of the GroovyShell. I've used it previously with @Grab annotations. You will need all of groovy on the classpath, the groovy-all.jar will not be enough. I'm guessing Ivy isn't packaged in the groovy-all.jar. Something like this should to the trick:

This script presumes a groovy script at /tmp/HelloWorld.groovy

def pathToFolderOfScript = '/tmp'
def gse = new GroovyScriptEngine([pathToFolderOfScript] as String[])
gse.run('HelloWorld.groovy', new Binding())
xlson
  • 2,677
  • 1
  • 20
  • 11
2

http://wayback.archive.org/web/20131006153845/http://docs.codehaus.org/display/GRADLE/Cookbook#Cookbook-runningthingsfromGradle

ant.java(classname: 'com.my.classname', fork: true,
         classpath: "${sourceSets.main.runtimeClasspath.asPath}")
seanf
  • 6,504
  • 3
  • 42
  • 52
1

I think you probably need to run the script as a new process... e.g.,

["groovy","examples/foo.groovy"].execute()

I would guess that the way Gradle is executed is not via invoking groovy, so the setup that makes @Grab work never happens. It could also be the the version of Groovy that Gradle uses doesn't support @Grab.

noah
  • 21,289
  • 17
  • 64
  • 88
  • 4
    Unlike the other suggestions here, this one requires that the user has an independent installation of Groovy. Gradle does not provide "groovy", "groovy.bat", etc. That's an unacceptable requirement for apps built with Gradle, because gradlew is used to eliminate the need to even have the Gradle system installed independently. – Blaine Oct 24 '11 at 17:11