Gradle (http://www.gradle.org/) is a build and automation tool written in Java/Groovy, which makes use of a Groovy-based DSL for defining declarative and imperative build scripts. Gradle brings a lot of innovation into the Java/Groovy build tool space, and at a fast pace is replacing other popular tools. At the same time, it builds upon the best practices and foundations of those tools, such as project conventions standardization and dependency management.
In this recipe, we will demonstrate how Gradle can simplify the compilation and testing of a complete Groovy project.
We will build the same example Groovy project defined in the Integrating Groovy into the build process using Ant recipe. We assume that you have at least some familiarity with Gradle, and it is already installed on your system. Otherwise, you can refer to the installation page (http://www.gradle.org/docs/current/userguide/installation.html) of the Gradle User Guide.
At first glance, a Gradle script may seem too simple to be actually functional. This is one of the strengths of the product: simplicity and power.
build.gradle
script:apply plugin: 'groovy' group = 'org.groovy.cookbook' repositories { mavenCentral() } dependencies { compile 'org.codehaus.groovy:groovy-all:2.1.6' testCompile 'junit:junit:4.10' }
gradle clean test
:clean :compileJava UP-TO-DATE :compileGroovy :processResources UP-TO-DATE :classes :compileTestJava UP-TO-DATE :compileTestGroovy :processTestResources UP-TO-DATE :testClasses :test BUILD SUCCESSFUL Total time: 9.989 secs
As you can probably guess, all the logic required for Groovy integration is built into the groovy
plugin declared on the first line of the build script. The remaining content of the script has the following functions:
groupdId
in case we decide to build a JAR and deploy it to some repositorymavenCentral
methodcompile
and for testCompile
configurations, which are defined by the groovy
plugin and which are used at respective build stagesUpon build completion, the code will be compiled and tested. The result of the build activity including compiled classes and JUnit report files will be located in the automatically created build
directory.
The Gradle build script language is actually a Groovy DSL. That's why you can define tasks directly using Groovy. For example, you can add an info
task that prints the project test code dependencies:
task info << { println "Name: $project.name" println 'Dependencies: ' project.configurations.testCompile.allDependencies.each { println it.name } }
To execute the task, you can just type gradle info
.
A more detailed introduction to Gradle features is out of scope for this recipe, and it's actually worth a separate book.