Gradle:也在依赖项目上运行子项目任务

时间:2016-07-18 12:17:15

标签: gradle gradle-plugin

我遇到了以下问题: 我有一个包含多个子项目的主项目,每个项目都相互依赖。例如:

+---Main
    +- Shared
       +- Variant1
          +- Variant1A

如果我使用Variant1A:build命令在项目3上运行构建任务,那么所有其他项目也会构建。

我现在为每个子项目添加了一个deploy任务,如果我部署了一个项目,我想部署它依赖的每个项目,如下所示:

+---Main:deploy
    +- Shared:deploy
       +- Variant1:deploy
          +- Variant1A:deploy

但是,运行Variant1A:deploy仅运行Variant1A项目的任务:

+---Main:build
    +- Shared:build
       +- Variant1:build
          +- Variant1A:deploy

由于我有很多子项目和许多复杂的依赖项,我不想用dependsOn指定每个项目。
所以我正在寻找一种在build之类的所有本地项目上运行任务的方法,但是我不想将逻辑添加到build任务,因为它不应该被部署在正常的建设过程中...

1 个答案:

答案 0 :(得分:0)

从您的根项目的build.gradle中,您可能可以执行类似这样的操作

// look for deploy as a task argument sent via command line
def isDeploy
// could be many tasks supplied via command line
for (def taskExecutionRequest : gradle.startParameter.taskRequests) {
    // we only want to make sure deploy was specified as a task request
    if (taskExecutionRequest.args.contains('deploy')) {
        isDeploy = true
    }
}
// if deploy task was specified then setup dependant tasks
if (isDeploy) {
    // add the task to all subprojects of the `rootProject`
    subprojects.each {
        // get all projects that depend on this subproject
        def projectDependencies = project.configurations.runtime.getAllDependencies().withType(ProjectDependency)
        // the subproject's dependant projects may also have project dependencies
        def dependentProjects = projectDependencies*.dependencyProject
        // now we have a list of all dependency projects of this subproject
        // start setting up the dependsOn task logic
        dependentProjects.each {
            // find the deploy task then make our dependant
            // project's deploy task a dependant of the deploy task
            tasks.findByName('deploy').dependsOn project(it.name).tasks.findByName('deploy')
        }
    }
}