Execute Groovy script from Gradle without compiling Java

I have a Java project with Gradle. Also I use Groovy to generate some class that will be used in Java code. Gradle executes script in separate task below:

task generateClass(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = 'generatorScript'
}

If I run this task, it first starts Java compilation, and only after that executes script. So if compilation failed, my generator script will not be executed. As it was mentioned, script generates one class, which my Java code is actually depends on, so, if not generated, Java will not be compiled. Vicious circle.

Script itself does not depend on some Java classes and is placed in separate sources directory:

/src
   /main
      /java
          /...(java classes)
      /groovy
          generatorScript.groovy

It seems like nothing interferes me to execute script separately and independently from Java compilation.

How can I achieve that?

Upvotes: 1

Views: 2256

Answers (1)

M.Ricciuti
M.Ricciuti

Reputation: 12106

The problem is that you have the generator groovy script in the main sourcesets, and you try to compile this groovy script to use it as classpath for your JavaExec task. This is why compileJava task is executed, I guess.

You could do in another way, using groovy.ui.GroovyMain to execute your script, with following solution based on this link

configurations {
    // a dedicated Configuration for Groovy classpath
    groovyScript
}

dependencies {
    // Set Groovy dependency so groovy.ui.GroovyMain can be found.
    groovyScript localGroovy()
}

task generateClass(type: JavaExec) {

    // Set class path used for running Groovy command line.
    classpath = configurations.groovyScript

    // Main class that runs the Groovy command line.
    main = 'groovy.ui.GroovyMain'

    // Pass your groovy script as argument of the GroovyMain main
    // (can be improved)
    args 'src/main/groovy/generatorScript.groovy'

}

Upvotes: 2

Related Questions