Gradle

A build system

Version 0.6-20090510124442+1000

Hans Dockter

Adam Murdoch

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Table of Contents

1. Introduction
2. Overview
2.1. Features
2.2. Why Groovy?
2.3. Missing Features
3. Getting Started
3.1. Prerequisites
3.2. Unpacking
3.3. Environment variables
3.4. Running and testing your installation
3.5. JVM Options
4. Build Script Basics
4.1. Hello World
4.2. Build scripts are code
4.3. Task dependencies
4.4. Dynamic tasks
4.5. Manipulating existing tasks
4.6. Shortcut notations
4.7. Dynamic Task Properties
4.8. Ant
4.9. Using methods
4.10. Default Tasks
4.11. Configure By DAG
4.12. Summary
5. Artifact Basics
5.1. Artifact Configurations
5.2. Repositories
5.3. External Dependencies
5.4. Artifact Publishing
5.5. API
6. Java Quickstart
6.1. A Basic Java Project
6.2. Multi-project Java Build
6.3. Summary
7. Groovy Quickstart
7.1. Using the Groovy Plugin
7.2. Summary
8. Web Application Quickstart
8.1. Building A WAR
8.2. Running Your Web Application
9. Using the Gradle Command-Line
9.1. Executing multiple tasks
9.2. Selecting which build to execute
10. Tutorial - 'This and That'
10.1. Skipping Tasks
10.2. Obtaining Information About Your Build
10.3. Directory Creation
10.4. Gradle Properties and System Properties
10.5. Accessing the web via a proxy
10.6. Caching
10.7. Configuring Arbitrary Objects
11. The Project and Task API
11.1. Project API
11.2. Task API
11.3. Summary
12. More about Tasks
12.1. Defining Tasks
12.2. Locating Tasks
12.3. Configuring Tasks
12.4. Adding Dependencies to Tasks
12.5. Replacing Tasks
12.6. Summary
13. Logging
13.1. Choosing a log level
13.2. External Tools and Standard Output
13.3. Sending your own log messages
14. Plugins
14.1. Declaring Plugins
14.2. Configuration
14.3. Summary
15. The Java Plugin
15.1. Init
15.2. Javadoc
15.3. Clean
15.4. Resources
15.5. Compile
15.6. Test
15.7. Bundles
15.8. Archive Tasks
15.9. Upload
15.10. Eclipse
16. The Groovy Plugin
16.1. Compile
16.2. Test
17. The War Plugin
17.1. Default Settings
17.2. Customizing
17.3. Eclipse WTP
18. The OSGi Plugin
19. The Project Reports Plugin
20. Dependency Management
20.1. Introduction
20.2. How to declare your dependencies
20.3. Java Plugin and Dependency Management
20.4. Strategies of transitive dependency management
20.5. Repositories and Resolvers
21. Interacting with Maven Repositories
21.1. Introduction
21.2. Deploying to a Maven Repository
21.3. Maven Pom Generation
22. The Build Lifecycle
22.1. Build Phases
22.2. Settings File
22.3. Multi-Project Builds
22.4. Initialization
22.5. Configuration and Execution of a Single Project Build
22.6. Responding to the Lifecycle in the Build Script
23. Multi-project Builds
23.1. Cross Project Configuration
23.2. Subproject Configuration
23.3. Execution rules for multi-project builds
23.4. Running Tasks by their Absolute Path
23.5. Project and Task Paths
23.6. Dependencies - Which dependencies?
23.7. Project Lib Dependencies
23.8. Property and Method Inheritance
23.9. Summary
24. Organizing Build Logic
24.1. Build Sources
24.2. External dependencies
24.3. Ant Optional Dependencies
24.4. Summary
25. The Gradle Wrapper
25.1. Configuration
25.2. Unix file permissions
25.3. Environment variable
A. Potential Traps
A.1. Groovy Script Variables
A.2. Configuration and Execution Phase
B. Gradle Command Line
C. Existing IDE Support and how to cope without it
C.1. IntelliJ
C.2. Eclipse
C.3. Using Gradle without IDE support

Chapter 1. Introduction

We would like to introduce Gradle to you, a build system that we think is a quantum leap for build technology in the Java (JVM) world. Gradle provides:

  • A very flexible general purpose build tool like Ant.

  • Switchable, build-by-convention frameworks a la Maven. But we never lock you in!

  • Very powerful support for multi-project builds.

  • Very powerful dependency management (based on Apache Ivy).

  • Full support for your existing Maven or Ivy repository infrastructure.

  • Support for transitive dependency management without the need for remote repositories or pom.xml and ivy.xml files.

  • Ant tasks as first class citizens.

  • Groovy build scripts.

  • A rich domain model for describing your build.

In Chapter 2, Overview you will find a detailed overview of Gradle. Otherwise, the tutorials are waiting, have fun :)

Chapter 2. Overview

2.1. Features

Here is a list of some of Gradle's features.

Language for Dependency Based Programming

This is the core of Gradle. Most build tools do offer such a thing. You can create tasks, create dependencies between them and those tasks get executed only once and in the right order. Yet compared to Ant [1] Gradle's task offer a rich API and can be any kind of object. Gradle's tasks support multi-project builds. There is much more to say about tasks later on.

Flexible Build By Convention

Gradle offers you build-by-convention on top of its core layer. It is the same idea as implemented by Maven. But Gradle's build-by-convention approach is highly configurable and flexible. And you don't have to use it, if you need utmost flexibility. You can enable/disable it on a per project basis in a multi-project build.

Ant Tasks

Ant tasks are first class citizens. Using Ant tasks from Gradle is as convenient and more powerful than using Ant tasks from a build.xml file.

Configure By DAG

Gradle has a distinct configuration and execution phase. Thus we can offer you special hooks. You can add configuration to your build, based on the complete execution graph of tasks, before any task is executed.

Easy Ivy

Our dependency management is based on Apache Ivy, the most advanced and powerful dependency management in the Java world. We have Ivy integrated in our build-by-convention framework. It is ready to go out-of-the-box. Ivy is mostly used via its Ant tasks but it also provides an API. Gradle integrates deeply with Ivy via this API. Gradle has its own dependency DSL on top of Ivy. This DSL introduces a couple of features not provided by Ivy itself.

Client Modules

We think dependency management is important to any project. Client Modules provide this, without the need of remote repositories and ivy.xml or pom.xml files. For example you can just put your jars into svn and yet enjoy complete transitive dependency management. Gradle also support fully Ivy or Maven repository infrastructures based on ivy.xml or pom.xml files and remote repositories.

Cross Project Configuration

Enjoy how easy and yet how extremely powerful the handling of multi-project builds can be. Gradle introduces Configuration Injection to make this possible.

Distinct Dependency Hierarchies

We allow you to model the project relationships in a multi-project build as they really are for your problem domain. Gradle follows your layout not vice versa.

Partial Builds

With Maven multi-project builds only work if executed from the root project and thus requiring a complete build. If you build from a subproject, only the subproject is build, not the projects the subproject depends on. Gradle offers partial builds. The subproject is build plus the projects it depends on. This is very convenient for larger builds.

Internal Groovy DSL

Gradle's build scripts are written in Groovy, not XML. This offers many advantages to XML: Rich interaction with existing libraries, ease of use, more power and a slower learning curve are some of them.

The Gradle Wrapper

The Gradle Wrapper allows you to execute Gradle builds on machines where Gradle is not installed. For example continuous integration servers or machines of users which want to build your open source project.

Gradle scales very well. It significantly increases your productivity, from rather simple single project builds up to huge enterprise multi-project builds.

Gradle is build by Gradle. From a build perspective Gradle is a simple project. But achieving the high degree of automation we have, would have been very hard (and expensive) to achieve with Ant or Maven.

2.2. Why Groovy?

We think the advantages of an internal DSL (based on a dynamic language) over XML are tremendous in case of build scripts. There are a couple of dynamic languages out there. Why Groovy? The answer lies in the context Gradle is operating in. Although Gradle is a general purpose build tool at its core, its main focus are Java projects. [2] In such projects obviously the team members know Java. One problem we see with Ant [3] and Maven is, that it involves a lot of knowledge only available to the build master. Such builds are very hard to comprehend, let alone to modify by a person not deeply involved with those tools. We think a build should be as transparent as possible to all team members.

You might argue why not using Java then as the language for build scripts. We think this is a valid question. It would have the highest transparency for your team and the lowest learning curve. But due to limitations of Java such a build language would not be as nice, expressive and powerful as it could be. [4] Languages like Python, Groovy or Ruby do a much better Job here. We have chosen Groovy as it offers by far the highest transparency for Java people. Its base syntax is the same as Java's as well as its type system, its package structure other things. Groovy builds a lot on top of that. But on a common ground with Java.

For Java teams which share also Python or Ruby knowledge or are happy to learn it the above arguments don't apply. In the near future Gradle wants to give you a choice between different languages for your build scripts. For Jython or JRuby this should be easy to implement. If members of those communities are interested in joining this effort, this is very much appreciated.

2.3. Missing Features

Here a list of features you might expect but are not available yet:

  • Creating IDE project and classpath files. This is one of the top priorities for the next release. We want to provide this for IntelliJ, Eclipse and NetBeans.

  • Integration for Emma, Cobertura and JDepends in our build-by-convention framework. Right now you have to integrate them yourself (for example with the Ant tasks for those tools).

  • Integration of Jetty in our build-by-convention framework to allow easy startup of a web application.

  • Integration of TestNG in our build-by-convention framework.



[1] We mean Ant's targets here.

[2] Gradle also supports Groovy projects. Gradle will support Scala projects in a future release.

[3] If the advanced features are used (e.g. mixins, macrodefs, ...)

[4] At http://www.defmacro.org/ramblings/lisp.html you find an interesting article comparing Ant, XML, Java and Lisp. It's funny that the 'if Java had that syntax' syntax in this article is actually the Groovy syntax.

Chapter 3. Getting Started

3.1. Prerequisites

Gradle requires a Java JDK to be installed. Gradle ships with its own Groovy library, therefore no Groovy needs to be installed. Any existing Groovy installation is ignored by Gradle. The standard Gradle distribution requires a JDK 1.5 or higher. We also provide a distinct JDK 1.4 compatible distribution.

Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.

3.2. Unpacking

The Gradle distribution comes packaged as a zip. The distribution contains:

  • The Gradle binaries.

  • The userguide (HTML and PDF).

  • The Javadoc HTML pages.

  • Extensive samples, including the examples referenced in the userguide, along with some larger and more complex builds you can use as starting points for your own build.

  • The binary sources (If you want to build Gradle you need to download the source distribution or checkout the sources from the source repository).

For Un*x users

You need a GNU compatible tool to unzip Gradle, if you want the file permissions to be properly set. We mention this as some zip front ends for Mac OS X don't restore the file permissions properly.

3.3. Environment variables

For running Gradle, add GRADLE_HOME/bin to your PATH environment variable. Usually, this is sufficient to run Gradle. Optionally, you may also want to set the GRADLE_HOME environment variable to point to the root directory of your Gradle installation.

3.4. Running and testing your installation

You run Gradle via the gradle command. To check if Gradle is properly installed just type gradle -v and you should get an output like:

----------------------------------------
Gradle 0.5.2
----------------------------------------

Gradle buildtime: Thursday, January 8, 2009 10:23:01 PM CET
Groovy: 1.5.6
Ant: Apache Ant version 1.7.0 compiled on December 13 2006
Ivy: 2.0.0-rc2
Java: 1.5.0_16
JVM: 1.5.0_16-133
JVM Vendor: Apple Inc.
OS Name: Mac OS X

3.5. JVM Options

JVM options for running Gradle can be set via environment variables. You can use GRADLE_OPTS or JAVA_OPTS. Those variables can be used together. JAVA_OPTS is by convention an environment variable shared by many Java applications. A typical use case would be to set the HTTP proxy in JAVA_OPTS and the memory options in GRADLE_OPTS. Those variables can also be set at the beginning of the gradle or gradlew script.

Chapter 4. Build Script Basics

You run a build using the gradle command. When run, gradle normally looks for a file called build.gradle in the current directory. [5] We call this build.gradle file a build script, although strictly speaking it is a build configuration script, as we will see later. In Gradle the location of the build script file defines a project. The name of the directory containing the build script is used as the name of the project.

4.1. Hello World

In Gradle the most basic building block is the task. The tasks for your build are defined in the build script. To try this out, create the following build script named build.gradle.

Example 4.1.  build.gradle

task hello {
    println 'Hello world!'
}

In a command-line shell, enter into the containing directory and execute the build script by running gradle -q hello: [6] [7]

Example 4.2. Output of gradle -q hello

> gradle -q hello
Hello world!

If you think this looks damn similar to Ant's targets, well, you are right. Gradle tasks are the equivalent to Ant targets. But as you will see, they are much more powerful. We have used a different terminology to Ant as we think the word task is more expressive than the word target . Unfortunately this introduces a terminology clash with Ant, as Ant calls its commands, such as javac or copy, tasks. So when we talk about tasks, we always mean Gradle tasks, which are the equivalent to Ant's targets. If we talk about Ant tasks (Ant commands), we explicitly say ant task.

4.2. Build scripts are code

Gradle's build scripts expose to you the full power of Groovy. As an appetizer, have a look at this:

Example 4.3.  build.gradle

task upper {
    String someString = 'mY_nAmE'
    println "Original: " + someString 
    println "Upper case: " + someString.toUpperCase()
}

Example 4.4. Output of gradle -q upper

> gradle -q upper
Original: mY_nAmE
Upper case: MY_NAME

or

Example 4.5.  build.gradle

task count {
    4.times { print "$it " }
}

Example 4.6. Output of gradle -q count

> gradle -q count
0 1 2 3

4.3. Task dependencies

As you probably have guessed, you can declare dependencies between your tasks.

Example 4.7.  build.gradle

task hello {
    println 'Hello world!'
}
task intro(dependsOn: hello) {
    println "I'm Gradle"
}

Example 4.8. Output of gradle -q intro

> gradle -q intro
Hello world!
I'm Gradle

To add a dependency, the corresponding task does not need to exist.

Example 4.9.  build.gradle

task taskX(dependsOn: 'taskY') {
    println 'taskX'
}
task taskY {
    println 'taskY'
}

Example 4.10. Output of gradle -q taskX

> gradle -q taskX
taskY
taskX

The dependency of taskX to taskY is declared before taskY is created. This is very important for multi-project builds. Task dependencies are discussed in more detail in Section 12.4, “Adding Dependencies to Tasks”.

4.4. Dynamic tasks

The power of Groovy be used for more than definining what a task does. For example, you can also use it to dynamically create tasks.

Example 4.11.  build.gradle

4.times { counter ->
    task "task_$counter" {
        println "I'm task number $counter"
    }
}

Example 4.12. Output of gradle -q task_1

> gradle -q task_1
I'm task number 1

4.5. Manipulating existing tasks

Once tasks are created they can be accessed via an API. This is different to Ant. For example you can create additional dependencies.

Example 4.13.  build.gradle

4.times { counter ->
    task "task_$counter" {
        println "I'm task number $counter"
    }
}
task('task_0').dependsOn 'task_2', 'task_3'

Example 4.14. Output of gradle -q task_0

> gradle -q task_0
I'm task number 2
I'm task number 3
I'm task number 0

Or you can add behavior to an existing task.

Example 4.15.  build.gradle

task hello {
    println 'Hello Earth'
}
task('hello').doFirst {
    println 'Hello Venus'
}
task('hello').doLast {
    println 'Hello Mars'
}

Example 4.16. Output of gradle -q hello

> gradle -q hello
Hello Venus
Hello Earth
Hello Mars

The calls doFirst and doLast can be executed multiple times. They add an action to the beginning or the end of the task's actions list. When the task executes, the actions in the action list are executed in order.

4.6. Shortcut notations

There is a convenient notation for accessing existing tasks.

Example 4.17.  build.gradle

task hello {
    println 'Hello world!'
}
hello.doLast {
    println 'Hello again!'
}

Example 4.18. Output of gradle -q hello

> gradle -q hello
Hello world!
Hello again!

This enables very readable code. Especially when using the out of the box tasks provided by the plugins (e.g. compile).

4.7. Dynamic Task Properties

You can assign arbitrary new properties to any task.

Example 4.19.  build.gradle

task myTask
myTask.myProperty = 'myCustomPropValue'

task showProps {
    println myTask.myProperty
}

Example 4.20. Output of gradle -q showProps

> gradle -q showProps
myCustomPropValue

4.8. Ant

Let's talk a little bit about Gradle's Ant integration. Ant can be divided into two layers. The first layer is the Ant language. It contains the syntax for the build.xml, the handling of the targets, special constructs like macrodefs, etc. Basically everything except the Ant tasks and types. Gradle does not offer any special integration for this first layer. Of course you can in your build script execute an Ant build as an external process. Your build script may contain statements like: "ant clean compile".execute(). [8]

The second layer of Ant is its wealth of Ant tasks and types, like javac, copy or jar. For this layer Gradle provides excellent integration simply by relying on Groovy. Groovy is shipped with the fantastic AntBuilder. Using Ant tasks from Gradle is as convenient and more powerful than using Ant tasks from a build.xml file. Let's look at an example:

Example 4.21.  build.gradle

task checksum {
    File[] files = new File('../antChecksumFiles').listFiles()
    Arrays.sort(files)
    files.each { File file ->
        ant.checksum(file: file.canonicalPath, property: file.name)
        println "$file.name Checksum: ${ant.antProject.properties[file.name]}"
    }
}

Example 4.22. Output of gradle -q checksum

> gradle -q checksum
agile_manifesto.html Checksum: 2dd24e01676046d8dedc2009a1a8f563
agile_principles.html Checksum: 659d204c8c7ccb5d633de0b0d26cd104
dylan_thomas.txt Checksum: 91040ca1cefcbfdc8016b1b3e51f23d3

In your build script, a property called ant is provided by Gradle. It is a reference to an instance of Groovy's AntBuilder. The AntBuilder is used the following way:

  • Ant task names corresponds to AntBuilder method names.

  • Ant tasks attributes are arguments for this methods. The arguments are passed in from of a map.

  • Nested Ant tasks corresponds to method calls of the passed closure.

To learn more about the Ant Builder have a look in GINA 8.4 or at the Groovy Wiki

4.9. Using methods

Gradle scales in how you can organize your build logic. The first level of organizing your build logic for the example above, is extracting a method.

Example 4.23.  build.gradle

task checksum {
    fileList('../antChecksumFiles').each { File file ->
        ant.checksum(file: file.canonicalPath, property: file.name)
        println "$file.name Checksum: ${ant.antProject.properties[file.name]}"
    }
}

task length {
    fileList('../antChecksumFiles').each { File file ->
        ant.length(file: file.canonicalPath, property: file.name)
        println "$file.name Length: ${ant.antProject.properties[file.name]}"
    }
}

File[] fileList(String dir) {
    File[] files = new File(dir).listFiles()
    Arrays.sort(files)
    files
}

Example 4.24. Output of gradle -q checksum

> gradle -q checksum
agile_manifesto.html Checksum: 2dd24e01676046d8dedc2009a1a8f563
agile_principles.html Checksum: 659d204c8c7ccb5d633de0b0d26cd104
dylan_thomas.txt Checksum: 91040ca1cefcbfdc8016b1b3e51f23d3

Later you will see that such methods can be shared among subprojects in multi-project builds. If your build logic becomes more complex, Gradle offers you other very convenient ways to organize it. We have devoted a whole chapter to this. See Chapter 24, Organizing Build Logic.

4.10. Default Tasks

Gradle allows you to define one or more default tasks for your build.

Example 4.25.  build.gradle

defaultTasks "clean", "run"

task clean {
    println "Default Cleaning!"
}

task run {
    println "Default Running!"
}

task other {
    println "I'm not a default task!"
}

Example 4.26. Output of gradle -q

> gradle -q
Default Cleaning!
Default Running!

This is equivalent to running gradle clean run. In a multi-project build every subproject can have its own specific default tasks. If a subproject does not specify default tasks, the default tasks of the parent project are used (if defined).

4.11. Configure By DAG

As we describe in full detail later (See Chapter 22, The Build Lifecycle) Gradle has a configuration phase and an execution phase. After the configuration phase Gradle knows all tasks that should be executed. Gradle offers you a hook to make use of this information. A usecase for this would be to check if the release task is part of the tasks to be executed. Depending on this you can assign different values to some variables.

