gradlebuild.gradlewarsubprojectspring-boot-gradle-plugin

Modifying gradle task in a subproject


So, let's say I have this kind of project structure:

Root
    projA
        projA1-api
        projA2-core
        projA3-main
    projB
        projB1-api
        projB2-core
        projB3-main
    projC
        projC1-api
        projC2-core
        projC3-main
    and so on...

Some of the subprojects (the ones ending in "-main") have war and spring boot plugins applied to them, the root build.gradle file does not. That means that projects projA3-main, projB3-main and projC3-main have the bootWar task which disables the war task.

Now, the problem lies within the fact that our jenkins pipeline builds wars by executing the gradle war command, which sucks and can't be changed.

So, what I want to do is to modify the war task in each of the subprojects containing the war plugin by setting it to depend on the bootWar task. I can do this by adding war.dependsOn bootWar into the subprojects' build.gradle files and that works, but I want to extract that code into the root build.gradle.

Also, I want the war task to also execute another task (let's call it customPrintTask) defined in the root build.gradle which just prints stuff into some file.

To summarize:

Root build.gradle doesn't have, war, bootWar or Spring Boot plugins, but has the customPrintTask task

"-main" subprojects have bootWar and spring boot plugins, and they also have the war plugin, but because I am using Spring Boot 2+ gradle plugin, the war task does not generate the war.

Basically, I want something like this:

allprojects {
    if (project.plugins.hasPlugin("war")) {
        war.dependsOn bootWar
        war.finalizedBy customPrintTask
    }
}

I hope that makes sense.


Solution

  • Yo, figured it out.

    allprojects {
        tasks.withType(War) {
            if (it.name != "bootWar") {
                dependsOn(customPrintTask)
                dependsOn(":" + it.project.name.replace("-main", "") + ":" + it.project.name + ":bootWar")
            }
        } 
    }
    

    I know no one cares, but this way I iterated over every task with the type War and if the tasks name is not bootWar(because of circular dependency) then depend on my custom print task and also depend on the bootWar task which is located in the subproject I am currently iterating over, which is the reason it looks dumb.

    It's pretty simple, not sure how I missed this one...looks extremely ugly, but it works!