Jeffrey Guenther
Jeffrey Guenther

Reputation: 901

How do I ensure code is generated before compiling when building?

I have a build.gradle with the following code:

apply plugin: 'java'
apply plugin: 'application'

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked"
    }
}

ext.antlr = [
    grammarpackage: "org.shirolang.interpreter",
    antlrSource: 'src/main/java/org/shirolang',
    destinationDir: "src/generated/java"
]

sourceSets{
    generated
    main{
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }
    test{
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }
}
project.run.classpath += sourceSets.generated.output

repositories {
    mavenCentral()
}

configurations {
    antlr4
}

sourceSets{
    main{
        java{
            srcDirs 'src/main/java', 'src/antlr/java'
        }
    }
}

dependencies {
    ...
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

task antlrOutputDir << {
    mkdir(antlr.destinationDir)
}

task generateGrammarSource(dependsOn: antlrOutputDir, type: JavaExec) {
   // code to generate a antlr grammar
}

compileJava {
    dependsOn generateGrammarSource
    classpath += sourceSets.generated.output
}

It outputs:

:antlrOutputDir
:compileGeneratedJava UP-TO-DATE
:processGeneratedResources UP-TO-DATE
:generatedClasses UP-TO-DATE
:generateGrammarSource

and a whole lot of missing symbol errors because the source code is generated after the compileGeneratedJava task is run. Why doesn't adding the dependsOn line to the compileJava task not force it to be fun first?

If I run generateGrammarSource on it's own before run, I get now errors, so I know the code generation is working properly.

I tried another posted solution to no avail. I can't seem to inject the task into the proper spot in the build cycle. How do I get generatedGrammarSource to run before the compilation steps?

Upvotes: 2

Views: 1137

Answers (1)

Jeffrey Guenther
Jeffrey Guenther

Reputation: 901

The problem is in the sourceSets block where I set srcDirs. It should be 'src/generated/java' instead of 'src/antlr/java'. The wrong directly was listed causing gradle not to see the generated source.

Upvotes: 2

Related Questions