Example 4.27.  build.gradle

build.taskGraph.whenReady {taskGraph ->
    if (taskGraph.hasTask(':release')) {
        version = '1.0'
    } else {
        version = '1.0-SNAPSHOT'
    }
}

task distribution {
    println "We build the zip with version=$version"
}
task release(dependsOn: 'distribution') {
    println 'We release now'
}

Example 4.28. Output of gradle -q release

> gradle -q release
We build the zip with version=1.0
We release now

The important thing is, that the fact that the release task has been choosen, has an effect before the release task gets executed. Nor has the release task to be the primary task (i.e. the task passed to the gradle command).

4.12. Summary

This is not the end of the story for tasks. So far we have worked with simple tasks. Tasks will be revisited in Chapter 12, More about Tasks and when we look at the Java Plugin in Chapter 15, The Java Plugin.



[5] There are command line switches to change this behavior. See Appendix B, Gradle Command Line)

[6] Every code sample in this chapter can be found in the samples dir of your Gradle distribution. The output box always denotes the directory name relative to the samples dir.

[7] The scripts are executed with the -q option which suppresses the Gradle logging. See Chapter 13, Logging for more details.

[8] In Groovy you can execute Strings. To learn more about executing external processes with Groovy have a look in GINA 9.3.2 or at the Groovy wiki

Chapter 5. Artifact Basics

This chapter is a work in progress.

This chapter introduces some of the basics of artifact handling in Gradle.

5.1. Artifact Configurations

Artifacts are grouped into configurations. A configuration is simply a set of files with a name. You can use them to declare the external dependencies your project has, or to declare the artifacts which your project publishes.

To define a configuration:

Example 5.1.  build.gradle

configurations {
    compile
}

To access a configuration:

Example 5.2.  build.gradle

println configurations.compile.name
println configurations['compile'].name

To configure a configuration:

Example 5.3.  build.gradle

configurations {
    compile {
        description = 'compile classpath'
        transitive = true
    }
}
configurations.compile {
    description = 'compile classpath'
}

5.2. Repositories

Artifacts are stored in repositories.

To use maven central repository:

Example 5.4.  build.gradle

repositories {
    mavenCentral()
}

To use a local directory:

Example 5.5.  build.gradle

repositories {
    flatDir(name: 'localRepository', dirs: 'lib')
}

You can also use any Ivy resolver. You can have multiple repositories.

To access a repository:

Example 5.6.  build.gradle

println repositories.localRepository.name
println repositories['localRepository'].name

To configure a repository:

Example 5.7.  build.gradle

repositories {
    localRepository {
        addArtifactPattern(file('lib').absolutePath + '/[name]/[revision]/[name]-[revision].[ext]')
    }
}
repositories.localRepository {
    addArtifactPattern(file('lib').absolutePath + '/[name]/[revision]/[name]-[revision].[ext]')
}

5.3. External Dependencies

To define an external dependency, you add a dependency to a configuration:

Example 5.8.  build.gradle

configurations {
    compile
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
}

group and version are optional

TBD - configuring an external dependency

To use the external dependencies of a configuration:

Example 5.9.  build.gradle

task listJars {
    configurations.compile.each { File file -> println file.name }
}

Example 5.10. Output of gradle -q listJars

> gradle -q listJars
commons-collections-3.2.jar

5.4. Artifact Publishing

TBD

5.5. API

Configurations are contained in a ConfigurationContainer . Each configuration implements the Configuration .

Chapter 6. Java Quickstart

To build a Java project, you use the Java Plugin. This plugin adds some tasks to your project, along with some configuration properties, which will compile and test your Java source code, and bundle it into a JAR file. We have in-depth coverage with many examples about the Java plugin, dependency management and multi-project builds in later chapters. In this chapter we want to give you an initial idea of how to build a Java project.

6.1. A Basic Java Project

Let's look at a simple example. To use the Java plugin, add the following to your build file:

Example 6.1.  build.gradle

usePlugin 'java'

Note: The code for this example can be found at samples/java/quickstart

This is all you need to define a Java project. This will apply the Java plugin to your project, which adds a number of tasks to your project.

What Tasks Are Available?

You can use gradle -t to list the tasks of a project. This will let you see the tasks that the Java plugin has added to your project.

Executing gradle libs will compile, test and jar your code. Gradle looks for your production source code under src/main/java and your test source code under src/test/java. In addition, any files under src/main/resources will be included in the JAR file as resources, and any files under src/test/resources will be included in the classpath used to run the tests. All output files will end up under the build directory.

You can find out more about the Java plugin in Chapter 15, The Java Plugin.

6.1.1. External Dependencies

Usually, a Java project will have some dependencies on external JAR files. To reference these JAR files in the project, you need to tell Gradle where to find them. In Gradle, artifacts such as JAR files, are located in a repository. A repository can be used for fetching the dependencies of a project, or for publishing the artifacts of a project, or both. For this example, we will use the public Maven repository:

Example 6.2.  build.gradle

repositories {
    mavenCentral()
}

Let's add some dependencies. Here, we will declare that our production classes have a compile-time dependency on commons collections, and that our test classes have a compile-time dependency on junit:

Example 6.3.  build.gradle

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

You can find out more in Chapter 20, Dependency Management.

6.1.2. Customising the Project

The Java plugin adds a number of properties to your project. These properties have default values which are usually sufficient to get started. It's easy to change these values if they don't suit. Let's look at this for our sample. Here we will specify the version number for our Java project, along with the Java version our source is written in. We also add some attributes to the JAR manifest.

Example 6.4.  build.gradle

sourceCompatibility = 1.5
version = '1.0'
manifest.mainAttributes(
    'Implementation-Title': 'Gradle Quickstart',
    'Implementation-Version': version
)

What properties are available?

You can use gradle -r to list the properties of a project. This will allow you to see the properties added by the Java plugin, and their default values.

The tasks which the Java plugin adds are regular tasks, exactly the same as if they were declared in the build file. This means you can use any of the mechanisms shown in earlier chapters to customise these tasks. For example, you can set the properties of a task, add behaviour to a task, change the dependencies of a task, or replace a task entirely. In our sample, we will configure the test task, which is of type Test , to add a system property when the tests are executed:

Example 6.5.  build.gradle

test {
    options.systemProperties['property'] = 'value'
}

6.1.3. Publishing the JAR File

Usually the JAR file needs to be published somewhere. To do this, you need to tell Gradle where to publish the JAR file. In Gradle, artifacts such as JAR files are published to repositories. In our sample, we will publish to a local directory. You can also publish to a remote location, or multiple location.

Example 6.6.  build.gradle

uploadMaster {
    repositories {
       flatDir(dirs: file('repos'))
    }
}

To publish the JAR file, run gradle uploadMaster.

6.1.4. Summary

Here's the complete build file for our sample:

Example 6.7.  build.gradle

usePlugin 'java'

sourceCompatibility = 1.5
version = '1.0'
manifest.mainAttributes(
    'Implementation-Title': 'Gradle Quickstart',
    'Implementation-Version': version
)

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

test {
    options.systemProperties['property'] = 'value'
}

uploadMaster {
    repositories {
       flatDir(dirs: file('repos'))
    }
}

6.2. Multi-project Java Build

Now let's look at a typical multi-project build. Below is the layout for the project:

Figure 6.1. Project layout

multiproject/
  api/
  services/
    webservice/
  shared/

Note: The code for this example can be found at samples/java/multiproject

Here we have three projects. Project api produces a JAR file which is shipped to the client to provide them a Java client for your XML webservice. Project webservice is a webapp which returns XML. Project shared contains code used both by api and webservice.

6.2.1. Defining a Multi-Project Build

To define a multi-project build, you need to create a settings file. The settings file lives in the root directory of the source tree, and specifies which projects to include in the build. It must be called settings.gradle. For this example, we are using a simple hierarchical layout. Here is the corresponding settings file:

Example 6.8.  settings.gradle

include "shared", "api", "services:webservice"

You can find out more about the settings file in Chapter 23, Multi-project Builds.

6.2.2. Common Configuration

For most multi-project builds, there is some configuration which is common to all projects. In our sample, we will define this common configuration in the root project, using a technique called configuration injection. Here, the root project is like a container and the subprojects method iterates over the elements of this container - the projects in this instance - and injects the specified configuration. This way we can easily define the manifest content for all archives, and some common dependencies:

Example 6.9.  build.gradle

subprojects {
    usePlugin 'java'

    repositories {
       mavenCentral()
    }

    dependencies {
        testCompile 'junit:junit:4.4'
    }

    group = 'org.gradle'
    version = '1.0'
    manifest.mainAttributes(provider: 'gradle')
}

Notice that our sample applies the Java plugin to each subproject. This means the tasks and configuration properties we have seen in the previous section are available in each subproject. So, you can compile, test, and JAR all the projects by running gradle libs from the root project directory.

6.2.3. Dependencies Between Projects

You can add dependencies between projects in the same build, so that, for example, the JAR file of one project is used to compile another project. In the api build file we will add a dependency on the JAR produced by the shared project. Due to this dependency, Gradle will ensure that project shared always gets built before project api.

Example 6.10.  api/build.gradle

dependencies {
    compile project(':shared')
}

6.2.4. Creating a Distribution

We also add a distribution, that gets shipped to the client:

Example 6.11.  api/build.gradle

task dist(type: Zip)
dist {
    dependsOn configurations.runtime.buildDependencies
    files configurations.runtime
    fileSet dir: 'src/dist'
}

6.3. Summary

In this chapter, you have seen how to do some of the things you commonly need to build a Java based project. This chapter is not exhaustive, and there are many other things you can do with Java projects in Gradle. These are dealt with in later chapters. Also, a lot of the behaviour you have seen in this chapter is configurable. For example, you can change where Gradle looks Java source files, or add extra tasks, or you can change what any task actually does. Again, you will see how this works in later chapters.

Finally, you can find more sample projects in the samples/java directory in the Gradle distribution.

Chapter 7. Groovy Quickstart

To build a Groovy project, you use the Groovy Plugin. This plugin extends the Java plugin to add Groovy compilation capabilties to your project. Your project can contain Groovy source code, Java source code, or a mix of the two. In every other respect, a Groovy project is identical to a Java project, which we have already seen in Chapter 6, Java Quickstart.

7.1. Using the Groovy Plugin

Let's look at an example. To use the Groovy plugin, add the following to your build file:

Example 7.1.  build.gradle

usePlugin 'groovy'

Note: The code for this example can be found at samples/groovy/quickstart

This will also apply the Java plugin to the project, if it has not already been applied. The Groovy plugin extends the compile task to look for source files in directory src/main/groovy, and the compileTests task to look for test source files in directorysrc/test/groovy. The compile tasks use joint compilation for these directories, which means they can contain a mixture of java and groovy source files.

To use the groovy compilation tasks, you must also declare the Groovy version to use and where to find the Groovy libraries. You do this by adding a dependency to the groovy configuration. The compile configuration inherits this dependency, so the groovy libraries will be included in classpath when compiling Groovy and Java source. For our sample, we will use Groovy 1.6.0 from the public Maven repository:

Example 7.2.  build.gradle

repositories {
    mavenCentral()
}

dependencies {
    groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.6.0'
}

Here is our completed build file:

Example 7.3.  build.gradle

usePlugin 'groovy'

repositories {
    mavenCentral()
}

dependencies {
    groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.6.0'
    testCompile group: 'junit', name: 'junit', version: '4.4'
}

Running gradle libs will compile, test and JAR your project. You can find out more about the Groovy Plugin in Chapter 16, The Groovy Plugin.

7.2. Summary

This chapter describes a very simple Groovy project. Usually, a real project will require more than this. Because a Groovy project is a Java project, whatever you can do with a Java project, you can also do with a Groovy project.

Finally, you can find more sample projects in the samples/groovy directory in the Gradle distribution.

Chapter 8. Web Application Quickstart

This chapter is a work in progress.

This chapter introduces some of the Gradle's support for web applications.

8.1. Building A WAR

8.2. Running Your Web Application

Chapter 9. Using the Gradle Command-Line

This chapter introduces the basics of the Gradle command-line. You execute Gradle builds using the gradle command. You have already seen this in action in previous chapters.

9.1. Executing multiple tasks

You can execute multiple tasks in a single build by listing each of the tasks on the command-line. For example, the command gradle compile test will execute the compile and test tasks. Gradle will execute the tasks in the order that they are listed on the command-line, and will also execute the dependencies for each task. Each task is executed once only, regardless of why it is included in the build: whether it was specified on the command-line, or it a dependency of another task, or both. Let's look at an example:

Example 9.1.  build.gradle

createTask('compile') {
    println 'compiling source'
}

createTask('test', dependsOn: 'compile') {
    println 'running tests'
}

createTask('libs', dependsOn: 'compile') {
    println 'building libs'
}

Below is the result of executing gradle -q libs test for this build script. Notice that the compile task is executed once, even though it is a dependency of both libs and test.

Example 9.2. Output of gradle -q libs test

> gradle -q libs test
compiling source
building libs
running tests

Because each task is executed once only, executing gradle libs libs is exactly the same as executing gradle libs.

9.2. Selecting which build to execute

When you run the gradle command, it looks for a build file in the current directory. You can use the -b option to select another build file. For example:

>gradle -b subproject/build.gradle

Alternatively, you can use the -p option to specify the project directory to use:

>gradle -p subproject

You can find out more about the gradle command's usage in Appendix B, Gradle Command Line

Chapter 10. Tutorial - 'This and That'

10.1. Skipping Tasks

Gradle offers multiple ways to skip the execution of a task.

Example 10.1.  build.gradle

createTask('skipMe') {
    println 'This should not be printed if the mySkipProperty system property is set to true.'
}.skipProperties << 'mySkipProperty'

Example 10.2. Output of gradle -DmySkipProperty skipMe

> gradle -DmySkipProperty skipMe
:skipMe SKIPPED

BUILD SUCCESSFUL

Total time: 1 secs

The -D option of the gradle command has the same effect as the -D option of the java command. This way you can set system properties of the JVM that runs Gradle. You can use this to add one or more skip properties to any task. If the corresponding system property is set to any value [9] except false (case does not matter), the actions of the task don't get executed. But often you don't even need to set the skip properties. If you set a system property according to the pattern skip.taskname , the actions of the task don't get executed.

Example 10.3.  build.gradle

createTask('autoskip') {
    println 'This should not be printed if the skip.autoskip system property is set.'
}

Example 10.4. Output of gradle -Dskip.autoskip autoskip

> gradle -Dskip.autoskip autoskip
:autoskip SKIPPED

BUILD SUCCESSFUL

Total time: 1 secs

If you want tasks to be skipped, that depends on a skipped task, you have to declare this explicitly via the skip properties

Example 10.5.  build.gradle

createTask('autoskip') {
    println 'This should not be printed if the skip.autoskip system property is set.'
}
createTask('depends', dependsOn: 'autoskip') {
    println "This should not be printed if the skip.autoskip system property is set."
}.skipProperties << 'skip.autoskip'

Example 10.6. Output of gradle -Dskip.autoskip depends

> gradle -Dskip.autoskip depends
:autoskip SKIPPED
:depends SKIPPED

BUILD SUCCESSFUL

Total time: 1 secs

If the rules for skipping a task can't be expressed with a simple property, you can use the StopExecutionException . If this exception is thrown by an action, the further execution of this action as well as the execution of any following action of this task is skipped. The build continues with executing the next task.

Example 10.7.  build.gradle

createTask('compile') {
    println 'We are doing the compile.'
}

compile.doFirst {
    // Here you would put arbitrary conditions in real life. But we use this as an integration test, so we want defined behavior.
    if (true) { throw new StopExecutionException() }
}
createTask('myTask', dependsOn: 'compile') {
   println 'I am not affected'
}

Example 10.8. Output of gradle -q myTask

> gradle -q myTask
I am not affected

This feature is helpful if you work with tasks provided by Gradle. It allows you to add conditional execution of the built-in actions of such a task.

You might be wondering why there is neither an import for the StopExecutionException nor do we access it via its fully qualified name. The reason is, that Gradle adds a set of default imports to your script. These imports are customizable (see Appendix C, Existing IDE Support and how to cope without it).

Every task has also a enabled flag which defaults to true. Setting it to false prevents the execution of any of the tasks actions.

Example 10.9.  build.gradle

createTask('disableMe') {
            println 'This should not be printed if the task is disabled.'
        }.enabled = false

Example 10.10. Output of gradle disableMe

> gradle disableMe
:disableMe SKIPPED

BUILD SUCCESSFUL

Total time: 1 secs

10.2. Obtaining Information About Your Build

Gradle provides several ways you can find out many details of your build. This can be useful for understanding the structure and dependencies of your build, and for debugging problems. Firstly, Gradle provides several command-line options which show particular details of your build. And secondly, Gradle provides a project-reports plugin, which adds tasks to generate reports about your build.

Running gradle --tasks gives you a list of the tasks which make up the build, broken down by project. This report shows the default tasks, if any, of each project, and the description and dependencies of each task. Below is an example of this report:

Example 10.11. Output of gradle -q --tasks

> gradle -q --tasks
------------------------------------------------------------
Root Project
------------------------------------------------------------
Default Tasks: dists

:clean - Deletes the build directory (build)
:dists 
   -> :api:libs, :webapp:libs

------------------------------------------------------------
Project :api
------------------------------------------------------------
:api:libs 
rule - build<ConfigurationName>: builds the artifacts of the given configuration

------------------------------------------------------------
Project :webapp
------------------------------------------------------------
:webapp:libs 
rule - build<ConfigurationName>: builds the artifacts of the given configuration

Running gradle --dependencies gives you a list of the dependencies of the build, broken down by project. This report shows the configurations of each project. For each configuration, the direct and transitive dependencies of that configuration are shown. Below is an example of this report:

Example 10.12. Output of gradle -q --dependencies

> gradle -q --dependencies
------------------------------------------------------------
Root Project
------------------------------------------------------------
No configurations

------------------------------------------------------------
Project :api
------------------------------------------------------------
compile
|-----api:unspecified:unspecified
      |-----commons-io:commons-io:1.2

------------------------------------------------------------
Project :webapp
------------------------------------------------------------
compile
|-----webapp:unspecified:unspecified
      |-----commons-io:commons-io:1.2

Running gradle --properties gives you a list of the properties of each project in the build.

Finally, you can use the project-reports plugin to add a number of reporting tasks to your project.

10.3. Directory Creation

There is a common situation, that multiple tasks depend on the existence of a directory. Of course you can deal with this by adding a mkdir to the beginning of those tasks. But this is kind of bloated. There is a better solution (works only if the tasks that need the directory have a dependsOn relationship):

Example 10.13.  build.gradle

classesDir = new File('build/classes')
createTask('resources') {
    classesDir.mkdirs()
    // do something
}
createTask('compile', dependsOn: 'resources') {
    if (classesDir.isDirectory()) {
        println 'The class directory exists. I can operate'
    }
    // do something
}

Example 10.14. Output of gradle -q compile

> gradle -q compile
The class directory exists. I can operate

But Gradle offers you also Directory Tasks to deal with this.

Example 10.15.  build.gradle

classes = dir('build/classes')
createTask('resources', dependsOn: classes) {
    // do something
}
createTask('otherResources', dependsOn: classes) {
    if (classes.dir.isDirectory()) {
        println 'The class directory exists. I can operate'
    }
    // do something
}

Example 10.16. Output of gradle -q otherResources

> gradle -q otherResources
The class directory exists. I can operate

A Directory Task is a simple task which name is a relative path to the project dir [10] . During the execution phase the directory corresponding to this path gets created if it does not exist yet. Another interesting thing to note in this example, is that you can also pass tasks objects to the dependsOn declaration of a task.

10.4. Gradle Properties and System Properties

Gradle offers a variety of ways to add properties to your build. With the -D command line option you can pass a system property to the JVM which runs Gradle.

There is also the possibility to directly add properties to your project objects. You can place a gradle.properties file either in the Gradle user home dir (defaults to USER_HOME/.gradle ) or in your project dir. For multiproject builds you can place gradle.properties files in any subproject. The properties of the gradle.properties can be accessed via the project object. The properties file in the the user's home directory has precedence over property files in the project directories.

