Sunday, September 11, 2011

Introduction to Gradle Part 3

In part 1 and 2, we built a simple Gradle build file for a Java project, war project, Groovy project , and finally a Gradle multi-build project.  We saw how these Gradle plugins worked and how to setup complex multi-project dependencies.  There is so much that groovy Gradle can do including OSGi, Scala, reports, and much more.  The documentation for Gradle builds can be found here.

Gradle customizations

Last, let's design some custom tasks.  Since, we are writing build scripts in Groovy, Gradle build custom tasks are simple and straight-forward.



(Project D/build.gradle)



import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction


class LumberghTask extends DefaultTask {
    def person = "Peter"
    def request = "Um... yah, I'm going to have to ask you to work this weekend."
   
    @TaskAction
    def greetEmployee() {
        println "Hello ${person} ... How's it going?"
        println request
    }
}

task hello(type: LumberghTask)

task requestWork(type: LumberghTask) {
    person = 'Samir'
    request = "Yah, if you could get those TPS reports to me, yah that would be great"
}


The script above is a custom task called the LumberghTask.  This task asks a variety of employees pointless and useless queries, but demonstrates how custom tasks work in Gradle.

The first step to run this task will be to call the hello target.  Execute the following task first:
gradle -q hello

Output:


Hello Peter ... How's it going?
Um... yah, I'm going to have to ask you to work this weekend.

Next, execute the following:


gradle -q requestWork


Output:

Hello Samir ... How's it going?
Yah, if you could get those TPS reports to me, yah that would be great

The requestWork overrides the person and request variables based on the task being called.  The taskHello is calling the LumberghTask directly. There are so many combinations available in Gradle, that reading the documentation provided here is highly recommended.  Gradle and Groovy provides maximum felxibility for any build environment.

No comments: