configurationbuildgradlesubproject

Gradle custom task only applied to certain subprojects?


I have created a custom herpderp Gradle task:

task herpderp(type: HerpDerpTask)

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

With this, I can add this task to other Gradle builds an use it inside build invocations for other projects:

gradle clean build herpderp

Now, I have the following multi-project setup:

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

Where myapp/build.gradle is:

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

    repositories {
        mavenLocal()
        mavenCentral()
    }

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

And where myapp/settings.gradle is:

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

I would like to be able to navigate to the parent myapp directory, and run gradler clean build herpderp and have the herpderp task only run on the myapp-client and myapp-shared projects (not the server project).

So it sounds like I need either another custom task or some type of closure/method inside myapp/build.gradle that:

  1. Runs clean build; then
  2. Drops (cd) into myapp-client and runs herpderp; and then
  3. Drop into myapp-shared and runs herpderp.

What do I need to add to any of my files in order to get herpderp invoked from the parent build command, but only executed in the client and shared subprojects?


Solution

  • The following piece of code can do the trick (should be placed in 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}!"
        }
    }