如何在构建时编译之前确保生成代码?

时间:2015-06-06 14:36:17

标签: gradle antlr

我有一个build.gradle,代码如下:

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
}

输出:

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

和大量遗漏符号错误,因为源代码是在compileGeneratedJava任务运行后生成的。为什么不将dependsOn行添加到compileJava任务中而不是强迫它首先变得有趣?

如果我在generateGrammarSource之前运行run,我现在会收到错误,所以我知道代码生成工作正常。

我尝试了另一个posted solution无济于事。我似乎无法将任务注入构建周期中的适当位置。如何在编译步骤之前运行generatedGrammarSource

1 个答案:

答案 0 :(得分:1)

问题出在我设置sourceSets的{​​{1}}块中。它应该是'src / generated / java'而不是'src / antlr / java'。列出了错误,导致gradle无法看到生成的源。