配置子项目后执行Gradle任务

use*_*070 9 gradle

我有一个多项目 Gradle 构建,其中子项目被分配独立于根项目的版本号。我想将此版本号注入到每个子项目中的几个资源文件中。通常,我会通过为根构建中的每个子项目配置 processResources 任务来完成此操作。然而,问题是 Gradle 似乎在加载子项目的构建文件之前执行 processResources 任务,并注入“未指定”作为版本。

目前,我的项目如下所示:

/设置.gradle

include 'childA' // ... and many others
Run Code Online (Sandbox Code Playgroud)

/build.gradle

subprojects {
    apply plugin: 'java'
    apply plugin: 'com.example.exampleplugin'
}

subprojects {
    // This has to be configured before processResources
    customPlugin {
        baseDir = "../common"
    }

    processResources {
        // PROBLEM: version is "unspecified" here
        inputs.property "version", project.version

        // Inject the version:
        from(sourceSets.main.resources.srcDirs) {
            include 'res1.txt', 'res2.txt', 'res3.txt'
            expand 'version':project.version
        }
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

/childA/build.gradle

version = "0.5.424"
Run Code Online (Sandbox Code Playgroud)

我考虑在root的开头添加evaluationDependsOnChildren()build.gradle,但这会导致错误,因为childA/build.gradlecustomPlugin { ... }. 我尝试过使用dependsOn、mustRunAfter和其他技术,但似乎都没有达到预期的效果。(也许我不太理解生命周期,但是好像根项目是在子项目之前配置和执行的。难道不应该配置根,然后配置子项目,然后执行吗?)

如何将每个子项目的版本注入到适当的资源文件中,而无需大量复制/粘贴或样板文件?

Vic*_*tor 10

您可以尝试使用此方法,并带有一个钩子:

gradle.projectsEvaluated({
   // your code
})
Run Code Online (Sandbox Code Playgroud)


Bor*_*per 5

我自己解决了这个问题。我正在使用 init.gradle 文件将某些内容应用到 rootProject,但我需要来自子项目的数据。

第一个选择是在修改每个子项目之前对其进行评估:

rootProject {
    project.subprojects { sub ->
        sub.evaluate()
        //Put your code here
Run Code Online (Sandbox Code Playgroud)

但我不确定强制子项目评估会产生什么副作用,所以我执行了以下操作:

allprojects {
    afterEvaluate { project ->
         //Put your code here
Run Code Online (Sandbox Code Playgroud)


tom*_*ulo 1

尝试这样做:

subprojects { project ->
    // your code
}
Run Code Online (Sandbox Code Playgroud)

否则project将引用未指定版本的根项目。

  • 尝试过,但 gradle 说“项目”没有这些属性,尽管我在子项目中设置它们。 (2认同)