Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
smeeb Avatar asked Feb 12 '23 06:02

smeeb


2 Answers

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}!"
    }
}
like image 66
Opal Avatar answered Feb 15 '23 09:02

Opal


As indicated in the Gradle documentation, you can filter subprojects and configure them this way:

configure(subprojects.findAll { it.name.endsWith("server") }) {
    apply plugin: 'com.google.cloud.tools.jib'
    jib {
       from {
          image = 'openjdk:alpine'
       }
    }
    ...
}
like image 38
LionH Avatar answered Feb 15 '23 11:02

LionH