Search code examples
javagradlegroovy

How to run a Groovy script from a Gradle task in another java process?


Let's say you have a Groovy script that ends with a System.exit(...) call and you want this Groovy script to be executed in a Gradle task. As the System.exit call will terminate the whole JVM you want to run this script in another Java process (as using GroovyShell does not seem to be an option because to of the System.exit call). How can you do this without using a separate Groovy installation's groovy command)?

If something like this might work, how do I have to replace ??? and ?????

  javaexec {
    classpath = ???
    mainClass = ????
    args = ['my-script.groovy']
  }

[Edit] Okay, here's a "minimal reproducible example" as mentioned in the comment below, if that makes the question better understandable:

The Groovy script:

    // file: my-script.groovy

    println 'Hello World'
    System.exit(0)

The Gradle task (this might be completely wrong and I do not know how to replace the question marks):

task runMyScript(type: JavaExec) {
  classpath = ???
  mainClass = ????
  args = ['my-script.groovy']
}

Solution

  • how to run groovy script using java command line you can check in groovy shells/batches:

    https://github.com/apache/groovy/blob/master/src/bin/groovy.bat#L30

    java -cp "$GROOVY_HOME/lib" groovy.ui.GroovyMain myscript.groovy
    

    the only question find out gradle/lib folder where usually groovy-all is located

    i can suggest this as straight forward:

    def groovyJar = new File(groovy.ui.GroovyMain.getProtectionDomain().getCodeSource()?.getLocation()?.toURI())
    

    Or when using javaexec as mentioned above, it's:

      javaexec {
        classpath = files(groovy.ui.GroovyMain.protectionDomain.codeSource.location)
        mainClass = 'groovy.ui.GroovyMain'
        args = ['my-script.groovy']
      }