You can also add properties directly to your project object via the -P command line option. For more exotic use cases you can even pass properties directly to the project object via system and environment properties. For example if you run a build on a continuous integration server where you have no admin rights for the machine. Your build script needs properties which values should not be seen by others. Therefore you can't use the -P option. In this case you can add an environment property in the project adminstration section (invisible to normal users). [11] If the environment property follows the pattern ORG_GRADLE_PROJECT_yourProperty=somevalue, yourProperty is added to your project object. If in the future CI servers support Gradle directly, they might start Gradle via its main method. Therefore we already support the same mechanism for system properties. The only difference is the prefix, which is org.gradle.project..

With the gradle.properties files you can also set system properties. If a property in such a file has the prefix systemProp. the property and its value are added to the system properties (without the prefix).

Example 10.17.  gradle.properties

gradlePropertiesProp=gradlePropertiesValue
systemPropertiesProp=shouldBeOverWrittenBySystemProp
envPropertiesProp=shouldBeOverWrittenByEnvProp
systemProp.system=systemValue

Example 10.18.  build.gradle

createTask('printProps') {
    println commandLineProjectProp
    println gradlePropertiesProp
    println systemProjectProp
    println envProjectProp
    println System.properties['system']
}

Example 10.19. Output of gradle -q -PcommandLineProjectProp=commandLineProjectPropValue -Dorg.gradle.project.systemProjectProp=systemPropertyValue printProps

> gradle -q -PcommandLineProjectProp=commandLineProjectPropValue -Dorg.gradle.project.systemProjectProp=systemPropertyValue printProps
commandLineProjectPropValue
gradlePropertiesValue
systemPropertyValue
envPropertyValue
systemValue

10.4.1. Checking for Project Properties

You can access a project property in your build script simply by using it name as you would use a variable. In case this property does not exists, an exception is thrown and the build fails. If your build script relies on optional properties the user might set for example in a gradle.properties file, you need to check for existence before you can access them. You can do this by using the method hasProperty('propertyName') which returns true or false.

10.5. Accessing the web via a proxy

Setting a proxy for web access (for example for downloading dependencies) is easy. Gradle does not need to provide special functionality for this. The JVM can be instructed to go via proxy by setting certain system properties. You could set this system properties directly in your build script with System.properties['proxy.proxyUser'] = 'userid'. An arguably nicer way is shown in Section 10.4, “Gradle Properties and System Properties”. Your gradle.properties file could look like this:

systemProp.http.proxyHost=http://www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password

We could not find a good overview for all possible proxy settings. The best we can offer are the constants in a file from the ant project. Here a link to the svn view. If anyone knows a better overview please let us know via the mailing list.

10.6. Caching

To improve the responsiveness Gradle caches the compiled build script by default. The first time you run a build for a project, Gradle creates a .gradle directory in which it puts the compiled build script. The next time you run this build, Gradle uses the compiled build script, if the timestamp of the compiled script is newer than the timestamp of the actual build script. Otherwise the build script gets compiled and the new version is stored in the cache. If you run Gradle with the -x option, any existing cache is ignored and the build script is compiled and executed on the fly. If you run Gradle with the -r option, the build script is always compiled and stored in the cache. That way you can always rebuild the cache if for example the timestamps for some reasons don't reflect that the build script needs to be recompiled.

10.7. Configuring Arbitrary Objects

You can configure arbitrary objects in the following very readable way.

Example 10.20.  build.gradle

createTask('configure') {
    pos = configure(new java.text.FieldPosition(10)) {
        beginIndex = 1
        endIndex = 5
    }
    println pos.beginIndex
    println pos.endIndex
}

Example 10.21. Output of gradle -q configure

> gradle -q configure
1
5



[9] The statement -Dprop sets the property to empty string, thus you don't need to type more to skip a task.

[10] The notation dir('/somepath') is a convenience method for tasks.add('somepath', type: Directory)

[11] Teamcity or Bamboo are for example CI servers which offer this functionality

Chapter 11. The Project and Task API

11.1. Project API

In the tutorial in Chapter 4, Build Script Basics we have called for example the method createTask. Where does this method come from? We said earlier that the directory containing the build script defines a project for Gradle. For Gradle this means, that it creates an instance of Project and associates it with the build script. With the build script you can configure this project object.

  • Any method you call in your build script, which is not defined in the build script, is delegated to the project object.

  • Any property you access in your build script, which is not defined in the build script, is delegated to the project object.

Let's try this out and try to access the name property of the Project object.

Example 11.1.  build.gradle

createTask('check') {
    println project.name
    println name
}

Example 11.2. Output of gradle -q check

> gradle -q check
projectApi
projectApi

Both println statements print out the same property. One uses the auto delegation to the project object, for properties not defined in the build script. The other statement uses the project property available to any build script, which provides an instance of the associated project object. Only if you define a property or a method which has the same name as a member of the project object, you need to use the project property. Look here to learn more about Project .

11.2. Task API

Many of the methods of the project object return task objects. We have already seen some ways on how to use the task objects in Chapter 4, Build Script Basics. Look here to learn more about Task .

11.3. Summary

The project and the task API constitute the core layer of Gradle and provide all the possible interaction options with this layer. [12] This core-layer constitutes a language for dependency based programming. [13] There are many other projects providing such a language. There is Ant for Java, Rake and Rant for Ruby, SCons for Python, the good old Make and many more. [14] We think that one thing that makes Gradle special compared to the other tools, is its strong support for applying dependency based programming on multiproject builds. We also think that just Gradle's core layer (together with its integration of the Ant tasks), provides a more convenient build system than Ant's core layer.



[12] There is more to come for this layer in the other chapters, e.g. support for multi-project builds (see Chapter 23, Multi-project Builds).

[14] Interestingly, Maven2 is the only major build system which does not use dependency based programming.

Chapter 12. More about Tasks

In the introductory tutorial (Chapter 4, Build Script Basics) you have learned how to create simple tasks. You have also learned how to add additional behavior to these tasks later on. And you have learned how to create dependencies between tasks. This was all about simple tasks. But Gradle takes the concept of tasks further. Gradle supports enhanced tasks, that is, tasks which have their own properties and methods. This is really different to what you are used to with Ant targets. Such enhanced tasks are either provided by you or are provided by Gradle.

12.1. Defining Tasks

We have already seen how to define tasks using a keyword style in Chapter 4, Build Script Basics. There is an alternate syntax for defining tasks:

Example 12.1.  build.gradle

tasks.add(name: 'hello') {
    println "hello"
}

tasks.add(name: 'copy', type: Copy)

Here we add tasks to the tasks collection. Have a look at TaskContainer for more variations of the add() method.

12.2. Locating Tasks

You often need to locate the tasks that you have defined in the build file, for example, to configure them or use them for dependencies. There are a number of ways you can do this. Firstly, each task is available as a property of the project, using the task name as the property name:

Example 12.2.  build.gradle

task hello

println hello.name
println project.hello.name

Tasks are also available through the tasks collection.

Example 12.3.  build.gradle

task hello

println tasks.hello.name
println tasks['hello'].name

You can access tasks from any project using the task's path with the task() method. You can call the task() method with a task name, or a relative path, or an absolute path.

Example 12.4.  build.gradle

project(':projectA') {
    task hello
}

task hello

println task('hello').path
println task(':hello').path
println task('projectA:hello').path
println task(':projectA:hello').path

Have a look at TaskContainer for more options for locating tasks.

12.3. Configuring Tasks

As an example, let's look at the Copy task provided by Gradle. To create a Copy task for your build, you can declare in your build script: [15]

Example 12.5.  build.gradle

task copy(type: Copy)

The copy task provides an API to configure it (see Copy ). If you create the copy task like this, it has no default behavior. [16] We want now use the copy task to learn about different ways to configure tasks. The examples below all show different ways to achieve the same configuration.

Example 12.6.  build.gradle

task copy(type: Copy)
copy.from(file('resources'))
copy.into(file('target'))
copy.includes('**/*.txt', '**/*.xml', '**/*.properties')

This is similar to the way we would normally configure objects in Java. You have to repeat the context (copyTask) in the configuration statement every time. This is a redundancy and not very nice to read.

There is a more convenient way of doing this.

Example 12.7.  build.gradle

task copy(type: Copy)
copy.from(file('resources'))
        .into(file('target'))
        .includes('**/*.txt', '**/*.xml', '**/*.properties')

You might know this approach from the Hibernates Criteria Query API or JMock. Of course the API of a task has to support this. The from, to and includes methods all return an instance of the Copy object. Gradle's build-in tasks usually support this configuration style.

But there is yet another way of configuring a task. It also preserves the context and it is arguably the most readable. It is usually our favorite.

Example 12.8.  build.gradle

task copy(type: Copy)
copy {
   from(file('resources'))
   into(file('target'))
   includes('**/*.txt', '**/*.xml', '**/*.properties')
}

This works for any task. Line 2 of the example is just a shortcut for the task() method. It is important to note that if you pass a closure to the task() method, this closure is applied to configure the task.

There is a slightly different ways of doing this.

Example 12.9.  build.gradle

task copy(type: Copy)
copy.configure {
   from(file('source'))
   into(file('target'))
   includes('**/*.txt', '**/*.xml', '**/*.properties')
}

Every task has a configure() method, which you can pass a closure for configuring the task. Gradle uses this style for configuring objects in many places, not just for tasks.

12.4. Adding Dependencies to Tasks

There are several ways you can define the dependencies of a task. In Section 4.3, “Task dependencies” you were introduced to defining dependencies using task names. Task names can refer to tasks in the same project as the task, or to tasks in other projects. To refer to a task in another project, you prefix the name of the task with the path of the project it belongs to. Below is an example which adds a dependency from projectA:taskX to projectB:taskY:

Example 12.10.  build.gradle

project('projectA') {
    task taskX(dependsOn: ':projectB:taskY') {
        println 'taskX'
    }
}

project('projectB') {
    task taskY {
        println 'taskY'
    }
}

Example 12.11. Output of gradle -q taskX

> gradle -q taskX
taskY
taskX

Instead of using a task name, you can define a dependency using a Task object, as shown in this example:

Example 12.12.  build.gradle

task taskX {
    println 'taskX'
}

task taskY {
    println 'taskY'
}

taskX.dependsOn taskY

Example 12.13. Output of gradle -q taskX

> gradle -q taskX
taskY
taskX

For more advanced uses, you can define a task dependency using a closure. When evaluated, the closure is passed the task whose dependencies are being calculated. The closure should return a single Task or collection of Task objects, which are then treated as dependencies of the task. The following example adds a dependency from taskX to all the tasks in the project whose name starts with lib:

Example 12.14.  build.gradle

task taskX {
    println 'taskX'
}

taskX.dependsOn {
    tasks.findAll { task -> task.name.startsWith('lib') }
}

task lib1 {
    println 'lib1'
}

task lib2 {
    println 'lib2'
}

task notALib {
    println 'notALib'
}

Example 12.15. Output of gradle -q taskX

> gradle -q taskX
lib1
lib2
taskX

For more information about task dependencies, see the Task API.

12.5. Replacing Tasks

Sometimes you want to replace a task. For example if you want to exchange a task added by the Java Plugin with a custom task of a different type. You can achieve this with:

Example 12.16.  build.gradle

createTask('copy', type: Copy)

createTask('copy', overwrite: true) {
    println('I am the new one.')
}

Example 12.17. Output of gradle -q copy

> gradle -q copy
I am the new one.

Here we replace a task of type Copy with a simple task. When creating the simple task, you have to set the overwrite property to true. Otherwise Gradle throws an exception, saying that a task with such a name already exists.

12.6. Summary

If you are coming from Ant, such an enhanced Gradle task as Copy looks like a mixture between an Ant target and an Ant task. And this is actually the case. The separation that Ant does between tasks and targets is not done by Gradle. The simple Gradle tasks are like Ant's targets and the enhanced Gradle tasks also include the Ant task aspects. All of Gradle's tasks share a common API and you can create dependencies between them. Such a task might be nicer to configure than an Ant task. It makes full use of the type system, is more expressive and easier to maintain.



[15] If you use the Java Plugin, this task is automatically created and added to your project.

[16] This is different when added by the Java Plugin where it is used for resource processing.

Chapter 13. Logging

The log is the main 'UI' of a build tool. If it is too verbose, real warnings and problems are easily hidden by this. On the other hand you need the relevant information for figuring out if things have gone wrong. Gradle has added to log-levels to the ones normally used. Those levels are QUIET and LIFECYCLE. The latter is the default and is telling you just what task is getting executed or skipped.

13.1. Choosing a log level

You can use command line switches to choose different log levels (see Table 13.1, “Log Level Command-Line Options”). The WARN and ERROR levels are included in all the other levels, except QUIET, where only ERROR is included. In Table 13.2, “Stacktrace Command-Line Options” you find the command line switches for stacktrace logging.

Table 13.1. Log Level Command-Line Options

Option Meaning
no logging options LIFECYCLE
-q QUIET
-i INFO
-d DEBUG

Table 13.2. Stacktrace Command-Line Options

Option Meaning
No stacktrace options No stacktraces are printed to the console in case of a build error (e.g. a compile error). Only in case of internal exceptions will stacktraces be printed. If the loglevel option -d is chosen, truncated stacktraces are always printed.
-s Truncated stacktraces are printed. We recommend this over full stacktraces. Groovy full stacktraces are extremely verbose (Due to the underlying dynamic invocation mechanisms. Yet they usually do not contain relevant information for what has gone wrong in your code.)
-f The full stacktraces are printed out.

13.2. External Tools and Standard Output

Gradle uses internally Ant and Ivy a lot. Both have their own logging system. Gradle injects an adapter into there logging system to redirect there logging output into the Gradle logging system. There is a 1:1 mapping from the Ant/Ivy log levels to the Gradle log levels, except the Ant/Ivy trace level, which is mapped to Gradle debug. This means the default Gradle log level does not show any Ant/Ivy output unless it is an error or a warning.

There are many tools out there which still use standard output for logging. Gradle redirects by default standard out to the QUIET level and standard err to the ERROR level. This behavior is configurable. Gradle provides a couple of switches for this. To change the log level, standard out is redirected to, when your build script gets evaluated, the project object offers a method called Project.captureStandardOutput() . To change the log level for standard out during task execution, tasks offer a method also with the name Task.captureStandardOutput() . Tasks and projects also offer a method disableStandardOutputCapture which causes the standard out to be send to the default standard out. If you need more fine grained control on how standard out is redirected you can use the class StandardOutputLogging .

13.3. Sending your own log messages

Gradle provides a logger property to a build script, which is an instance of a slf4j logger. Here is the code of the logging integration test, which shows you how to use the logger, as well as working with standard out redirection.

Example 13.1.  build.gradle

logger.info(Logging.QUIET, prefix + "quietLog")
logger.info(Logging.LIFECYCLE, prefix + "lifecycleLog")
logger.info(prefix + "infoLog")
logger.debug(prefix + "debugLog")
logger.warn(prefix + "warnLog")
logger.error(prefix + "errorLog")
println(prefix + 'quietOut')
captureStandardOutput(LogLevel.INFO)
println(prefix + 'infoOut')

createTask('logLifecycle') {
    println(prefix + 'lifecycleTaskOut')
}.captureStandardOutput(LogLevel.LIFECYCLE)

createTask('logInfo') {
    println(prefix + 'infoTaskOut')
}.captureStandardOutput(LogLevel.INFO)

createTask('log', dependsOn: [logInfo, logLifecycle]) {
    println(prefix + 'quietTaskOut')
}

Strictly speaking, QUIET and LIFECYCLE are no log levels, but they are markers. But logically Gradle treats them as log levels. In a future version of Gradle we want to provide a logger which provides additional log methods quiet and lifecycle.

You can also hook into Gradle's logging system from within other classes (classes from the buildSrc directory for example). Simply use a slf4j logger.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;    

public class MyClass {
    private static Logger logger = LoggerFactory.getLogger(MyClass.class);
    ...

You can use this logger the same way as you use the provided logger in the build script.

Chapter 14. Plugins

Now we look at how Gradle provides build-by-convention and out of the box functionality. These features are decoupled from the core of Gradle. Gradle provides them via plugins. To make this clear at the very beginning. The plugins provided by Gradle belong to the core distribution of Gradle and they are NEVER updated or changed in any way for a particular Gradle distribution. If there is a bug in the compile functionality of Gradle, we gonna release a new version of Gradle. There is no change of behavior for the lifetime of a given distribution of Gradle. We mention this as there is another build tools with a plugin system which behaves differently.

14.1. Declaring Plugins

If you want to use the plugin for building a Java project, simply type

usePlugin('java')

at the beginning of your script. That's all. From a technological point of view plugins use just the same operations as you can use from your build scripts. That is they use the Project and Task API (see Chapter 11, The Project and Task API). The Gradle plugins use this API for:

  • Adding tasks to your build (e.g. compile, test)

  • Creating dependencies between those tasks to let them execute in the appropriate order.

