The Groovy DSL

A build.gradle file is not a configuration format with a schema: it is a Groovy script that Gradle compiles and runs when the build starts. Everything that looks like a special syntax is a method call of Groovy with a closure after it. This lesson reads a build script line by line and runs a task written in the same style.

A build script

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'java' } group = 'com.example' version = '1.0.0' repositories { mavenLocal() } tasks.register('summary') { description = 'Prints the coordinates of the project' group = 'help' def label = "${project.group}:${project.name}:${project.version}" doLast { println label } }

What Gradle does with it

The -q flag asks for the quiet log: Gradle prints the output of the task and nothing else. Without it the task lines and the build result would appear around this one line.

gradle -q summary --console=plain --offline --no-daemon

com.example:shop:1.0.0

The task is registered, not run: tasks.register is lazy, so the body of the closure runs when Gradle decides the task has to run. Naming it on the command line is that decision.

gradle help --task summary --console=plain --offline --no-daemon


> Task :help
Detailed task information for summary

Path
     :summary (registered in build file 'build.gradle')

Type
     Task (org.gradle.api.Task)

Options
     --rerun Causes the task to be re-run even if up-to-date.

Description
     Prints the coordinates of the project

Group
     help

BUILD SUCCESSFUL in 11s
1 actionable task: 1 executed

Blocks, methods and properties

The Groovy language brings three things a build script uses all the time: optional parentheses, closures as the last argument of a method, and def for a local variable. None of them belongs to Gradle; a groovy command runs the same code.

Strings and values

A single-quoted string is a plain String. A double-quoted one is a GString: ${...} inside it is evaluated when the string is built, so label above is computed once, when the script runs, and printed later. That is the difference between '${project.name}', which prints the dollar expression, and "${project.name}", which prints the name.

A GString is not a String, and a map key or a comparison that needs one will fail on it. When a value is used as a path or a name, write label.toString() or build it with String.format.

Related

Автор статьи: Arthur Isaev