Chapter 2
The Gradle Core Tutorial

If you execute a build, Gradle normally looks for a file called build.gradle in the current directory (There are command line switches to change this behavior. See Appendix C). We call the build.gradle a build script. Although strictly speaking it is a build configuration script, as we see later. In Gradle the location of the build script file defines a project. The name of the directory containing the build script is the name of the project.

2.1 Hello World

In Gradle everything revolves around tasks. The tasks for your build are defined in the build script. To try this out, create the following build script named build.gradle and enter with your shell into the containing directory.

  createTask('hello') {
      println 'Hello world!'
  }

Now execute the build script1 2 :

  >gradle -q -bhello.gradle 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, like javac or copy, task. So if 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.

2.2 Build scripts are code

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

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

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

or

  createTask('count') {
      4.times { print "$it " }
  }

  >gradle -q -bcount.gradle count
  0 1 2 3

2.3 Task dependencies

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

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

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

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

  createTask('taskX', dependsOn: 'taskY') {
      println 'taskX'
  }
  createTask('taskY') {
      println 'taskY'
  }

  >gradle -q -blazyDependsOn.gradle taskX
  taskY
  taskX

The dependency of targetX to targetY is declared before targetY is created. This is very important for multi-project builds.

2.4 Dynamic tasks

The power of Groovy can not only be used inside the tasks. You can use it for example to dynamically create tasks.

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

  >gradle -q -bdynamic.gradle task_1
  I'm task number 1

2.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.

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

  >gradle -q -bdynamicDepends.gradle 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.

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

  >gradle -q -bhelloEnhanced.gradle hello
  Hello Venus
  Hello Earth
  Hello Mars

The calls doFirst and doLast can be executed multiple times. What they do is to add an action to the beginning or the end of the tasks actions list.

2.6 Shortcut notations

There is a convenient notation for accessing existing tasks.

  createTask('hello') {
      println 'Hello world!'
  }
  hello.doLast {
      println 'Hello again!'
  }

  >gradle -q -bhelloWithShortCut.gradle 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).

2.7 Ant

Let’s talk a little bit about Gradles 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()3 .

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:

  createTask('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]}"
      }
  }
  
  >gradle -q -bantChecksum.gradle 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 Groovys AntBuilder. The AntBuilder is used the following way:

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

2.8 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.

  createTask('checksum') {
      fileList('antChecksumFiles').each { File file ->
          ant.checksum(file: file.canonicalPath, property: file.name)
          println "$file.name Checksum: ${ant.antProject.properties[file.name]}"
      }
  }
  
  createTask('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
  }

  >gradle -q -bantChecksumWithMethod.gradle 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 15.

2.9 Configure By DAG

As we describe in full detail later (See chapter 13) 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.

  version = null
  configureByDag = {dag ->
      if (dag.hasTask(':release')) {
          version = '1.0'
      } else {
          version = '1.0-SNAPSHOT'
      }
  }
  createTask('distribution') {
      println "We build the zip with version=$version"
  }
  createTask('release', dependsOn: 'distribution') {
      println 'We release now'
  }

  >gradle -q -bconfigByDag.gradle 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).

2.10 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 7 and when we look at the Java Plugin in chapter 9.