  • Adding a so called convention object to your project configuration.

Let's check this out:

Example 14.1.  build.gradle

usePlugin('java')

createTask('check') {
    println(task('compile').destinationDir.name) // We could also write println(compile)
}

Example 14.2. Output of gradle -q check

> gradle -q check
classes

The Java Plugin adds a compile task to the project object which can be accessed by a build script.

The usePlugin method either takes a string or a class as an argument. You can write [17]

usePlugin(org.gradle.api.plugins.JavaPlugin)

Any class, which implements the Plugin interface, can be used as a plugin. Just pass the class as an argument. You don't need to configure anything else for this. If you want to access a custom plugin via a string identifier, you must inform Gradle about the mapping. You can do this in the file plugin.properties in the top level directory of Gradle. It looks like this for the current release:

Figure 14.1. plugin.properties

java=org.gradle.api.plugins.JavaPlugin
groovy=org.gradle.api.plugins.GroovyPlugin
war=org.gradle.api.plugins.WarPlugin
osgi=org.gradle.api.plugins.osgi.OsgiPlugin
jetty=org.gradle.api.plugins.jetty.JettyPlugin
maven=org.gradle.api.plugins.MavenPlugin
project-reports=org.gradle.api.plugins.ProjectReportsPlugin

If you want to use your own plugins, you must make sure that they are accessible via the build script classpath. See Chapter 24, Organizing Build Logic for more information.

14.2. Configuration

If you use the Java Plugin there is for example a compile and processResources task for your production code (the same is true for your test code). The default location for the output of those task is the directory build/classes. What if you want to change this? Let's try:

Example 14.3.  build.gradle

usePlugin('java')

createTask('check') {
    processResources.destinationDir = new File(buildDir, 'output')
    println(processResources.destinationDir.name)
    println(compile.destinationDir.name)
}

Example 14.4. Output of gradle -q check

> gradle -q check
output
classes

Setting the destinationDir of the processResources task had only an effect on the processResources task. Maybe this was what you wanted. But what if you want to change the output directory for all tasks? It would be unfortunate if you had to do this for each task separately.

Gradles tasks are usually convention aware. A plugin can add a convention object to your build. It can also map certain values of this convention object to task properties.

Example 14.5.  build.gradle

usePlugin('java')

createTask('check') {
    classesDirName = 'output'
    println(processResources.destinationDir.name)
    println(compile.destinationDir.name)
    println(convention.classesDirName)
}

Example 14.6. Output of gradle -q check

> gradle -q check
output
output
output

The Java Plugin has added a convention object with a classesDirName property. The properties of a convention object can be accessed like project properties. As shown in the example, you can also access the convention object explicitly.

By setting a task attribute explicitly (as we have done in the first example) you overwrite the convention value for this particular task.

Not all of the tasks attributes are mapped to convention object values. It is the decision of the plugin to decide what are the shared properties and then bundle them in a convention object and map them to the tasks.

14.2.1. More about convention objects

Every project object has a convention object which is a container for convention objects contributed by the plugins declared for your project. If you simply access or set a property or access a method in your build script, the project object first looks if this is a property of itself. If not, it delegates the request to its convention object. The convention object checks if any of the plugin convention objects can fulfill the request (first wins and the order is not defined). The plugin convention objects also introduce a namespace.

usePlugin('java')
println classesDir
println convention.classesDir
println convention.plugins.java.classesDir

All three statements print out the same property. The more specific statements are useful if there are ambiguities.

14.2.2. Declaring Plugins Multiple Times

A plugin is only called once for a given project, even if you have multiple usePlugin() statements. An additional call after the first call has no effect but doesn't hurt either. This can be important if you use plugins which extends other plugins. For example usePlugin('groovy') calls also the Java Plugin. We say the Groovy plugin extend the Java plugin. But you might as well write:

usePlugin('java')
usePlugin('groovy')

If you use cross-project configuration in multi-project builds this is a useful feature.

14.3. Summary

Plugins provide tasks, which are glued together via dependsOn relations and a convention object.



[17] Thanks to Gradle's default imports (see Appendix C, Existing IDE Support and how to cope without it) you can also write usePlugin(JavaPlugin) in this case.

Chapter 15. The Java Plugin

Table 15.1, “Default Directory Layout” shows the default project layout assumed by the Java Plugin. This is configurable via the convention object. Table 15.2, “Java Plugin Tasks” shows the tasks added by the Java Plugin. These tasks constitute a lifecycle for Java builds. Table 15.3, “Java Plugin - Directory Properties” and Table 15.5, “Java Convention Object - Non Dir Properties” shows the most important properties of the convention object of the Java plugin. [18] Gradle's conventions contain a convention for the directory hierarchy as well as conventions for the element names of the hierarchy. For example the srcDirs are relative to the srcRoot. Therefore srcDirs is a read-only property. If you want to change the name of the source dirs you need to do this via the srcDirNames property. But the paths you specify here are relative to the srcRoot. This has the advantage to make bulk changes easy. If you change srcRoot from src to source, this automatically applies to all directory properties which are relative to srcRoot. As this also introduces an inflexibility, we have additional floating dirs, which are not bound to any hierarchy (see Table 15.4, “Java Convention Object - Floating Dir Properties”). For example code generation tool could make use of this, by adding a source dir which is located in the build folder.

Table 15.1. Default Directory Layout

Directory Meaning
src/main/java Application/Library sources
src/main/resources Application/Library resources
src/test/java Test sources
src/test/resources Test resources

Table 15.2. Java Plugin Tasks

Taskname dependsOn Type
clean - Clean
init - Task
processResources init Copy
compile processResources Compile
processTestResources compile Copy
compileTests processTestResources Compile
test compileTests Test
javadoc - Javadoc
libs All Jar and War tasks in the project. Task
dists libs and all Zip and Tar tasks in the project. Task
buildConfigurationName The tasks which produce the artifacts in configuration ConfigurationName. Task
uploadConfigurationName The tasks which produce the artifacts in configuration ConfigurationName. Upload

Table 15.3. Java Plugin - Directory Properties

Directory Name Property Directory File Property Default Name Default File
srcRootName srcRoot src projectDir/src
srcDirNames srcDirs [main/java] [ srcRoot/main/java]
resourceDirNames resourceDirs [main/resources] [ srcRoot/main/resources]
testSrcDirNames testSrcDirs [test/java] [ srcRoot/test/java]
testResourceDirNames testResourceDirs main/resources [ srcRoot/main/resources]
classesDirName classesDir classes buildDir/classes
testClassesDirName testClassesDir test-classes buildDir/test-classes
testResultsDir testResultsDirName test-results buildDir/test-results
testReportDir testReportDirName tests reportsDir/test
libsDirName libsDir empty string buildDir
distsDirName distsDir dists buildDir/dists
docsDirName docsDir docs buildDir/docs
javadocDirName javadocDir javadoc buildDir/javadoc
reportsDirName reportsDir reports buildDir/reports

Table 15.4. Java Convention Object - Floating Dir Properties

Property Type Default Value
floatingSrcDirs List empty
floatingResourceDirs List empty
floatingTestSrcDirs List empty
floatingTestResourceDirs List empty

Table 15.5. Java Convention Object - Non Dir Properties

Property Type Default Value
sourceCompatibility JavaVersion . Can also set using a String or a Number, eg '1.5' or 1.5. 1.5
targetCompatibility JavaVersion . Can also set using a String or Number, eg '1.5' or 1.5. sourceCompatibility
manifest GradleManifest empty
metaInf List empty

15.1. Init

The init task has no default action attached to it. It is meant to be a hook. You can add actions to it or associates your custom tasks with it. The Java Plugin executes this task before any other of its tasks get executed (except clean and javadoc which does not depends on init).

15.2. Javadoc

The javadoc task has no default association with any other task. It has no prerequisites on the actions of other tasks, as it operates on the source. We support the core javadoc options and the options of the standard doclet described in the reference documentation of the Javadoc executable.

For some of the Javadoc options we provide defaults these defaults are only used when they are not set explicitly. Except for the sourcepath and classpath option for these options you can in addition to setting your custom values also make it so that the defaults get appended to these paths with the (alwaysAppendDefaultSourcepath and alwaysAppendDefaultClasspath toggles).

Table 15.6. Javadoc Options

Javadoc option Default value When is the default used
destination directory [javadocDir] When the destination directory is not set explicitly
sourcepath The java or groovy source directories When the sourcepath is empty or when you set the alwaysAppendDefaultSourcepath to true
classpath The dependencies from the compile configuration + the classesDir When the classpath is empty or when you set the alwaysAppendDefaultClasspath to true
windowTitle project name + version When the window title is not set explicitly
subPackages All first level sub directories in the srcDirs When the following options are all empty: packageNames, sourceNames and subPackages

For a complete list of supported Javadoc options consult the API documentation of the following classes: CoreJavadocOptions and StandardJavadocDocletOptions .

Table 15.7. Java Convention Object - Javadoc Properties

Task Property Convention Property
srcDirs srcDirs
classesDir classesDir
destinationDir [javadocDir]

15.3. Clean

The clean task simply removes the directory denoted by its dir property. This property is mapped to the buildDir property of the project. In future releases there will be more control of what gets deleted. If you need more control now, you can use the Ant delete task.

15.4. Resources

Gradle uses the Copy task for resource handling. It has two instances, processResources and processTestResources.

Table 15.8. Java Convention Object - Resource Properties

Task Instance Task Property Convention Property
processResources sourceDirs resourceDirs
processResources destinationDir classesDir
processTestResources sourceDirs testResourceDirs
processTestResources destinationDir testClassesDir

The processResources task offers includes and excludes directives as well as filters. Have a look at Copy to learn about the details.

15.5. Compile

The Compile task has two instances, compile and compileTests.

Table 15.9. Java Convention Object - Compile Properties

Task Instance Task Property Convention Property
compile srcDirs srcDirs
compile destinationDir classesDir
compile sourceCompatibility sourceCompatibility
compile targetCompatibility targetCompatibility
compileTests srcDirs testSrcDirs
compileTests destinationDir testClassesDir
compileTests sourceCompatibility sourceCompatibility
compileTests targetCompatibility targetCompatibility

The classpath of the compile task is derived from two sources. One is the configuration assigned to the task by the dependency manager. The other classpath source is the unmanagedClasspath property: a list of files denoting a jar or a directory. Usually you create your classpath with the dependency manager. The unmanagedClasspath is used internally by Gradle. This classpath is not shared between projects in a multi-project build. Nor is it part of a dependency descriptor if you choose to upload your library to a repository. See Section 20.3, “Java Plugin and Dependency Management” how the Java Plugin glues the tasks with the dependency manager and see the whole Chapter 20, Dependency Management how to use the dependency manager.

Have a look at Compile to learn about the details. The compile task delegates to Ants javac task to do the compile. Via the compile task you can set most of the properties of Ants javac task.

15.6. Test

The test task executes the unit tests which have been compiled by the compileTests task.

Table 15.10. Java Convention Object - Test Properties

Task Property Convention Property
testClassesDir testClassesDir
testResultsDir testResultsDir
unmanagedClasspath [classesDir]

Have a look at Test to learn more. Right now the test results are always in XML-format. The task has a stopAtFailuresOrErrors property to control the behavior when tests are failing. Test always executes all tests. It stops the build afterwards if stopAtFailuresOrErrors is true and there are failing tests or tests that have thrown an uncaught exception.

Per default the tests are run in a forked JVM and the fork is done per test. You can modify this behavior by setting forking to false or set the forkmode to once.

The test task tries to run all classes as tests, that have been compiled from the test source dirs. The Java plugin defines default exclude pattern for the .class files. The default include is **/*Tests.class", "**/*Test.class and the default exclude is **/Abstract*.class.

The test task delegates to Ants junit task. TestNG is not supported yet. You can expect TestNG support in one of our next releases.

15.7. Bundles

The Bundle task has two instances, libs and dists. The Bundle task is a special animal. It is a container for archive tasks (jar, zip, ...).

Table 15.11. Java Convention Object - Bundle Properties

Task Instance Task Property Convention Property
libs tasksBaseName project.archivesBaseName
dists tasksBaseName project.archivesBaseName

15.7.1. The libs Task

The libs task contains all the archive tasks which constitute the libraries needed to use your project as a library. Executing the libs task leads to the execution of all the contained archive tasks. In a multi-project build the archives which are produced by the libs task are available in the classpath of a dependent project. If you upload your project into a repository, those archives are part of the dependency descriptor. If you come from Maven you can have only one library jar per project. With Ivy you can have as many as you want. The Java plugin adds by default one jar archive to the libs task. The task name is by default archive_jar and can of course be manipulated by this name. This jar contains the content of the classesDir. This is the behavior your are used from Maven. If you are happy with that you usually don't have to touch this task. Except if you want to change the names of the generated archives.

The libs task depends on the test task and its archive tasks. The archive tasks assigned to the libs task depend by default on the test task as well. You can change this via the childrenDependsOn property of the libs task.

15.7.2. The dists Task

The dists task contains all the archive task that make up your distributions. For example a binary and a source distribution. The dists task has two purposes. One is providing a hook for distributions in the lifecycle. The other is for uploading distribution archives (the same is also true for the libs task.) The dists task depends on its archive tasks and the libs task. The contained archive tasks depend by default on the libs task as well. You can change this via the childrenDependsOn property of the dists task.

15.7.3. Adding Archives

The Bundle task has a couple of convenience methods for adding new archive tasks to it. Right now there are the methods (jar, war, zip, tar, tarGz, tarBzip2). They all behave in the same way.

Example 15.1.  build.gradle

usePlugin 'java'
archivesBaseName = 'myArchiveName' // defaults to project.name
version = 1.0

task myZip(type: Zip)
myZip {
    fileSet(dir: 'somedir')
}

println myZip.archiveName

Example 15.2. Output of gradle -q init

> gradle -q init
myArchiveName-1.0.zip

This adds an archive task with the name archive_zip. It is important to distinguish between the name of the archive task and the name of the archive generated by the archive task. The name of the generated archive file is by default the name of the project. The default for naming generated archives can be changed with the archivesBaseName project property. The name of the archive can be changed at any time later on. You can pass a closure to the zip() method, which statements are applied against the newly created archive task object. In Section 15.8, “Archive Tasks” you will learn more about which statements you can apply against a particular archive task. You could for example change the name of the archive directly in the closure:

Example 15.3.  build.gradle

usePlugin 'java'
version = 1.0

task myZip(type: Zip)
myZip {
    fileSet(dir: 'somedir')
    baseName = 'customName'
}

println myZip.archiveName

Example 15.4. Output of gradle -q init

> gradle -q init
customName-1.0.zip

You can further customize the names by passing arguments to archive method of the bundle task:

Example 15.5.  build.gradle

usePlugin 'java'
archivesBaseName = 'gradle'
version = 1.0

task myZip(type: Zip)
myZip {
    appendix = 'wrapper'
    classifier = 'src'
    fileSet(dir: 'somedir')
}

println myZip.archiveName

Example 15.6. Output of gradle -q init

> gradle -q init
gradle-wrapper-1.0-src.zip

15.7.4. Configuration Action

t.b.d.

15.8. Archive Tasks

An archive task is a task which produces an archive at execution time. The following archives tasks are available:

Table 15.12. Archive Tasks

Type Accepted file container Extends
Zip fileSet, fileCollection, zipFileSet AbstractArchiveTask
Tar fileSet, fileCollection, zipFileSet, tarFileSet Zip
Jar fileSet, fileCollection, zipFileSet Zip
War fileSet, fileCollection, zipFileSet Jar

The following file containers are available:

Table 15.13. Filecontainer for Archives

Type Meaning
FileSet A set of files defined by a common baseDir and include/exclude patterns.
ZipFileSet Extends FileSet with additional properties known from Ant's zipfileset task.
TarFileSet Extends ZipFileSet with additional properties known from Ant's tarfileset task.
FileCollection An arbitrary collection of files to include in the archive. In contrast to a FileSet they don't need to have a common basedir. There are a number of ways of creating a FileCollection. For example, the Configuration objects of a project implement FileCollection.
AntDirective An arbitrary Ant resource declaration.

To learn about all the details have a look at the javadoc of the archive task class or the file container class itself.

15.8.1. Common Properties

The name of the generated archive is assembled from the task properties baseName, classifier and extension to: baseName-project.version-classifier.extension. [19] The assembled name is accessible via the archiveName property. The name property denotes the name of the task, not the generated archive. An archive task has also a customName property. If this property is set, the archiveName property returns its value instead of assembling a name out of the properties mentioned above.

Archives have a destinationDir property to specify where the generated archive should be placed. It has also an archivePath property, which returns a File object with the absolute path of the generated archive.

15.8.2. Adding Content

To add content to an archive you must add file container to an archive (see Table 15.13, “Filecontainer for Archives”). You can add as many file containers as you like. They behave pretty much the same as the Ant resources with similar names.

myZipTask.fileSet(dir: 'contentDir') {
    include('**/*.txt')
    exclude('**/*.gif')
}

You can add arbitrary files to an archive:

myZipTask.files('path_to_file1', 'path_to_file2')

Other examples:

myZipTask.zipFileSet(dir: 'contentDir') {
    include('**/*.txt')
    exclude('**/*.gif')
    prefix = 'myprefix'
}
myTarTask.tarFileSet(dir: 'contentDir') {
    include('**/*.txt')
    exclude('**/*.gif')
    uid = 'myuid'
}

There is also the option to add an arbitrary Ant expression describing an Ant resource.

myZipTask.antDirective {        
   zipgroupfileset(dir: new File(rootDir, 'lib'))    
}

This is for rather exotic use cases. Usually you should be fine with the file container provided by Gradle.

15.8.3. Merging

If you want to merge the content of other archives into the archive to be generated Gradle offers you two methods. One is merge:

myZipTask.merge('path1/otherArchive1.zip', 'path2/otherArchive.tar.gz')

This merges the whole content of the archive passed to the merge method into the generated archive. If you need more control which content of the archive should be merged and to what path, you can pass a closure to the merge method:

myZipTask.merge('path1/otherArchive1.zip', 'path2/otherArchive.tar.gz') {
    include('**/*.txt')
    exclude('**/*.gif')
    prefix = 'myprefix'
}

Under the hood Gradle scans the extension of the archives to be merged. According to the extension, it creates a ZipFileSet or TarFileSet. The closure is applied to this newly created file container. There is another method for merging called mergeGroup.

myZipTask.mergeGroup('path_to_dir_with_archives') {
    include('**/*.zip')
    exclude('**/*.tar.gz')
}

With this method you can assign a set of archives to be merged. Those archives have to be located under the directory you pass as an argument. You can define filters what archives should be included. They are always included fully and you can't specify a path. If you need this features, you must use the merge method.

15.8.4. Manifest

The convention object of the Java Plugin has a manifest property pointing to an instance of GradleManifest . With this GradleManifest object you can define the content of the MANIFEST.MF file of all the jar or a war archives in your project.

Example 15.7.  build.gradle

manifest.mainAttributes("Implementation-Title": "Gradle", "Implementation-Version": version)

You can also define sections of a manifest file.

If a particular archive needs unique entries in its manifest you have to create your own GradleManifest instance for it.

Example 15.8.  build.gradle

manifest.mainAttributes("Implementation-Title": "Gradle", "Implementation-Version": version)
myZipTask.manifest = new GradleManifest(manifest.createManifest())
myZipTask.manifest.mainAttributes(mykey: "myvalue")

Passing the common manifest object to the constructor of GradleManifest add the common manifest values to the task specific manifest instance.

15.8.5. MetaInf

The convention object of the Java Plugin has a metaInf property pointing to a list of FileSet objects. With this file sets you can define which files should be in the META-INF directory of a jar or a war archive.

metaInf << new FileSet(someDir)

15.9. Upload

The Upload task has two instances, uploadLibs and uploadDists. An easy way of describing there behavior, is that all archives added to the libs and dists bundle are uploaded by the corresponding upload task. An upload task uploads to the repositories assigned to it. If needed you have more control on what files get uploaded. Have a look at Upload to learn more.

15.10. Eclipse

Gradle comes with a number of tasks for generating eclipse files for your projects.

15.10.1. Eclipse Classpath

EclipseClasspath has a default instance with the name eclipseCp. It generates a .classpath file.

Table 15.14. Java Convention Object - Eclipse Properties

Task Property Convention Property
srcDirs srcDirs + resourcesDirs
testSrcDirs testSrcDirs + testResourcesDirs
outputDirectory classesDir
testOutputDirectory testClassesDir
classpathLibs the resolve result for testRuntime

15.10.2. Eclipse Project

EclipseProject has a default instance with the name eclipseProject. It generates a .project file.

Table 15.15. Java Convention Object - Eclipse Project Properties

Task Property Convention Property
name project.name
projectType ProjectType.JAVA

The java plugin also provides a task called eclipse which generates both of the eclipse tasks mentioned above. If you are using the war plugin, eclipse also leads to the execution of the eclipseWtp task.



[18] The buildDir property is a property of the project object. It defaults to build.

[19] If the classifier is empty the trailing - is not added to the name. The same is true for the project.version property.

Chapter 16. The Groovy Plugin

The Groovy Plugin extends the Java Plugin. It can deal with pure Java projects, [20] with mixed Java and Groovy projects, and with pure Groovy projects. The Groovy plugin does not add any tasks. It modifies some of the tasks of the Java Plugin and adds to the Convention object. See Table 16.1, “Default Directory Layout (additional to the Java layout)”, Table 16.2, “Groovy Convention Object (extends JavaConvention).” and Table 16.3, “Groovy Convention Object (extends JavaConvention) - Floating Dir Properties”. It also add a new dependency configuration groovy.

Gradle is written in Groovy and allows you to write your build scripts in Groovy. But this is an internal aspect of Gradle which is strictly separated from building Groovy projects. You are free to choose the Groovy version your project should be build with. This Groovy version is not just used for compiling your code and running your tests. The groovyc compiler and the the groovydoc tool are also taken from the Groovy version you provide. As usual, with freedom comes responsibility ;). You are not just free to choose a Groovy version, you have to provide one. Gradle expects that the groovy libraries are assigned to the groovy dependency configuration. Here is an example using the public Maven repository:

Example 16.1.  build.gradle

repositories {
    mavenCentral()
}

dependencies {
    groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.6.0'
}

And here is an example using the Groovy JARs checked into the lib directory of the source tree:

Example 16.2.  build.gradle

repositories {
    flatDir(dirs: file('lib'))
}

dependencies {
    groovy module(':groovy-all:1.6.0') {
        dependency(':commons-cli:1.0')
        module(':ant:1.7.0') {
            dependencies(':ant-junit:1.7.0:jar', ':ant-launcher:1.7.0')
        }
    }
}

Table 16.1. Default Directory Layout (additional to the Java layout)

Folder Meaning
src/main/groovy Application/Library sources in Groovy
src/test/groovy Test sources in Groovy

Table 16.2. Groovy Convention Object (extends JavaConvention).

Dir Name Dir File Default Value Name Default Value File
groovySrcDirNames groovySrcDirs [main/groovy] [ srcRoot/main/groovy]
groovyTestSrcDirNames groovyTestSrcDirs test/groovy [ srcRoot/test/groovy]
groovydocDirName groovydocDir groovydoc docsDir/groovydoc

Table 16.3. Groovy Convention Object (extends JavaConvention) - Floating Dir Properties

Property Type Default Value
floatingGroovySrcDirs List empty
floatingGroovyTestSrcDirs List empty

All the Groovy source directories can contain Groovy and Java code. The Java source directories may only contain Java source code (and can of course be empty) [21]

16.1. Compile

The GroovyCompile task has two instances, compile and compileTests. The task type extends the Compile task (see Section 15.5, “Compile”)

Table 16.4. Groovy Convention Object - Source Directory Properties

Task Instance Task Property Convention Property
compile groovySourceDirs groovySrcDirs
compileTests groovySourceDirs groovyTestSrcDirs

