Gradle自定义任务仅适用于某些子项目?

时间:2014-12-28 17:53:17

标签: configuration build gradle subproject

我创建了一个自定义herpderp Gradle任务:

task herpderp(type: HerpDerpTask)

class HerpDerpTask extends DefaultTask {
    @TaskAction
    def herpderp() {
        println "Herp derp!"
    }
}

有了这个,我可以将这个任务添加到其他Gradle构建中,在其他项目的构建调用中使用它:

gradle clean build herpderp

现在,我有以下多项目设置:

myapp/
    myapp-client/
        build.gradle
        src/** (omitted for brevity)
    myapp-shared/
        build.gradle
        src/** (omitted for brevity)
    myapp-server
        build.gradle
        src/** (omitted for brevity)
    build.gradle
    settings.gradle

myapp/build.gradle的位置:

subprojects {
    apply plugin: 'groovy'
    sourceCompatibility = '1.7'
    targetCompatibility = '1.7'

    repositories {
        mavenLocal()
        mavenCentral()
    }

    dependencies {
        compile (
            'org.codehaus.groovy:groovy-all:2.3.7'
        )
    }
}

myapp/settings.gradle在哪里:

include ':myapp-shared'
include ':myapp-client'
include ':myapp-server'

我希望能够导航到父myapp目录,并运行gradler clean build herpderp并让herpderp任务仅在myapp-client和{{1}上运行项目(不是服务器项目)。

所以听起来我需要另一个自定义任务或myapp-shared内的某种类型的闭包/方法:

  1. 运行myapp/build.gradle;然后
  2. clean build投放到cd并运行myapp-client;然后
  3. 放入herpderp并运行myapp-shared
  4. 我需要向我的文件的任何添加什么才能从父版本命令调用herpderp,但只在客户端和共享子项目中执行?

2 个答案:

答案 0 :(得分:5)

以下代码可以解决问题(应该放在myapp/build.gradle中):

allprojects.findAll { it.name in ['myapp-client', 'myapp-shared'] }. each { p ->
   configure(p) {
      task herpderp(type: HerpDerpTask)
   }
}

class HerpDerpTask extends DefaultTask {
    @TaskAction
    def herpderp() {
        println "Herp derp from ${project.name}!"
    }
}

答案 1 :(得分:1)

Gradle documentation中所述,您可以过滤子项目并通过以下方式对其进行配置:

configure(subprojects.findAll { it.name.endsWith("server") }) {
    apply plugin: 'com.google.cloud.tools.jib'
    jib {
       from {
          image = 'openjdk:alpine'
       }
    }
    ...
}