Sunday, November 09, 2014

Gradle : How to modify tasks post task graph creation

Gradle allows you to script your build file and add hooks in to the build lifecycle so you can maximize flexibility without complicating build setup and tasks.
One of the useful ways to manipulate all tasks once they are loaded by gradle into task execution graph is to use the whenReady lifecycle hook which only gets called when gradle  the complete tasks execution graph.This allows you to dynamically modify task properties, add new properties,etc. This comes helpful when you need to manipulate some tasks based on the user arguments passed in the project or some other project properties.

Below is the snippet that you need to add to make this work:
1:  gradle.taskGraph.whenReady {  
2:   tasks.each {  
3:    it.doFirst {   
4:     println "Calling ${}"  
5:    }  
6:   }  
7:  }  

 sgokak ~Todo $ gradle build  
 Calling compileJava  
 :processResources UP-TO-DATE  
 Calling classes  
 Calling war  
 Calling assemble  
 :compileTestJava UP-TO-DATE  
 :processTestResources UP-TO-DATE  
 Calling testClasses  
 :test UP-TO-DATE  
 Calling check  
 Calling build  

As you can see from the above output, the doFirst Closure  is only executed when the task is actually executed and not for any UP-TO-DATE tasks.