Have a look at GroovyCompile to learn about the details. The compile task delegates to the Ant Groovyc task to do the compile. Via the compile task you can set most of the properties of Ants Groovyc task.

16.2. Test

In contrast to the Java plugin the fork mode is set to once by default, because of the significant startup time of Groovy. The Java plugin uses per test as fork mode (see Section 15.6, “Test”).



[20] We don't recommend this, as the Groovy plugin uses the Groovyc Ant task to compile the sources. For pure Java projects you might rather stick with pure javac. In particular as you would have to supply a groovy jar for doing this.

[21] We are using the same conventions as introduced by Russel Winders Gant tool (http://gant.codehaus.org).

Chapter 17. The War Plugin

The war plugin extends the Java Plugin. It disables the default jar archive generation of the Java Plugin and adds a default war archive task. Have also a look at War

17.1. Default Settings

Table 17.1. Default Directory Layout

Directory Meaning
src/main/webapp Web application sources

Table 17.2. War Plugin - Directory Properties

Directory Name Property Directory File Property Default Name Default File
webAppDirName webAppDir main/webapp srcRoot/main/webapp

The default behavior of the War plugin is to copy the content of src/main/webapp to the root of the archive. Your webapp folder may of course contain a WEB-INF sub-directory, which again may contain a web.xml file. Your compiled classes are compiled to WEB-INF/classes. All the dependencies of the runtime [22] configuration are copied to WEB-INF/lib. The War plugin add two new dependency configurations: providedCompile and providedRuntime. Those new configurations have the same scope as the respective compile and runtime configurations. Except that they are not added to the war-archive. It is important to note that those provided configurations work transitively. Let's say you add commons-httpclient:commons-httpclient:3.0 to any of the provided configurations. This dependency has a dependency on commons-codec. This means neither httpclient nor commons-codec is added to your war, even if commons-code were an explicit dependency of your compile configuration. If you don't want this transitive behavior, simply declare your provided dependencies like commons-httpclient:commons-httpclient:3.0@jar.

17.2. Customizing

Here an example with the most important customization options:

Example 17.1.  build.gradle

import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod

group = 'gradle'
version = '1.0'
usePlugin('war')
usePlugin('jetty')

configurations {
   moreLibs
}

repositories {
   flatDir(dirs: "$rootDir/lib")
   mavenCentral()
}

dependencies {
    compile ":compile:1.0"
    providedCompile ":providedCompile:1.0@jar", "javax.servlet:servlet-api:2.5"
    runtime ":runtime:1.0"
    providedRuntime ":providedRuntime:1.0@jar"
    testCompile "junit:junit:3.8.2"
    moreLibs ":otherLib:1.0"
}

war {
    fileSet(dir: file('src/rootContent')) // adds a file-set to the root of the archive
    webInf(dir: file('src/additionalWebInf')) // adds a file-set to the WEB-INF dir.
    additionalLibs(dir: file('additionalLibs')) // adds a file-set to the WEB-INF/lib dir.
    libConfigurations('moreLibs') // adds a configuration to the WEB-INF/lib dir.
    webXml = file('src/someWeb.xml') // copies a file to WEB-INF/web.xml
}

[jettyRun, jettyRunWar, jettyRunExploded]*.daemon = true
stopKey = 'foo'
stopPort = 9451

createTask('runTest', dependsOn: jettyRun) {
    callServlet()
}

createTask('runWarTest', dependsOn: jettyRunWar) {
    callServlet()
}

File explodedDir = "$buildDir/exploded" as File
createTask('explodedWar', dependsOn: war) {
    ant.unzip(src: war.archivePath, dest: explodedDir)
}

jettyRunExploded {
    dependsOn explodedWar
    webApp = explodedDir
}

createTask('runExplodedTest', dependsOn: jettyRunExploded) {
    callServlet()
}

[jettyRun, jettyRunWar, jettyRunExploded].each { jetty ->
    jetty.dependsOn jettyStop
    jetty.connectors = configure(new org.mortbay.jetty.nio.SelectChannelConnector()) {
        port = 8163
        maxIdleTime = 30000
    }
}

private void callServlet() {
    HttpClient client = new HttpClient()
    GetMethod method = new GetMethod("http://localhost:8163/web-project/hello")
    client.executeMethod(method)
    new File(buildDir, "servlet-out.txt").write(method.getResponseBodyAsString())
    jettyStop.execute()
}

Of course one can configure the different file-sets with a closure to define excludes and includes.

If you want to enable the generation of the default jar archive additional to the war archive just type:

archive_jar.enabled = true

17.3. Eclipse WTP

EclipseWtp has a default instance with the name eclipseWtp. It generates a .settings/org.eclipse.wst.common.component file.



[22] The runtime configuration extends the compile configuration.

Chapter 18. The OSGi Plugin

The Gradle OSGi plugin enables the generation of an OSGi manifest. This OSGi manifest is automatically added to the jars produces by the Java plugin libs bundle. This plugin makes heavy use of Peter Kriens BND tool.

The OSGi plugin adds an osgi property to every jar generated by the libs bundle. This osgi property points to an instance of OsgiManifest . Via the OsgiManifest object you can control the generation of the OSGi Manifest of the respective jar. The OSGi plugin assign default values to the OsgiManifest object.

Table 18.1. OSGi Properties

Task Property Convention Property
classesDir project.classesDir
version project.version
name project.archivesBaseName
symbolicName transformation of the name and the group to produce a valid OSGi symbolic name
classpath project.dependencies.resolve('runtime')

A classes in the classes dir are analyzed regarding there package dependencies and the packages they expose. Based on this the Import-Package and the Export-Package values of the OSGi Manifest are calculated. If the classpath contains jars with an OSGi bundle, the bundle information is used to specify version information for the Import-Package value. Beside the explicit properties of the OsgiManifest object you can add instructions.

configure(project.archive_jar.osgi) {
    name = 'overwrittenSpecialOsgiName'
    instruction 'Private-Package',
            'org.mycomp.package1',
            'org.mycomp.package2'
    instruction 'Bundle-Vendor', 'MyCompany'
    instruction 'Bundle-Description', 'Platform2: Metrics 2 Measures Framework'
    instruction 'Bundle-DocURL', 'http://www.mycompany.com'
}

The first argument of the instruction call is the key of the property. The other arguments form the value. They are joined by Gradle with the , separator. To learn more about the available instructions have a look at the BND tool.

Chapter 19. The Project Reports Plugin

The Project Reports Plugin is currently a work in progress, and at this stage doesn't do particularly much. We plan to add much more to these reports in the next release of Gradle.

The Project Reports Plugin adds some tasks to your project which generate reports containing useful information about your build.

Table 19.1. Project Reports Plugin - Directory Properties

Directory Name Property Directory File Property Default Name Default File
reportsDirName reportsDir reports buildDir/reports

Chapter 20. Dependency Management

20.1. Introduction

The current dependency management solutions all require to work with XML descriptor files and are usually based on remote repositories for downloading the dependencies. Gradle fully supports this approach. Gradle works perfectly with your existent dependency management infrastructure, be it Maven or Ivy. All the repositories you have set up with your custom pom or ivy files can be used as they are. No changes necessary. But Gradle offers also a simpler approach which might be better suited for many projects.

We think dependency management is very important for almost any project. Yet the kind of dependency management you need depends on the complexity and the environment of your project. Is your project a distribution or a library? Is it part of an enterprise environment, where it is integrated into other projects builds or not? But all types of projects share the following requirements:

  • The version of the jar must be easy to recognize. Sometimes the version is in the Manifest file of the jar, often not. And even if, it is rather painful to always look into the Manifest file to learn about the version. Therefore we think that you should only use jars which have there version as part of there file name.

  • It has to be clear what are the first level dependencies and what are the transitive ones. There are different ways to achieve this. We will look at this later.

  • Conflicting versions of the same jar should be detected and either resolved or cause an exception.

20.1.1. Versioning the jar name

Why do we think this is necessary? Without a dependency management as described above, your are likely to burn your fingers sooner or later. If it is unclear which version of a jar your are using, this can introduce subtle bugs which are very hard to find. For example there might be a project which uses Hibernate 3.0.4. There are some problems with Hibernate so a developer installs version 3.0.5 of Hibernate on her machine. This did not solve the problem but she forgot to roll back Hibernate to 3.0.4. Weeks later there is an exception on the integration machine which can't be reproduced on the developer machine. Without a version in the jar name this problem might take a long time to debug. Version in the jar names increases the expressiveness of your project and making it easier to maintain.

20.1.2. Transitive dependency management

Why is transitive dependency management so important? If you don't know which dependencies are first level dependencies and which ones are transitive you are loosing very soon control over your build. Even Gradle has already 20+ jars. An enterprise project using Spring, Hibernate, etc. easily ends up with 100+ jars. There is no way to memorize where all this jars belong to. If you want to get rid of a first level dependency you can't be sure which other jars you should remove. Because a dependency of your first level dependency might also be a first level dependency itself. Or it might be a transitive dependency of another of your first level dependency. Many first level dependencies are runtime dependencies and the transitive dependencies are of course all runtime dependencies. So the compiler won't help you much here. The end of the story is, as we have seen very often, nobody dares to remove any jar any longer. The project classpath is a complete mess and if a classpath problems arises, hell on earth invites you for a ride. In one of my former projects, I've found some ldap related jar in the classpath, which sheer presence, as I've found out after much research, accelerated LDAP access. So removing this jar would not have led to any errors at compile or runtime.

Gradle offers you different ways to express what are first level and what are transitive dependencies. Gradle allows you for example to store your jars in CVS or SVN without XML descriptor files and still use transitive dependency management. Gradle also validates your dependency hierarchy against the reality of your code by using only the first level dependencies for compiling.

20.1.3. Version conflicts

In your dependency description you tell Gradle which version of a dependency is needed by another dependency. This leads frequently to conflicts. Different dependencies rely on different versions of another dependency. The JVM unfortunately does not offer yet any easy way, to have different versions of the same jar in the classpath (See Section 20.1.4, “Dependency management and Java”). What Gradle offers you is a resolution strategy, by default the newest version is used. To deal with problems due to version conflicts, reports with dependency graphs are also very helpful. Such reports are another feature of dependency management.

20.1.4. Dependency management and Java

Traditionally, Java has offered no support at all for dealing with libraries and versions. There are no standard ways to say that foo-1.0.jar depends on a bar-2.0.jar. This has led to proprietary solutions. The most popular ones are Maven and Ivy. Maven is a complete build system whereas Ivy focuses solely on dependency management.

Both approaches rely on descriptor xml files, which contains information about the dependencies of a particular jar. Both also use repositories where the actual jars are placed together with there descriptor files. And both offer resolution for conflicting jar versions in one form or the other. Yet we think the differences of both approaches are gigantic in terms of flexibility and maintainability. Beside this, Ivy fully supports the Maven dependency handling. So with Ivy you have access to both worlds. We like Ivy very much. Gradle uses it under the hood for its dependency management. Ivy is most often used via Ant and XML descriptors. But it also has a very good API. We integrate deeply with Ivy via its API. This enables us to build new concepts on top of Ivy which Ivy does not offer itself.

Right now there is a lot of movement in the field of dependency handling. There is OSGi and there is JSR-277. OSGi is available already, JSR-277 is supposed to be shipped with Java 7. These technologies deal also with a painful problem which is neither solved by Maven nor by Ivy. This is enabling different versions of the same jar to be used at runtime.

20.2. How to declare your dependencies

People who know Ivy have come across most the concepts we are going to introduce now. But Gradle does not use any XML for declaring the dependencies (e.g. no ivy.xml file). It has its own notations which is part of the Gradle build file.

20.2.1. Configurations

Dependencies are grouped in configurations. Configurations have a name and they can extend each other. If you use the Java or Groovy plugin, Gradle adds a number of related configurations to your build. The plugin also associates configurations with tasks. See Section 20.3, “Java Plugin and Dependency Management” for details. Of course you can add your own configurations on top of that. This is very handy for example for adding dependencies not needed for building or running your software (e.g. additional JDBC drivers). You might want to add such dependencies to a distribution of your software.

A dependency can belong to more than one configuration although that might be rather the exception. What is a dependency after all and how do you add it to a configuration?

20.2.2. Module Dependencies

Module dependencies are the most common dependencies. They correspond to a dependency in a repository you have declared. Gradle provides different notations for module dependencies. The most common notation for such a dependency follows the pattern: [group]:[artifact]:[version]. Here is an example for a module dependency:

dependencies {
    compile "org.hibernate:hibernate:3.0.5"
}

If you declare such a dependency, Gradle looks for a corresponding module descriptor file (pom.xml or ivy.xml) in the repositories. If such a module descriptor file exists, it is parsed and the artifacts of this module (in this case hibernate-3.0.5.jar) as well as its dependencies are downloaded. If no such module descriptor file exists, Gradle looks for a file called hibernate-3.0.5.jar to download.

A module dependency has an API to allow for further configuration. For example if the module descriptor (e.g. pom.xml) declares dependencies you don't want you have, you can exclude them:

dependencies {
    compile("org.codehaus.groovy:groovy-all:1.5.4") {
            exclude(module: 'jline')
            exclude(group: 'junit', module: 'junit')
    }
}

Have a look at ModuleDependency to learn more about the API.

20.2.2.1. Classifiers

The Maven dependency management has the notion of classifiers. Gradle supports this. To use Classifiers in Maven you can type: "org.testng:testng:5.8:jdk15".

20.2.2.2. Artifact only notation

An artifact only notation creates a module dependency which only downloads one artifact file. The notation for such a dependency follows the pattern: [group]:[artifact]:[version]@[extension] or [group]:[artifact]:[version]:[classifier]@[extension]. For example:

dependencies {
    compile "org.apache.ant:ant-junit:1.7.0@jar"
}

Gradle needs a repository somewhere where this artifact can be found, but there is no xml descriptor required in the repository. If there is one, it is ignored. In the simplest case such a repository is a folder on your local machine.

20.2.3. Client Module Dependencies

Client module dependencies enable you to declare transitive dependencies directly in your build script. Client module dependencies can be nested.

addClientModule(confs: ['compile'], id: "org.codehaus.groovy:groovy-all:1.5.4") {
    addDependency("commons-cli:commons-cli:1.0:jar")
    addClientModule("org.apache.ant:ant:1.7.0") {
        addDependency("org.apache.ant:ant-launcher:1.7.0:jar")
        addDependency("org.apache.ant:ant-junit:1.7.0")
    }
}

This declares a dependency of your project on Groovy. Groovy itself has dependencies. But Gradle does not look for an xml descriptor to figure them out but gets the information from the build file. The dependencies of a client module can be normal module dependencies or artifact dependencies or another client module. Have also a look at ClientModule

In the current release Client Modules have one limitation. For example if your project is a library and you want this library to be uploaded to your company's Maven or Ivy repository. Gradle uploads the jars of your project to the company repository together with the XML descriptor file of the dependencies. If you use Client Modules the dependency declaration in the XML descriptor file is not correct. We try to improve this in a future release of Gradle.

20.2.4. Project dependencies

Gradle distinguishes between external dependencies and dependencies on projects which are part of the same multi-project build. For the latter you can declare Project Dependencies.

dependencies {
    compile project(':shared')
}

Have also a look at ProjectDependency

Multi-project builds are discussed in Chapter 23, Multi-project Builds.

20.2.5. Global Excludes

You can exclude a transitive dependency for all your dependencies via global excludes.

dependencies {
    excludeRules.add(group: 'junit', module: 'junit')
}

You can either specify only the organization (group) or only the module name. Have also a look at ExcludeRuleContainer

20.2.6. Ivy dependencies

Gradle offers its own notation to describe dependencies. Under the hood we transform them into ivy dependency objects. Our notation provides a large subset of what is possible with Ivy. If you want or need to options that can't be expresses by the Gradle domain, you have two options:

You can use our ivy transforms to modify the Ivy objects created by Gradle. Look at Dependency to learn more.

Or you can pass ivy dependency objects directly to Gradle.

DefaultDependencyDescriptor dependencyDescriptor = new DefaultDependencyDescriptor(
            new ModuleRevisionId(new ModuleId('junit', 'junit'), '4.2'), false)
// do more configuration with the descriptor
dependencies {
    addDependencyDescriptors dependencyDescriptor
}

20.2.7. Configuring the Dependency Manager

In the examples above we have already configured the dependency manager. How does this work? The project object offers a property called dependencies. If you call dependencies with a closure, all statements within the closure are delegated first to the dependency manager. This is the same mechanism which is used for configuring tasks.

20.3. Java Plugin and Dependency Management

The Java Plugin preconfigures the dependency management. It adds a set of configurations and links the tasks like compile and test to this configuration. Table 20.1, “Java/Groovy Configurations” shows the details. The Java plugin defines also where to find the jars and zips to be uploaded. Finally it does a couple of settings for multi-project builds. If you have for example declared a project dependency for the compile configuration you don't want this project to be build if you execute a clean.

Table 20.1. Java/Groovy Configurations

Name Extends Task Meaning
compile - compile Compile time dependencies
runtime compile - Runtime dependencies
testCompile compile testCompile Additional dependencies for compiling tests.
testRuntime runtime, testCompile test Additional dependencies for running tests only.
libs - uploadLibs Dependencies (e.g. jars) produced by this project.
default runtime, master - Dependencies produced and required by this project.
dists - uploadDists Archives added to the dists bundle belong to this configuration.

20.4. Strategies of transitive dependency management

Many projects rely on the Maven2 repository. This is not without problems.

  • The IBibilio repository is often down or has a very long response time.

  • The pom.xml's of many projects have wrong informations. (as one example, the pom of commons-httpclient-3.0 declares junit as a runtime dependency).

  • For many projects there is not one right set of dependencies (as more or less impose by he pom format).

If your project relies on the IBibilio repository you are likely to need an additional custom repository, because:

  • You might need dependencies that are not uploaded to IBibilio yet.

  • You want to deal properly with wrong metadata in a IBibilio pom.xml.

  • You don't want to expose people who want to build your project, to the relatively frequent downtimes or very long response times of IBibilio.

It is not a big deal to set-up a custom repository. [23] But it is tedious, to keep it up to date. For a new version, you have always to create the new XML descriptor and the directories. And your custom repository is another infrastructure element which might have downtimes and needs to be updated. To enable historical builds, you need to keep all the past libraries. It is another layer of indirection, which contains information relevant for your build and you have to navigate to the lengthy path with your browser to get the information. All this is not really a big deal but in its sum it has a relevant impact on your agility. Why should you cope with this? You pay something, so you should also get something, right? So we end up with the question: Does it make sense to store the dependency information (and the dependencies) in remote repositories? Our answer is: It depends.

20.4.1. Enterprise Environments

In a larger enterprise environment you are likely to have a number of independent builds, possibly many different, large multi-project builds. Here a repository infrastructure makes a lot of sense. You have already infrastructure that guarantees a high uptime. Multiple projects can share there information about certain common dependencies they have. There is a central place to look for dependency information. And the repositories are used to integrate the internal projects with each other. One project publishes itself to the company repository, with all its dependency information stored in an ivy.xml or pom.xml file. [24] Together with a continuous integration server this offers a strong integration for projects with separate builds. As you have seen, Gradle fully supports this approach.

20.4.2. Other environments

But what about other environments. What about a typical open source projects like Gradle or environments which consists of a single multi-project build . They don't integrate with other projects in the same environment or need to share dependency information in this environment. In such a (very common) case we think dependency management based on remote repositories is an unnecessary indirection which makes things more complicated than necessary. Gradle itself (which is build by Gradle) stores its dependencies in svn. There is a lib folder which contains all jars needed to build Gradle. Yet we have a complete management of our dependencies. For Gradle the lib folder is a local repository containing all the jars (in a flat structure). There are no xml descriptors. We use either client module dependencies to express our dependency relations, or artifact dependencies in case a first level dependency has no transitive dependencies. People can check out Gradle from svn and have everything necessary to build it. The same applies to our source distribution.

You might argue that such an approach works only for projects like Gradle, which is not used as a library but is simply a distribution. What about open source library projects (e.g. commons-httpclient) that need to upload themselves to the Maven2 repo together with a pom.xml file. As soon as the limitation mentioned in Section 20.2.3, “Client Module Dependencies” has been overcome, your project can upload to such a repository without relying on XML descriptor files themselves.

You could also have a mixed strategy. If your main concern is bad metadata in the and maintaining custom XML descriptors, Client Modules offer an alternative. But you can of course still use Maven2 repo and your custom repository as a repository for jars only and still enjoy transitive dependency management.

20.4.3. Implicit transitive dependencies

There is another way to deal with transitive dependencies without xml descriptor files. You can do this with Gradle, but we don't recommend it. We mention it for the sake of completeness and comparison with other build tools.

List groovy = ["org.codehaus.groovy:groovy-all:1.5.4:jar",
               "commons-cli:commons-cli:1.0:jar",
               "org.apache.ant:ant:1.7.0:jar"]
List hibernate = [...] // enter the dependencies here
dependencies {
    compile groovy
    runtime hibernate
}

The trick is to use only artifact dependencies and group them in lists. That way you have somehow expressed, what are your first level dependencies and what are transitive dependencies.

But for the Gradle dependency management all dependencies are considered first level dependencies. The dependency reports don't show your real dependency graph and the compile task uses all dependencies, not just the first level dependencies. All in all, your build is less maintainable and reliable than it could be when using client modules. And you don't gain anything.

20.5. Repositories and Resolvers

20.5.1. Introduction

Gradle (Ivy) distinguishes between resolvers and repositories. A repository is the physical source for your dependencies. A resolver is responsible for retrieving a dependency (usually from a repository but not necessarily). As a Gradle or Ivy user, resolvers are the objects your are working with. You can also aggregate multiple resolvers in a certain order (not just linked lists). It is one of the very strengths of Ivy, how versatile you can aggregate resolvers and that you can write easily your own. Gradle for example makes use of this to implement client modules. If you add a resolver, you always have to give it a name. This name is used to internally address a resolver but is also used for the dependency logging. The Java plugin does not add any default resolver to your projects dependency manager. Gradle offers a couple of convenience methods to add resolvers. You can also always add an instance of an Ivy resolver object directly.

20.5.2. Maven Repository

To add a resolver for the Maven2 repository (http://repo1.maven.org/maven2) simply type:

dependencies {
    addMavenRepo()
}

The added resolver has the name MavenRepo and is added to the classpathResolvers (see Section 20.5.5, “Resolver Container”).

If you want to add a custom repository with a Maven layout you can type:

dependencies {
    addMavenStyleRepo('myrepo', 'http://repo.gradle.org')
}

Quite often certain jars are not in the official Maven repository for licensing reasons (e.g. JTA). But the poms are there and you want to use them. Gradle (and Ivy) use the same resolver to look for the pom and the corresponding artifact. It is now possible to define a chain of resolvers, where one resolver is used for retrieving the pom and another resolver is used for retrieving the artifact. For the dependencies of the artifact the chain of resolvers can be used. To solve this problem

dependencies {
    addMavenRepo('http://repo.gradle.org', 'http://repo2.gradle.org')
}

Now Gradle looks only in the official Maven repository for the poms, but looks in both the official Maven repository and the two repositories specified above for the artifacts belonging to the pom. Let's look at an example to understand this better.

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>repotest</groupId>
    <artifactId>repotest</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <artifactId>testdep</artifactId>
            <groupId>testdep</groupId>
            <version>1.0</version>
        </dependency>
    </dependencies>
</project>

We have 4 files in different repositories. For this example let's assume that repotest-1.0.pom is in the official Maven repository and that the other files are in http://repo.gradle.org.

Let's define our resolvers like this:

dependencies {  
    addMavenRepo() 
    addMavenStyleRepo('myrepo', 'http://repo.gradle.org')
    compile "repotest:repotest:1.0"    
}

Gradle finds repotest-1.0.pom in the official Maven repo. After this it tries to find the corresponding artifact repotest-1.0.jar. It looks only in the Maven repo for this file as it expects to find pom and artifact by the same resolver. The build fails.

Let's try to improve this:

dependencies {  
    addMavenRepo('http://repo.gradle.org') 
    compile "repotest:repotest:1.0"    
}

Gradle finds repotest-1.0.pom in the Maven repo. After this it tries to find the corresponding artifact repotest-1.0.jar and finds it in http://repo.gradle.org. But what about testdep-1.0.pom? As Gradle looks for poms only in the Maven repo it can't find this pom file. [25]

The final correct version to solve our use case is:

dependencies {  
    addMavenRepo('http://repo.gradle.org') 
    addMavenStyleRepo('myrepo', 'http://repo.gradle.org') 
    compile "repotest:repotest:1.0"    
}

20.5.3. Flat Directory Resolver

If you want to use a (flat) filesytem directory as a repository, simply type:

dependencies {
    addFlatDirResolver('lib', "$rootDir/lib1", new File(rootDir, 'lib2'))
    dependencies(':junit:4.4', ':commons-io:1.3.1:jar')
}

In the example we assign multiple directories to a flat directory resolver [26] . The first argument is the name of the resolver. The group attributes in the dependency declaration is empty (but there has to be a colon at the beginning). Specifying the extension (e.g. jar) is optional and defaults to jar. You could add a group attribute if you are in a chain of resolvers. This resolver simply ignores it. The repositories could look like this:

project-root
  - lib1
    - junit-4.4.jar
  - lib2
    - commons-io-1.3.1.jar

The addFlatDirResolver methods adds a resolver to the classpathResolvers (see Section 20.5.5, “Resolver Container”)

You can add easily file system repositories with a different layout (see Section 20.5.6, “More about Ivy resolvers”)

20.5.4. Cache

When Gradle downloads dependencies from remote repositories it stores them in a local cache located at USER_HOME/.gradle/cache. When Gradle downloads dependencies from one of its predefined local resolvers (e.g. Flat Directory resolver), the cache is not used as an intermediate storage for dependencies.

20.5.5. Resolver Container

There are three hooks for adding resolvers. Via the resolvers assigned to the classpathResolvers property of the dependency manager, the compile, compileTests and test tasks retrieve their dependencies. The uploadLibs and uploadDists tasks have both an uploadResolvers property. You can assign one resolver to multiple hooks.

All of those hooks are instances of ResolverContainer . This class provided methods for adding new resolvers at a particular position in the resolve chain. [27] Ivy offers more complex structures for resolvers than simple chains. The resolver container does not offer particular support for this. But by manipulating its properties directly you could set up such other structures.

20.5.6. More about Ivy resolvers

Gradle, thanks to Ivy under its hood, is extremely flexible regarding repositories:

  • There are many options for the protocol to communicate with the repository (e.g. filesystem, http, ssh, ...)

  • Each repository can have its own layout.

If you declare a dependency like junit:junit:3.8.2 how does Gradle find it in the repositories. Somehow the dependency information has to be mapped to a path. In contrast to Maven, where this path is fixed, with Gradle you can define a pattern how this path should look like. Here are some examples: [28]

// Maven2 layout (if a repository is marked as Maven2 compatible, the organization (group) is split into subfolders according to the dots.)
someroot/[organisation]/[module]/[revision]/[module]-[revision].[ext]

// Typical layout for an ivy repository (the organization is not split into subfolder)
someroot/[organisation]/[module]/[revision]/[type]s/[artifact].[ext]

// Simple layout (the organization is not used, no nested folders.)
someroot/[artifact]-[revision].[ext]

To add any kind of repository (you can pretty easy write your own ones) you can do:

dependencies {
    classpathResolvers.add(new WebdavResolver()) {
            name = 'gradleReleases'
            user = codehausUserName
            userPassword = codehausUserPassword
            addArtifactPattern(root + "[artifact]-[revision].[ext]")
}

WebdavResolver is a class that implements an Ivy interface and is part of the Gradle distribution. An overview of which Resolvers are offered by Ivy and thus also by Gradle can be found here. With Gradle you just don't configure them via xml but directly via their API.



[23] If you want to shield your project from the downtimes of IBibilio things get more complicated. You probably want to set-up a repository proxy for this. In an enterprise environment this is rather common. For an open source project it looks like overkill.

[24] As discussed in Section 20.4.2, “Other environments” this will be also possible with client modules in a future release.

[25] To make things more flexible (or complicated): By default the build would not fail, as Ivy's default behavior is to create internally a default pom if it can't find a pom. This default pom has of course no dependencies and defines just the artifact testdep-1.0.jar and would be found in http://repo.gradle.org. If you want the build to fail if a pom can't be found you must the set the allownomd property of the resolver to false.

[26] You can pass any type for describing a path, as long as the type's toString() method returns a valid path.

[27] Ivy power users can set dependencies.chainConfigurer = { // some statements }. This closure is applied to the ChainResolver containing the other Ivy resolvers.

[28] At http://ant.apache.org/ivy/history/latest-milestone/concept.html you can learn more about ivy patterns.

Chapter 21. Interacting with Maven Repositories

21.1. Introduction

With Gradle you can deploy to remote Maven repositories or install to your local Maven repository. This includes all Maven metadata manipulation and works also for Maven snapshots. In fact, Gradle's deployment is 100 percent Maven compatible as we use the native Maven Ant tasks under the hood.

Deploying to a Maven repository is only half the fun if you don't have a pom. Fortunately Gradle can generate this pom for your, from the dependency information it has.

21.2. Deploying to a Maven Repository

Let's assume your projects libs bundle produces just one jar file. Now you want to deploy this jar file to a remote Maven repository.

uploadLibs {
    uploadResolvers.addMavenDeployer('maven-deployer') {
        repository(url: "file://localhost/tmp/myRepo/")
    }
}

That is all. Calling the uploadLibs task will generate the pom and deploys the artifact and the pom to the specified repository.

There is some more work to do if you need support for other protocols than file. In this case the native Maven code we delegate to needs additional libraries. Those libraries depend on the protocol you need. The available protocols and the corresponding libraries are listed in Table 21.1, “Protocol jars for Maven deployment”. Those libraries have again transitive dependencies which have transitive dependencies. You need to provide the complete list of those to the MavenDeployer{ [29] }. The easiest way to do this is the following:

dependencies {
    addConfiguration('deployerJars')
    addMavenRepo()
    deployerJars "org.apache.maven.wagon:wagon-ssh:1.0-beta-2"
}
uploadLibs {
    uploadResolvers.addMavenDeployer('maven-deployer') {
        repository(url: "scp://repos.mycompany.com/releases")
        addProtocolProviderJars(dependencies.resolve('deployerJars'))
    }
}

Table 21.1. Protocol jars for Maven deployment

Protocol Library
http org.apache.maven.wagon:wagon-http:1.0-beta-2
ssh org.apache.maven.wagon:wagon-ssh:1.0-beta-2
ssh-external org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2
scp org.apache.maven.wagon:wagon-scp:1.0-beta-2
ftp org.apache.maven.wagon:wagon-ftp:1.0-beta-2
webdav org.apache.maven.wagon:wagon-webdav:1.0-beta-2
file -

21.2.1. Configuration of the Maven Deployer

There are many configuration options for the Maven deployer. The configuration is done with a nested tree. Here is a configuration with all existing elements of this tree. Table 21.2, “Configuration elements of the MavenDeployer” lists the available elements and a link to the javadoc of the corresponding class. In the javadoc you can see the possible attributes you can set for a particular element.

uploadLibs {
    uploadResolvers.addMavenDeployer('maven-deployer') {
        uniqueVersion = true
        repository(url: "ssh://localhost/tmp/myRepo/") {
            authentication(userName: "me", password: "myPassword")
            releases()
            snapshots()
            proxy()
        }
        snapshotRepository(url: "ssh://localhost/tmp/mySnapshotRepo/") {
            authentication(userName: "me", password: "myPassword")
            releases()
            snapshots()
            proxy()
        }
    }
}

In Maven you can define repositories and optionally snapshot repositories. If not snapshot repository is defined releases and snapshots are both deployer to the repository element. Otherwise snapshots are deployed to the snapshotRepository element.

21.2.2. Installing to the local repository

The easiest way to install to the local Maven repository is by using the maven plugin:

usePlugin('maven')

This plugin adds an install task. This install task depends on the libs task of the Java plugin. It installs your libraries to your local Maven repository. If the default location for the local repository is redefined in a Maven settings.xml, this is considered by this task.

21.3. Maven Pom Generation

The Maven Poms are automatically generated by Gradle. You can find the generated poms in the <buildDir>/lib-poms and <buildDir>/dist-poms directory. In many scenarios it just works and you don't have to do anything. But there are situations were you want or have to customize the pom generation.

21.3.1. Changing non-dependency elements of the pom

You might want that the artifact deployed to the maven repository has a different version or name than the artifact generated by Gradle. In such a case you can apply custom settings.

uploadLibs {
    uploadResolvers.addMavenDeployer('maven-deployer') {
        repository(url: "file://localhost/tmp/myRepo/")
        pom.version = '1.0Maven'
        pom.artifactId = 'myName'
    }
}

To learn about all the customizable attributes of a pom have a look here: MavenPom .

To do this for the Maven Installer added by the Maven plugin (see Section 21.2.2, “Installing to the local repository”), you can do:

install {
    configure(uploadResolvers.get('maven-installer')) {
        pom.version = '1.0Maven'
        pom.artifactId = 'myName'
    }
}

21.3.2. Multiple Artifacts per project

Maven can only deal with one artifact per project. This is also reflected in the structure of the Maven pom. We think there are many situations where it makes sense to have more than one artifact per project. Obviously just for the fact that those artifacts have different names but belong to the same group, they need different poms. Another use case is that you might not want to publish all project artifacts to the Maven Repository but only a subset. If your project libs or dists have more than one artifact you have to assign each artifact you want to publish. The MavenDeployer and the MavenInstaller both provide an API for this:

uploadLibs {
    uploadResolvers.addMavenDeployer('maven-deployer') {
        repository(url: "file://localhost/tmp/myRepo/")
        addFilter('api') { artifact, file ->
            artifact.name == 'api'
        }
        addFilter('service') { artifact, file ->
            artifact.name == 'service'
        }
        pom('api').version = 'mySpecialMavenVersion'
    }
}

To learn more about this have a look at GroovyPomFilterContainer and its associated classes.

21.3.3. Dependency Mapping

The Java plugin configures the a default mapping between Gradle configuration and Maven scopes. Most of the time you don't need to touch this and you can safely skip this section. A Gradle-Maven dependency mapping is not trivial, as in Gradle dependencies can belong to more than one configuration. Our mapping works like the following. You can map a configuration to one and only one scope. Different configurations can be mapped to more than one scope. One can assign also a priority to a particular configuration-to-scope mapping. The default mapping is accessible via the dependency manager like dependencies.defaultMavenScopeMapping. Have a look at Conf2ScopeMappingContainer to learn how you can use the returned instance. Let's look at different mapping scenarios:

  • A dependency belongs to only one configuration: The first thing Gradle checks is whether there is a mapping for this configuration. If there is none, the dependency is by default not added to the pom. By setting the mapping property includeUnmappedConfigurations to true, such a dependency will be added. If the configuration is mapped, the corresponding scope is obvious and the dependency is added.

  • A dependency belongs to more than one mapped configuration: If the mapped configurations map to the same scope the situation is clear. If the mapped configurations map to different scopes the configuration mapping with the highest priority is chosen. If there is more than one configuration with a highest priority and they map to different scopes an exception is thrown.

Gradle exclude rules are converted to Maven excludes if possible. Such a conversion is possible if in the Gradle exclude rule the organisation as well as the module name is specified (as Maven needs both in contrast to Ivy). Right now Global Excludes are not converted to the Maven Pom.

21.3.4. Planned future features

We plan support for conversion of global excludes. We also plan support for the new Ivy override element, which corresponds to the dependencyManagement element of a Maven pom. Last but not least we want to make the customization more powerful, by enabling to add custom dependency elements to the pom and remove/modify auto-generated ones.



[29] It is planned for a future release to provide out-of-the-box support for this

Chapter 22. The Build Lifecycle

We said earlier, that the core of Gradle is a language for dependency based programming. In Gradle terms this means that you can define tasks and dependencies between tasks. Gradle guarantees that these tasks are executed in the order of their dependencies, and that each task is executed only once. Those tasks form a Directed Acyclic Graph. There are build tools that build up such a dependency graph as they execute their tasks. Gradle builds the complete dependency graph before any task is executed. This lies at the heart of Gradle and makes many things possible which would not be possible otherwise.

Your build scripts configure this dependency graph. Therefore they are strictly speaking build configuration scripts.

22.1. Build Phases

A Gradle build has three distinct phases.

Initialization

Gradle supports single and multi-project builds. During the initialization phase, Gradle determines which projects are going to take part in the build, and creates a Project instance for each of these projects.

Configuration

The build scripts of all projects which are part of the build are executed. This configures the project objects.

Execution

Gradle determines the subset of the tasks, created and configured during the configuration phase, to be executed. The subset is determined by the task name arguments passed to the gradle command and the current directory. Gradle then executes each of the selected tasks.

22.2. Settings File

Beside the build script files, Gradle defines a settings file. The settings file is determined by Gradle via a naming convention. The default name for this file is settings.gradle. Later in this chapter we explain, how Gradle looks for a settings file.

The settings file gets executed during the initialization phase. A multiproject build must have a settings.gradle file in the root project of the multiproject hierarchy. It is required because in the settings file it is defined, which projects are taking part in the multi-project build (see Chapter 23, Multi-project Builds). For a single-project build, a settings file is optional. You might need it for example, to add libraries to your build script classpath (see Chapter 24, Organizing Build Logic). Let's first do some introspection with a single project build:

Example 22.1.  settings.gradle

println 'This is executed during the initialization phase.'

Example 22.2.  build.gradle

println 'This is executed during the configuration phase.'

task test {
    println 'This is executed during the execution phase.'
}

Example 22.3. Output of gradle test

> gradle test
This is executed during the initialization phase.
This is executed during the configuration phase.
:test
This is executed during the execution phase.

BUILD SUCCESSFUL

Total time: 1 secs

For a build script, the property access and method calls are delegated to a project object. Similarly property access and method calls within the settings file is delegated to a settings object. Have a look at Settings .

22.3. Multi-Project Builds

A multi-project build is a build where you build more than one project during a single execution of Gradle. You have to declare the projects taking part in the multiproject build in the settings file. There is much more to say about multi-project builds in the chapter dedicated to this topic (see Chapter 23, Multi-project Builds).

22.3.1. Project Locations

Multi-project builds are always represented by a tree with a single root. Each element in the tree represent a project. A project has a virtual and a physical path. The virtual path denotes the position of the project in the multi-project build tree. The project tree is created in the settings.gradle file. By default it is assumed that the location of the settings file is also the location of the root project. But you can redefine the location of the root project in the settings file.

22.3.2. Building the tree

In the settings file you can use a set of methods to build the project tree. Hierarchical and flat physical layouts get special support.

22.3.2.1. Hierarchical Layouts

Example 22.4.  settings.gradle

include 'project1', 'project2', 'project2:child1'

The include method takes as an argument a relative virtual path to the root project. This relative virtual path is assumed to be equals to the relative physical path of the subproject to the root project. You only need to specify the leafs of the tree. Each parent path of the leaf project is assumed to be another subproject which obeys to the physical path assumption described above.

22.3.2.2. Flat Layouts

Example 22.5.  settings.gradle

includeFlat 'project3', 'project4'

The includeFlat method takes directory names as an argument. Those directories need to exist at the same level as the root project directory. The location of those directories are considered as child projects of the root project in the virtual multi-project tree.

22.3.3. Modifying Elements of the Project Tree

The multi-project tree created in the settings file is made up of so called project descriptors. You can modify these descriptors in the settings file at any time. To access a descriptor you can do:

Example 22.6.  settings.gradle

println rootProject.name
println project(':projectA').name

Using this descriptor you can change the name, project directory and build file of a project.

Example 22.7.  settings.gradle

rootProject.name = 'main'
project(':projectA').projectDir = new File(settingsDir, '../my-project-a')
project(':projectA').buildFileName = 'projectA.gradle'

Have a look at ProjectDescriptor for more details.

22.4. Initialization

How does Gradle know whether to do a single or multiproject build? If you trigger a multiproject build from the directory where the settings file is, things are easy. But Gradle also allows you to execute the build from within any subproject taking part in the build. [30] If you execute Gradle from within a project that has no settings.gradle file, Gradle does the following:

  • It searches for a settings.gradle in a directory called master which has the same nesting level as the current dir.

  • If no settings.gradle is found, it searches the parent directories for the existence of a settings.gradle file.

  • If no settings.gradle file is found, the build is executed as a single project build.

  • If a settings.gradle file is found, Gradle checks if the current project is part of the multiproject hierarchy defined in the found settings.gradle file. If not, the build is executed as a single project build. Otherwise a multiproject build is executed.

What is the purpose of this behavior? Somehow Gradle has to find out, whether the project you are into, is a subproject of a multiproject build or not. Of course, if it is a subproject, only the subproject and its dependent projects are build. But Gradle needs to create the build configuration for the whole multiproject build (see Chapter 23, Multi-project Builds). Via the -u command line option, you can tell Gradle not to look in the parent hierarchy for a settings.gradle file. The current project is then always build as a single project build. If the current project contains a settings.gradle file, the -u option has no meaning. Such a build is always executed as:

  • a single project build, if the settings.gradle file does not define a multiproject hierarchy

  • a multiproject build, if the settings.gradle file does define a multiproject hierarchy.

The auto search for a settings file does only work for multi-project builds with a physical hierarchical or flat layout. For a flat layout you must additionally obey to the naming convention described above. Gradle supports arbitrary physical layouts for a multiproject build. But for such arbitrary layouts you need to execute the build from the directory where the settings file is located. For how to run partial builds from the root see Section 23.4, “Running Tasks by their Absolute Path”. In our next release we want to enable partial builds from subprojects by specifying the location of the settings file as a command line parameter. Gradle creates Project objects for every project taking part in the build. For a single project build this is only one project. For a multi-project build these are the projects specified in Settings object (plus the root project). Each project object has by default a name equals to the name of its top level folder. Every project except the root project has a parent project and might have child projects.

22.5. Configuration and Execution of a Single Project Build

For a single project build, the workflow of the after initialization phases are pretty simple. The build script is executed against the project object that was created during the initialization phase. Then Gradle looks for tasks with names equal to those passed as command line arguments. If these task names exist, they are executed as a separate build in the order you have passed them. The configuration and execution for multi-project builds is discussed in Chapter 23, Multi-project Builds.

22.6. Responding to the Lifecycle in the Build Script

Your build script can receive notifications as the build progresses through its lifecyle. These notifications generally take 2 forms: You can either implement a particular listener interface, or you can provide a closure to execute when the notification is fired. The examples below use closures. For details on how to use the listener interfaces, refer to the API documentation.

22.6.1. Project evaluation

You can receive a notification immediately before and after a project is evaluated. This can be used to do things like performing additional configuration once all the definitions in a build script have been applied, or for some custom logging or profiling.

Below is an example which adds a test task to each project with the hasTests property set to true.

Example 22.8.  build.gradle

allprojects {
    afterEvaluate { project ->
        if (project.hasTests) {
            println "Adding test task to $project"
            project.tasks.add('test') {
                println "Running tests for $project"
            }
        }
    }
}

Example 22.9.  projectA.gradle

hasTests = true

Example 22.10. Output of gradle -q test

> gradle -q test
Adding test task to project ':projectA'
Running tests for project ':projectA'

This example uses method Project.afterEvaluate() to add a closure which is executed after the project is evaluated.

It is also possible to receive notifications when any project is evaluated. This example performs some custom logging of project evaluation. Notice that the afterProject notification is received regardless of whether the project evaluates successfully or fails with an exception.

Example 22.11.  build.gradle

build.afterProject {project, exception ->
    if (exception) {
        println "Evaluation of $project FAILED"
    } else {
        println "Evaluation of $project succeeded"
    }
}

Example 22.12. Output of gradle -q test

> gradle -q test
Evaluation of root project 'buildProjectEvaluateEvents' succeeded
Evaluation of project ':projectA' succeeded
Evaluation of project ':projectB' FAILED

You can also add a ProjectEvaluationListener to the Build to receive these events.

22.6.2. Task creation

You can receive a notification immediately after a task is added to a project. This can be used to set some default values or add behaviour before the task is made available in the build file.

The following example sets the srcDir property of each task as it is created.

Example 22.13.  build.gradle

tasks.whenTaskAdded { task ->
    task.srcDir = 'src/main/java'
}

task a

println "source dir is $a.srcDir"

Example 22.14. Output of gradle -q a

> gradle -q a
source dir is src/main/java

You can also add a TaskAction to a TaskContainer to receive these events.

22.6.3. Task execution graph ready

You can receive a notification immediately after the task execution graph has been populated. We have seen this already in Section 4.11, “Configure By DAG”.

You can also add a TaskExecutionGraphListener to the TaskExecutionGraph to receive these events.

22.6.4. Task execution

You can receive a notification immediately before and after any task is executed.

The following example logs the start and end of each task execution. Notice that the afterTask notification is received regardless of whether the task completes successfully or fails with an exception.

Example 22.15.  build.gradle

task ok

task broken(dependsOn: ok) {
    throw new RuntimeException('broken')
}

build.taskGraph.beforeTask { task ->
    println "executing $task ..."
}

build.taskGraph.afterTask { task, exception ->
    if (exception) {
        println "FAILED"
    }
    else {
        println "done"
    }
}

Example 22.16. Output of gradle -q broken

> gradle -q broken
executing task ':ok' ...
done
executing task ':broken' ...
FAILED

You can also use a TaskExecutionListener to the TaskExecutionGraph to receive these events.



[30] Gradle supports partial multiproject builds (see Chapter 23, Multi-project Builds).

Chapter 23. Multi-project Builds

The powerful support for multi-project builds is one of Gradle's unique selling points. This topic is also the intellectually most challenging.

23.1. Cross Project Configuration

Let's start with a very simple multi-project build. After all Gradle is a general purpose build tool at its core, so the projects don't have to be java projects. Our first examples are about marine life.

23.1.1. Defining Common Behavior

We have the following project tree. This is a multi-project build with a root project water and a subproject bluewhale.

Figure 23.1. Project layout

water/
  build.gradle
  settings.gradle
  bluewhale/

Note: The code for this example can be found at samples/userguide/multiproject/firstExample/water

Example 23.1.  settings.gradle

include 'bluewhale'

And where is the build script for the bluewhale project? In Gradle build scripts are optional. Obviously for a single project build, a project without a build script doesn't make much sense. For multiproject builds the situation is different. Let's look at the build script for the water project and execute it:

Example 23.2.  build.gradle

Closure cl = { task -> println "I'm $task.project.name" }
task hello(cl)
project(':bluewhale') {
    task hello(cl)
}

Example 23.3. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale

Gradle allows you to access any project of the multi-project build from any build script. The Project API provides a method called project(), which takes a path as an argument and returns the Project object for this path. The capability to configure a project build from any build script we call cross project configuration. Gradle implements this via configuration injection.

We are not that happy with the build script of the water project. It is inconvenient to add the task explicitly for every project. We can do better. Let's first add another project called krill to our multi-project build.

Figure 23.2. Project layout

water/
  build.gradle
  settings.gradle
  bluewhale/
  krill/

Note: The code for this example can be found at samples/userguide/multiproject/addKrill/water

Example 23.4.  settings.gradle

include 'bluewhale', 'krill'

Now we rewrite the water build script and boil it down to a single line.

Example 23.5.  build.gradle

allprojects {
    task hello { task -> println "I'm $task.project.name" }
}

Example 23.6. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
I'm krill

Is this cool or is this cool? And how does this work? The Project API provides a property allprojects which returns a list with the current project and all its subprojects underneath it. If you call allprojects with a closure, the statements of the closure are delegated to the projects associated with allprojects. You could also do an iteration via allprojects.each, but that would be more verbose.

Other build systems use inheritance as the primary means for defining common behavior. We also offer inheritance for projects as you will see later. But Gradle uses configuration injection as the usual way of defining common behavior. We think it provides a very powerful and flexible way of configuring multiproject builds.

23.2. Subproject Configuration

The Project API also provides a property for accessing the subprojects only.

23.2.1. Defining Common Behavior

Example 23.7.  build.gradle

allprojects {
    task hello {task -> println "I'm $task.project.name" }
}
subprojects {
    hello.doLast {println "- I depend on water"}
}

Example 23.8. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
- I depend on water
I'm krill
- I depend on water

23.2.2. Adding Specific Behavior

You can add specific behavior on top of the common behavior. Usually we put the project specific behavior in the build script of the project where we want to apply this specific behavior. But as we have already seen, we don't have to do it this way. We could add project specific behavior for the bluewhale project like this:

Example 23.9.  build.gradle

allprojects {
    task hello {task -> println "I'm $task.project.name" }
}
subprojects {
    hello.doLast {println "- I depend on water"}
}
project(':bluewhale').hello.doLast {
    println "I'm the largest animal that has ever lived on this planet."
}

Example 23.10. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
- I depend on water
I'm the largest animal that has ever lived on this planet.
I'm krill
- I depend on water

As we have said, we usually prefer to put project specific behavior into the build script of this project. Let's refactor and also add some project specific behavior to the krill project.

Figure 23.3. Project layout

water/
  build.gradle
  settings.gradle
  bluewhale/
    build.gradle
  krill/
    build.gradle

Note: The code for this example can be found at samples/userguide/multiproject/spreadSpecifics/water

Example 23.11.  settings.gradle

include 'bluewhale', 'krill'

Example 23.12.  bluewhale/build.gradle

hello.doLast { println "- I'm the largest animal that has ever lived on this planet." }

Example 23.13.  krill/build.gradle

hello.doLast {
    println "- The weight of my species in summer is twice as heavy as all human beings."
}

Example 23.14.  build.gradle

allprojects {
    task hello {task -> println "I'm $task.project.name" }
}
subprojects {
    hello.doLast {println "- I depend on water"}
}

Example 23.15. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
- I depend on water
- I'm the largest animal that has ever lived on this planet.
I'm krill
- I depend on water
- The weight of my species in summer is twice as heavy as all human beings.

23.2.3. Project Filtering

To show more of the power of configuration injection, let's add another project called tropicalFish and add more behavior to the build via the build script of the water project.

23.2.3.1. Filtering By Name

Figure 23.4. Project layout

water/
  build.gradle
  settings.gradle
  bluewhale/
    build.gradle
  krill/
    build.gradle
  tropicalFish/

Note: The code for this example can be found at samples/userguide/multiproject/addTropical/water

Example 23.16.  settings.gradle

include 'bluewhale', 'krill', 'tropicalFish'

Example 23.17.  build.gradle

allprojects {
    task hello {task -> println "I'm $task.project.name" }
}
subprojects {
    hello.doLast {println "- I depend on water"}
}
configure(subprojects.findAll {it.name != 'tropicalFish'}) {
    hello.doLast {println '- I love to spend time in the arctic waters.'}
}

Example 23.18. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
- I depend on water
- I love to spend time in the arctic waters.
- I'm the largest animal that has ever lived on this planet.
I'm krill
- I depend on water
- I love to spend time in the arctic waters.
- The weight of my species in summer is twice as heavy as all human beings.
I'm tropicalFish
- I depend on water

The configure() method takes a list as an argument and applies the configuration to the projects in this list.

23.2.3.2. Filtering By Properties

Using the project name for filtering is one option. Using dynamic project properties is another.

Figure 23.5. Project layout

water/
  build.gradle
  settings.gradle
  bluewhale/
    build.gradle
  krill/
    build.gradle
  tropicalFish/
    build.gradle

Note: The code for this example can be found at samples/userguide/multiproject/tropicalWithProperties/water

Example 23.19.  settings.gradle

include 'bluewhale', 'krill', 'tropicalFish'

Example 23.20.  bluewhale/build.gradle

arctic = true
hello.doLast { println "- I'm the largest animal that has ever lived on this planet." }

Example 23.21.  krill/build.gradle

arctic = true
hello.doLast {
    println "- The weight of my species in summer is twice as heavy as all human beings."
}

Example 23.22.  tropicalFish/build.gradle

arctic = false

Example 23.23.  build.gradle

allprojects {
    task hello {task -> println "I'm $task.project.name" }
}
subprojects {
    hello {
        doLast {println "- I depend on water"}
        afterEvaluate { Project project ->
            if (project.arctic) { doLast {
                println '- I love to spend time in the arctic waters.' }
            }
        }
    }
}

Example 23.24. Output of gradle -q hello

> gradle -q hello
I'm water
I'm bluewhale
- I depend on water
- I'm the largest animal that has ever lived on this planet.
- I love to spend time in the arctic waters.
I'm krill
- I depend on water
- The weight of my species in summer is twice as heavy as all human beings.
- I love to spend time in the arctic waters.
I'm tropicalFish
- I depend on water

In the build file of the water project we use an afterEvaluate notification. This means that the closure we are passing gets evaluated after the build scripts of the subproject are evaluated. As the property arctic is set in those build scripts, we have to do it this way. You will find more on this topic in Section 23.6, “Dependencies - Which dependencies?”

23.3. Execution rules for multi-project builds

When we have executed the hello task from the root project dir things behaved in an intuitive way. All the hello tasks of the different projects were executed. Let's switch to the bluewhale dir and see what happens if we execute Gradle from there.

Example 23.25. Output of gradle -q hello

> gradle -q hello
I'm bluewhale
- I depend on water
- I'm the largest animal that has ever lived on this planet.
- I love to spend time in the arctic waters.

The basic rule behind Gradle's behavior is simple. Gradle looks down the hierarchy, starting with the current dir, for tasks with the name hello an executes them. One thing is very important to note. Gradle always evaluates every project of the multi-project build and creates all existing task objects. Then, according to the task name arguments and the current dir, Gradle filters the tasks which should be executed. Because of Gradle's cross project configuration every project has to be evaluated before any task gets executed. We will have a closer look at this in the next section. Let's now have our last marine example. Let's add a task to bluewhale andkrill.

Example 23.26.  bluewhale/build.gradle

arctic = true
hello.doLast { println "- I'm the largest animal that has ever lived on this planet." }

task distanceToIceberg {
    println '20 nautical miles'
}

Example 23.27.  krill/build.gradle

arctic = true
hello.doLast { println "- The weight of my species in summer is twice as heavy as all human beings." }

task distanceToIceberg {
    println '5 nautical miles'
}

Example 23.28. Output of gradle -q distanceToIceberg

> gradle -q distanceToIceberg
20 nautical miles
5 nautical miles

Here the output without the -q option:

Example 23.29. Output of gradle distanceToIceberg

> gradle distanceToIceberg
:bluewhale:distanceToIceberg
20 nautical miles
:krill:distanceToIceberg
5 nautical miles

BUILD SUCCESSFUL

Total time: 1 secs

The build is executed from the water project. Neither water nor tropicalFish have a task with the name distanceToIceberg. Gradle does not care. The simple rule mentioned already above is: Execute all tasks down the hierarchy which have this name. Only complain if there is no such task!

23.4. Running Tasks by their Absolute Path

As we have seen, you can run a multi-project build by entering any subproject dir and execute the build from there. All matching task names of the project hierarchy starting with the current dir are executed. But Gradle also offers to execute tasks by their absolute path (see also Section 23.5, “Project and Task Paths”):

Example 23.30. Output of gradle -q :hello :krill:hello hello

> gradle -q :hello :krill:hello hello
I'm water
I'm krill
- I depend on water
- The weight of my species in summer is twice as heavy as all human beings.
- I love to spend time in the arctic waters.
I'm tropicalFish
- I depend on water

The build is executed from the tropicalFish project. We execute the hello tasks of the water, the krill and the tropicalFish project. The first two tasks are specified by there absolute path, the last task is executed on the name matching mechanism described above.

23.5. Project and Task Paths

A project path has the following pattern: It starts always with a colon, which denotes the root project. The root project is the only project in a path that is not specified by its name. The path :bluewhale corresponds to the file system path water/project in the case of the example above.

The path of a task is simply its project path plus the task name. For example :bluewhale:hello. Within a project you can address a task of the same project just by its name. This is interpreted as a relative path.

Originally Gradle has used the '/' character as a natural path separator. With the introduction of directory tasks (see Section 10.3, “Directory Creation”) this was no longer possible, as the name of the directory task contains the '/' character.

23.6. Dependencies - Which dependencies?

The examples from the last section were special, as the projects had no Execution Dependencies. They had only Configuration Dependencies. Here is an example where this is different:

23.6.1. Execution Dependencies

23.6.1.1. Dependencies and Execution Order

Figure 23.6. Project layout

messages/
  settings.gradle
  consumer/
    build.gradle
  producer/
    build.gradle

Note: The code for this example can be found at samples/userguide/multiproject/dependencies/firstMessages/messages

Example 23.31.  settings.gradle

include 'consumer', 'producer'

Example 23.32.  consumer/build.gradle

task action {
    println "Consuming message: " +  System.getProperty('org.gradle.message')
}

Example 23.33.  producer/build.gradle

task action {
    println "Producing message:"
    System.setProperty('org.gradle.message', 'Watch the order of execution.')
}

Example 23.34. Output of gradle -q action

> gradle -q action
Consuming message: null
Producing message:

This did not work out. If nothing else is defined, Gradle executes the task in alphanumeric order. Therefore :consumer:action is executed before :producer:action. Let's try to solve this with a hack and rename the producer project to aProducer.

Figure 23.7. Project layout

messages/
  settings.gradle
  aProducer/
    build.gradle
  consumer/
    build.gradle

Example 23.35.  settings.gradle

include 'consumer', 'aProducer'

Example 23.36.  aProducer/build.gradle

task action {
    println "Producing message:"
    System.setProperty('org.gradle.message', 'Watch the order of execution.')
}

Example 23.37.  consumer/build.gradle

task action {
    println "Consuming message: " +  System.getProperty('org.gradle.message')
}

Example 23.38. Output of gradle -q action

> gradle -q action
Producing message:
Consuming message: Watch the order of execution.

Now we take the air out of this hack. We simply switch to the consumer dir and execute the build.

Example 23.39. Output of gradle -q action

> gradle -q action
Consuming message: null

For Gradle the two action tasks are just not related. If you execute the build from the messages project Gradle executes them both because they have the same name and they are down the hierarchy. In the last example only one action was down the hierarchy and therefore it was the only task that got executed. We need something better than this hack.

23.6.1.2. Declaring Dependencies

Figure 23.8. Project layout

messages/
  settings.gradle
  consumer/
    build.gradle
  producer/
    build.gradle

Note: The code for this example can be found at samples/userguide/multiproject/dependencies/messagesWithDependencies/messages

Example 23.40.  settings.gradle

include 'consumer', 'producer'

Example 23.41.  consumer/build.gradle

dependsOn(':producer')

task action {
    println "Consuming message: " +  System.getProperty('org.gradle.message')
}

Example 23.42.  producer/build.gradle

task action {
    println "Producing message:"
    System.setProperty('org.gradle.message', 'Watch the order of execution.')
}

Example 23.43. Output of gradle -q action

> gradle -q action
Producing message:
Consuming message: Watch the order of execution.

Running this from the consumer directory gives:

Example 23.44. Output of gradle -q action

> gradle -q action
Producing message:
Consuming message: Watch the order of execution.

We have now declared that the consumer project has an execution dependency on the producer project. For Gradle declaring execution dependencies between projects is syntactic sugar. Under the hood Gradle creates task dependencies out of them. You can also create cross project tasks dependencies manually by using the absolute path of the tasks.

23.6.1.3. The Nature of Project Dependencies

Let's change the naming of our tasks and execute the build.

Example 23.45.  consumer/build.gradle

dependsOn(':producer')

task consume {
    println "Consuming message: " +  System.getProperty('org.gradle.message')
}

Example 23.46.  producer/build.gradle

task produce {
    println "Producing message:"
    System.setProperty('org.gradle.message', 'Watch the order of execution.')
}

Example 23.47. Output of gradle -q consume

> gradle -q consume
Consuming message: null

Uhps. Why does this not work? The dependsOn command is created for projects with a common lifecycle. Provided you have two Java projects were one depends on the other. If you trigger a compile for for the dependent project you don't want that all tasks of the other project get executed. Therefore a dependsOn creates dependencies between tasks with equal names. To deal with the scenario above you would do the following:

Example 23.48.  consumer/build.gradle

task consume(dependsOn: ':producer:produce') {
    println "Consuming message: " +  System.getProperty('org.gradle.message')
}

Example 23.49.  producer/build.gradle

task produce {
    println "Producing message:"
    System.setProperty('org.gradle.message', 'Watch the order of execution.')
}

Example 23.50. Output of gradle -q consume

> gradle -q consume
Producing message:
Consuming message: Watch the order of execution.

23.6.2. Configuration Time Dependencies

Let's have one more example with our producer-consumer build before we enter Java land. We add a property to the producer project and create now a configuration time dependency from consumer on producer.

Example 23.51.  consumer/build.gradle

key = 'unknown'
if (project(':producer').hasProperty('key')) {
    key = project(':producer').key
}
task consume(dependsOn: ':producer:produce') {
    println "Consuming message from key '$key': " +  System.getProperty(key)
}

Example 23.52.  producer/build.gradle

key = 'org.gradle.message'

task produce {
    println "Producing message:"
    System.setProperty(key, 'Watch the order of execution.')
}

Example 23.53. Output of gradle -q consume

> gradle -q consume
Producing message:
Consuming message from key 'unknown': null

The default evaluation order of the projects is alphanumeric (for the same nesting level). Therefore the consumer project is evaluated before the producer project and the key value of the producer is set after it is read by the consumer project. Gradle offers a solution for this.

Example 23.54.  consumer/build.gradle

evaluationDependsOn(':producer')

key = 'unknown'
if (project(':producer').hasProperty('key')) {
    key = project(':producer').key
}
task consume(dependsOn: ':producer:produce') {
    println "Consuming message from key '$key': " +  System.getProperty(key)
}

Example 23.55. Output of gradle -q consume

> gradle -q consume
Producing message:
Consuming message from key 'org.gradle.message': Watch the order of execution.

The command evaluationDependsOn triggers the evaluation of producer before consumer is evaluated. The example is a bit contrived for the sake of showing the mechanism. In this case there would be an easier solution by reading the key property at execution time.

Example 23.56.  consumer/build.gradle

task consume(dependsOn: ':producer:produce') {
    String key = project(':producer').key 
    println "Consuming message from key '$key': " +  System.getProperty(key)
}

Example 23.57. Output of gradle -q consume

> gradle -q consume
Producing message:
Consuming message from key 'org.gradle.message': Watch the order of execution.

Configuration dependencies are very different to execution dependencies. Configuration dependencies are between projects whereas execution dependencies are always resolved to task dependencies. Another difference is that always all projects are configured, even when you start the build from a subproject. The default configuration order is top down, which is usually what is needed.

On the same nesting level the configuration order depends on the alphanumeric position. The most common use case is to have multi-project builds that share a common lifecycle (e.g. all projects use the Java plugin). If you declare with dependsOn a execution dependency between different projects, the default behavior of this method is to create also a configuration dependency between the two projects. Therefore it is likely that you don't have to define configuration dependencies explicitly.

23.6.3. Real Life examples

Gradle's multi-project features are driven by real life use cases. The first example for describing such a use case, consists of two webapplication projects and a parent project that creates a distribution out of them. [31] For the example we use only one build script and do cross project configuration.

Figure 23.9. Project layout

webDist/
  settings.gradle
  build.gradle
  date/
    src/main/java/org/gradle/sample/DateServlet.java
  hello/
    src/main/java/org/gradle/sample/HelloServlet.java

Note: The code for this example can be found at samples/userguide/multiproject/dependencies/webDist

Example 23.58.  settings.gradle

include 'date', 'hello'

Example 23.59.  build.gradle

dependsOnChildren()

allprojects {
    usePlugin('java')
    group = 'org.gradle.sample'
    version = '1.0'
}

subprojects {
    usePlugin('war')
    repositories {
        mavenCentral()
    }
    dependencies {
        compile "javax.servlet:servlet-api:2.5"
    }
}

task explodedDist(dependsOn: libs) {
    File explodedDist = mkdir(buildDir, 'explodedDist')
    subprojects.each {project ->
        project.libs.archiveTasks.each {archiveTask ->
            ant.copy(file: archiveTask.archivePath, todir: explodedDist)
        }
    }
}

We have an interesting set of dependencies. Obviously the date and hello task have a configuration dependency on webDist, as all the build logic for the webapp projects is injected by webDist. The execution dependency is in the other direction, as webDist depends on the build artifacts of date and hello. There is even a third dependency. webDist has a configuration dependency on date and hello because it needs to know the archivePath. But it asks for this information at execution time. Therefore we have no circular dependency.

Such and other dependency patterns are daily bread in the problem space of multi-project builds. If a build system does not support such patterns, you either can't solve your problem or you need to do ugly hacks which are hard to maintain and massively afflict your productivity as a build master.

There is one more thing to note from the current example. We have used the command dependOnChildren(). It is a convenience method and calls the dependsOn method of the parent project for every child project (not every sub project). It declares a execution dependency of webDist on date and hello.

Another use case would be a situation where the subprojects have a configuration and execution dependency on the parent project. This is the case when the parent project does configuration injection into its subprojects, and additionally produces something at execution time that is needed by its child projects (e.g. code generation). In this case the parent project would call the childrenDependOnMe method to create an execution dependency for the child projects. We might add an example for this in a future version of the userguide.

23.7. Project Lib Dependencies

What if one projects needs the jar produced by another project in its compile path. And not just the jar but also the transitive dependencies of this jar. Obviously this is a very common use case for Java multi-project builds. As already mentioned in Section 20.2.4, “Project dependencies”, Gradle offers project dependencies for this.

Figure 23.10. Project layout

java/
  settings.gradle
  build.gradle
  api/
    src/main/java/org/gradle/sample/api/Person.java
    src/main/java/org/gradle/sample/apiImpl/PersonImpl.java
  services/
    personService/
      src/main/java/org/gradle/sample/services/PersonService.java
      src/test/java/org/gradle/sample/services/PersonServiceTest.java
  shared/
    src/main/java/org/gradle/sample/shared/Helper.java

Note: The code for this example can be found at samples/userguide/multiproject/dependencies/java

We have the projects shared, api and personService. personService has a lib dependency on the other two projects. api has a lib dependency on shared. [32]

Example 23.60.  settings.gradle

include 'api', 'shared', 'services:personService'

Example 23.61.  build.gradle

subprojects {
    usePlugin('java')
    group = 'org.gradle.sample'
    version = '1.0'
}

project(':api') {
    dependencies.compile project(':shared')
}

project(':services:personService') {
    dependencies {
        compile project(':shared'), project(':api')
        testCompile "junit:junit:3.8.2"
    }
}

All the build logic is in the build.gradle of the root project. [33] A lib dependency is a special form of an execution dependency. It causes the other project to be build first and adds the jar with the classes of the other project to the classpath. It also add the dependencies of the other project to the classpath. So you can enter the api folder and trigger a gradle compile. First shared is build and then api is build. Project dependencies enable partial multi-project builds.

If you come from Maven land you might be perfectly happy with this. If you come from Ivy land, you might expect some more fine grained control. Gradle offers this to you:

Example 23.62.  build.gradle

subprojects {
    usePlugin('java')
    group = 'org.gradle.sample'
    version = '1.0'
}

project(':api') {
    configurations {
        spi
    }
    dependencies {
        compile project(':shared')
    }
    task spiJar(type: Jar) {
        baseName = 'api-spi'
        confs = ['spi']
        fileSet() {
            include('org/gradle/sample/api/**')
        }
    }
}

project(':services:personService') {
    dependencies {
        compile project(':shared')
        compile project(':api') {
            dependencyConfiguration = 'spi'
        }
        testCompile "junit:junit:3.8.2", project(':api')
    }
}

The Java plugin adds per default a jar to your project libraries which contains all the classes. In this example we create an additional library containing only the interfaces of the api project. We assign this library to a new dependency configuration. For the person service we declare that the project should be compiled only against the api interfaces but tested with all classes from api.

23.8. Property and Method Inheritance

Properties and methods declared in a project are inherited to all its subprojects. This is an alternative to configuration injection. But we think that the model of inheritance does not reflect the problem space of multi-project builds very well. In a future edition of this userguide we might write more about this.

Method inheritance might be interesting to use as Gradle's Configuration Injection does not support methods yet (but will in a future release.).

You might be wondering why we have implemented a feature we obviously don't like that much. One reason is that it is offered by other tools and we want to have the check mark in a feature comparison :). And we like to offer our users a choice.

23.9. Summary

Writing this chapter was pretty exhausting and reading it might have a similar effect. Our final message for this chapter is that multi-project builds with Gradle are usually not difficult. There are six elements you need to remember: allproject, subprojects, dependsOn, childrenDependOnMe, dependOnChildren and project lib dependencies. [34] With those elements, and keeping in mind that Gradle has a distinct configuration and execution phase, you have already a lot of flexibility. But when you enter steep territory Gradle does not become an obstacle and usually accompanies and carries you to the top of the mountain.



[31] The real use case we had, was using http://lucene.apache.org/solr, where you need a separate war for each index your are accessing. That was one reason why we have created a distribution of webapps. The Resin servlet container allows us, to let such a distribution point to a base installation of the servlet container.

[32] services is also a project, but we use it just as a container. It has no build script and gets nothing injected by another build script.

[33] We do this here, as it makes the layout a bit easier. We usually put the project specific stuff into the buildscript of the respective projects.

[34] So we are well in the range of the 7 plus 2 Rule :)

Chapter 24. Organizing Build Logic

Gradle offers a variety of ways to organize your build logic. First of all you can put your build logic directly in the action closure of a task. If a couple of tasks share the same logic you can extract this logic into a method. If multiple projects of a multi-project build share some logic you can define this method in the parent project. If the build logic gets too complex for being properly modeled by methods you want have an OO Model. [35] Gradle makes this very easy. Just drop your classes in a certain folder and Gradle automatically compiles them and puts them in the classpath of your build script.

24.1. Build Sources

If you run Gradle, it checks for the existence of a folder called buildSrc. Just put your build source code in this folder and stick to the layout convention for a Java/Groovy project (see Table 15.1, “Default Directory Layout”). Gradle then automatically compiles and tests this code and puts it in the classpath of your build script. You don't need to provide any further instruction. For multi-project builds there can be only one buildSrc directory which has to be in the root project.

This is probably good enough for most of the cases. If you need more flexibility, you can provide a build.gradle and a settings.gradle file in the buildSrc folder. If you like, you can even have a multi-project build in there.

24.2. External dependencies

If your build script needs external libraries you can declare them in the settings.gradle file.

dependencies("commons-math:commons-math:1.1:jar")

You can pass any of the dependencies described in Section 20.2, “How to declare your dependencies” (except project dependencies). There is no need to provide a dependency configuration(e.g. compile). For multi-project builds dependencies declared in the settings.gradle file of the root project, are available to all build scripts of the sub-projects.

24.3. Ant Optional Dependencies

For reasons we don't fully understand yet, external dependencies are not picked up by Ant's optional tasks. But you can easily do it in another way. [36]

dependencies {
    addConfiguration('ftpAntTask')
    clientModule(['ftpAntTask'], ":ant-commons-net:1.7.0") {
        clientModule(":commons-net:1.4.1") {
            dependencies(":oro:2.0.8:jar")
        }
    }
}
createTask('ftp') {
    ant {
        taskdef(name: 'ftp',
                classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
                classpath: dependencies.antpath('ftpAntTask'))
        ftp(server: "ftp.apache.org", userid: "anonymous", password: "me@myorg.com") {
            fileset(dir: "htdocs/manual")
        }
    }
}

24.4. Summary

Gradle offers you a variety of ways of organizing your build logic. You can choose what is right for your domain and find the right balance between unnecessary indirections, and avoiding redundancy and a hard to maintain code base. It is our experience that even very complex custom build logic is rarely shared between different builds. Other build tools enforce a separation of this build logic into a separate project. Gradle spares you this unnecessary overhead and indirection.



[35] Which might range from a single class to something very complex)

[36] In fact, we think this is anyway the nicer solution. Only if your buildscript and Ant's optional task need the same library you would have to define it two times. In such a case it would be nice, if Ant's optional task would automatically pickup the classpath defined in the gradesettings.

Chapter 25. The Gradle Wrapper

Gradle is a new tool. You can't expect it to be installed on machines beyond your sphere of influence. An example are continuous integration server where Gradle is not installed and where you have no admin rights for the machine. Or what if you provide an open source project and you want to make it as easy as possible for your users to build it?

There is a simple and good news. Gradle provides a solution for this. It ships with a Wrapper task. [37] [38] You can create such a task in your build script.

createTask('wrapper', type: Wrapper).configure {
    gradleVersion = '0.1'
}

You usually explicitly execute this task (for example after a switch to a new version of Gradle). After such an execution you find the following new or updated files in your project folder (if the default configuration is used).

project-root
  - gradle-wrapper.jar
  - gradlew.exe
  - gradlew.bat

All these files should be submitted to your version control system. The gradlew command can be used exactly the same way as the gradle command.

25.1. Configuration

If you run Gradle with gradlew, Gradle checks if a Gradle distribution for the wrapper is available. If not it tries to download it, otherwise it delegates to the gradle command of this distribution with all the arguments passed originally to the gradlew command.

You can specify the download URL of the wrapper distribution. You can also specify where the wrapper should be stored and unpacked (either within the project or within the gradle user home dir). If the wrapper is run and there is local archive of the wrapper distribution Gradle tries to download it and stores it at the specified place. If there is no unpacked wrapper distribution Gradle unpacks the local archive of the wrapper distribution at the specified place.

All the configuration options have defaults except the version of the wrapper distribution. If you don't want any download to happen when your project is build via gradlew, simply add the Gradle distribution zip to your version control at the location specified by your wrapper configuration.

For the details on how to configure the wrapper, see Wrapper

If you build via the wrapper, any existing Gradle distribution installed on the machine is ignored.

25.2. Unix file permissions

The Wrapper task adds appropriate file permissions to allow the execution for the gradlew *NIX command. Subversion preserves this file permission. We are not sure how other version control systems deal with this. What should always work is to execute sh gradlew.

25.3. Environment variable

Some rather exotic use cases might occur when working with the Gradle Wrapper. For example the continuos integration server goes down during unzipping the Gradle distribution. As the distribution directory exists gradlew delegates to it but the distribution is corrupt. Or the zip-distribution was not properly downloaded. When you have no admin right on the continuous integration server to remove the corrupt files, Gradle offers a solution via environment variables.

Table 25.1. Gradle Wrapper Environment Variables

Variable Name Meaning
GRADLE_WRAPPER_ALWAYS_UNPACK If set to true, the distribution directory gets always deleted when gradlew is run and the distribution zip is freshly unpacked. If the zip is not there, Gradle tries to download it.
GRADLE_WRAPPER_ALWAYS_DOWNLOAD If set to true, the distribution directory and the distribution zip gets always deleted when gradlew is run and the distribution zip is freshly downloaded.


[37] If you download the Gradle source distribution or check out Gradle from SVN, you can build Gradle via the Gradle wrapper.

[38] Gradle itself is continuously built by Bamboo and Teamcity via this wrapper. See http://gradle.org/ci-server.html

Appendix A. Potential Traps

A.1. Groovy Script Variables

For Gradle users it is important to understand how Groovy deals with script variables. Groovy has to type of script variables. One with a local scope and one with a script wide scope.

Example A.1.  scope.groovy

String localScope1 = 'localScope1'
def localScope2 = 'localScope2'
scriptScope = 'scriptScope'

println localScope1
println localScope2
println scriptScope

closure = {
    println localScope1
    println localScope2
    println scriptScope
}

def method() {
    try {localScope1} catch(MissingPropertyException e) {println 'localScope1NotAvailable' }
    try {localScope2} catch(MissingPropertyException e) {println 'localScope2NotAvailable' }
    println scriptScope
}

closure.call()
method()

Example A.2. Output of gradle

> gradle 
localScope1
localScope2
scriptScope
localScope1
localScope2
scriptScope
localScope1NotAvailable
localScope2NotAvailable
scriptScope

Variables which are declared with a type modifier are visible within closures but not visible within methods. This is a heavily discussed behavior in the Groovy community. [39]

A.2. Configuration and Execution Phase

It is important to keep in mind that Gradle has a distinct configuration and execution phase (see Chapter 22, The Build Lifecycle).

Example A.3.  build.gradle

classesDir = new File('build/classes')
classesDir.mkdirs()
createTask('clean') {
    ant.delete(dir: 'build')
}
createTask('compile', dependsOn: 'clean') {
    if (!classesDir.isDirectory()) {
        println 'The class directory does not exist. I can not operate'
        // do something
    }
    // do something
}

Example A.4. Output of gradle -q compile

> gradle -q compile
The class directory does not exist. I can not operate

As the creation of the directory happens during the configuration phase, the clean task removes the directory during the execution phase.



[39] One of those discussions can be found here: http://www.nabble.com/script-scoping-question-td16034724.html

Appendix B. Gradle Command Line

The gradle command has the following usage:

gradle [option...] [task-name...]

The command-line options available for the gradle command are listed below:

-?, -h, --help

Shows a help message.

-C, --cache

Specifies how compiled build scripts should be cached. Possible values are: rebuild, off, on. Default value is on. See Section 10.6, “Caching” for more details.

-D, --system-prop

Sets a system property of the JVM, for example -Dmyprop=myvalue.

-I, --no-imports

Disable usage of default imports for build script files. See Section C.3, “Using Gradle without IDE support” for details.

-K, --default-import-file

Specifies the default import file.

-P, --project-prop

Sets a project property of the root project, for example -Pmyprop=myvalue.

-b, --build-file

Specifies the build file.

-c, --settings-file

Specifies the settings file.

-d, --debug

Log in debug mode (includes normal stacktrace). See Chapter 13, Logging.

-e, --embedded

Specify an embedded build script.

-f, --full-stacktrace

Print out the full (very verbose) stacktrace for any exceptions. See Chapter 13, Logging.

-g, --gradle-user-home

Specifies the gradle user home directory.

-i, --info

Set log level to info. See Chapter 13, Logging.

-l, --plugin-properties-file

Specifies the plugin properties file.

-n, --dependencies

Show list of all project dependencies.

-p, --project-dir

Specifies the start directory for Gradle. Defaults to current directory.

-q, --quiet

Log errors only. See Chapter 13, Logging.

-r, --properties

Show list of all available project properties.

-s, --stacktrace

Print out the stacktrace also for user exceptions (e.g. compile error). See Chapter 13, Logging.

-t, --tasks

Show list of all available tasks and their dependencies.

-u, --no-search-upwards

Don't search in parent folders for a settings.gradle file.

-v, --version

Prints version info.

The same information is printed to the console when you execute gradle -h.

Appendix C. Existing IDE Support and how to cope without it

C.1. IntelliJ

Gradle has been mainly developed with Idea IntelliJ and its very good Groovy plugin. Gradle's build script [40] has also been developed with the support of this IDE. IntelliJ allows you to define any filepattern to be interpreted as a Groovy script. In the case of Gradle you can define such a pattern for build.gradle and settings.gradle. This will already help very much. What is missing is the classpath to the Gradle binaries to offer content assistance for the Gradle classes. You might add the Gradle jar (which you can find in your distribution) to your project's classpath. It does not really belong there, but if you do this you have a fantastic IDE support for developing Gradle scripts. Of course if you use additional libraries for your build scripts they would further pollute your project classpath.

We hope that in the future *.gradle files get special treatment by IntelliJ and you will be able to define a specific classpath for them.

C.2. Eclipse

There is a Groovy plugin for eclipse. We don't know in what state it is and how it would support Gradle. In the next edition of this userguide we can hopefully write more about this.

C.3. Using Gradle without IDE support

What we can do for you is to spare you typing things like throw new org.gradle.api.tasks.StopExecutionException() and just type throw new StopExecutionException() instead. We do this by automatically adding a set of import statements to the Gradle scripts before Gradle executes them. This set is defined by a properties file gradle-imports in the Gradle distribution. It has the following content.

Figure C.1. gradle-imports

import org.gradle.*
import org.gradle.util.*
import org.gradle.api.*
import org.gradle.api.dependencies.*
import org.gradle.api.logging.*
import org.gradle.api.execution.*
import org.gradle.api.initialization.*
import org.gradle.api.invocation.*
import org.gradle.api.plugins.*
import org.gradle.api.tasks.*
import org.gradle.api.tasks.bundling.*
import org.gradle.api.tasks.compile.*
import org.gradle.api.tasks.javadoc.*
import org.gradle.api.tasks.testing.*
import org.gradle.api.tasks.util.*
import org.gradle.api.tasks.wrapper.*

You can define a project specific set of imports to be added to your build scripts. Just place a file called gradle-imports in your root project directory. If you start Gradle with the {-I} option, the imports defined in the Gradle distribution are disabled. The imports defined in your project directory are always used.



[40] Gradle is built with Gradle