【问题标题】:Execute gradle task on sub projects在子项目上执行 gradle 任务
【发布时间】:2014-10-22 14:07:22
【问题描述】:

我有一个要配置的 MultiModule gradle 项目。

Root
    projA
    projB
    other
        projC
        projD
        projE
        ...

我想要做的是在根 build.gradle 中有一个任务,它将在另一个目录中的每个项目中执行 buildJar 任务。

我知道我能做到

configure(subprojects.findAll {it.name != 'tropicalFish'}) {
    task hello << { task -> println "$task.project.name"}
}

但这也会得到 projA 和 projB,我只想在 c,d,e 上运行任务... 请告诉我实现这一目标的最佳方法。

【问题讨论】:

    标签: gradle build.gradle multi-module


    【解决方案1】:

    不完全确定你追求的是哪一个,但它们应该涵盖你的基地。

    1.直接调用任务

    你应该可以打电话

    gradle :other/projC:hello :other/projD:hello
    

    我对此进行了测试:

    # Root/build.gradle
    allprojects {
        task hello << { task -> println "$task.project.name" }
    }
    

    # Root/settings.gradle
    include 'projA'
    include 'projB'
    include 'other/projC'
    include 'other/projD'
    

    2。仅在子项目中创建任务

    还是您只希望在其他/* 项目上创建任务?

    如果是后者,那么以下工作:

    # Root/build.gradle
    allprojects {
        if (project.name.startsWith("other/")) {
            task hello << { task -> println "$task.project.name" }
        }
    }
    

    然后可以调用它:

    $ gradle hello
    :other/projC:hello
    other/projC
    :other/projD:hello
    other/projD
    

    3.创建仅在子项目中运行任务的任务

    此版本与我对您问题的阅读相匹配,这意味着子项目 (buildJar) 上已经有一个任务,并在根目录中创建一个只会调用子项目 other/*:buildJar 的任务

    allprojects {
        task buildJar << { task -> println "$task.project.name" }
        if (project.name.startsWith("other/")) {
            task runBuildJar(dependsOn: buildJar) {}
        }
    }
    

    这会在每个项目上创建一个任务“buildJar”,并仅在其他/*项目上创建一个“runBuildJar”,因此您可以调用:

    $ gradle runBuildJar
    :other/projC:buildJar
    other/projC
    :other/projC:runBuildJar
    :other/projD:buildJar
    other/projD
    :other/projD:runBuildJar
    

    您的问题可以通过多种方式阅读,希望这涵盖了所有内容:)

    【讨论】:

    • 感谢您的回答。没有一个选项适合我的需要: 1. 我们需要知道所有子项目的列表。 2+3。需要修改构建脚本。最后,我找到了另一种方法来实现这一点,并将其添加为新答案。
    • @Marwin:你的答案在哪里?会感兴趣的。
    • @frhd 查看下面我的答案gradle -p other hello
    【解决方案2】:

    我今天发现了这个问题,因为我有同样的问题。 Mark 提到的所有方法都可以使用,但它们都有一些缺点。所以我又添加了一个选项:

    4.切换当前项目

    gradle -p other hello
    

    这会切换“当前项目”,然后运行当前项目下名为hello的所有任务。

    【讨论】:

    • 需要注意的是,这实际上会将工作目录切换到“其他”。因此,当没有“其他/build.gradle”文件时(我们使用父目录中的“子项目{...}”来配置子项目),这将失败。这就是为什么我推荐其他答案并改用“gradle:taskName”的原因。
    【解决方案3】:

    示例 5. 定义所有项目和子项目的共同行为,

    allprojects {
        task hello {
            doLast { task ->
                println "I'm $task.project.name"
            }
        }
    }
    subprojects {
        hello {
            doLast {
                println "- I depend on water"
            }
        }
    }
    

    从 Gradle 文档中, https://docs.gradle.org/current/userguide/multi_project_builds.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多