ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 01.01.2026
Просмотров: 1145
Скачиваний: 0
14.2.1. Checking for project properties
You can access a project property in your build script simply by using its 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.
14.3. Configuring the project using an external build script
You can configure the current project using an external build script. All of the Gradle build language is available in the external script. You can even apply other scripts from the external script.
Example 14.3. Configuring the project using an external build script
build.gradle
apply from: 'other.gradle'
other.gradle
println "configuring $project" task hello << {
println 'hello from other script'
}
Output of gradle -q hello
> gradle -q hello
configuring root project 'configureProjectUsingScript' hello from other script
14.4. Configuring arbitrary objects
You can configure arbitrary objects in the following very readable way.
Page 74 of 343
Example 14.4. Configuring arbitrary objects build.gradle
task configure << {
pos = configure(new java.text.FieldPosition(10)) { beginIndex = 1
endIndex = 5
}
println pos.beginIndex println pos.endIndex
}
Output of gradle -q configure
> gradle -q configure 1 5
14.5. Configuring arbitrary objects using an external script
You can also configure arbitrary objects using an external script.
Example 14.5. Configuring arbitrary objects using a script
build.gradle
task configure << {
pos = new java.text.FieldPosition(10) // Apply the script
apply from: 'other.gradle', to: pos println pos.beginIndex
println pos.endIndex
}
other.gradle
beginIndex = 1; endIndex = 5;
Output of gradle -q configure
> gradle -q configure 1 5
Page 75 of 343
14.6. Caching
To improve responsiveness Gradle caches all compiled scripts by default. This includes all build scripts, initialization scripts, and other scripts. The first time you run a build for a project, Gradle creates a .gradle directory in which it puts the compiled script. The next time you run this build, Gradle uses the compiled script, if the script has not changed since it was compiled. Otherwise the script gets compiled and the new version is stored in the cache. If you run Gradle with the --recompile-scripts option, the cached script is discarded and the script is compiled and stored in the cache. This way you can force Gradle to rebuild the cache.
[5] Teamcity or Bamboo are for example CI servers which offer this functionality.
Page 76 of 343
15
The Build Environment
15.1. Configuring the build environment via gradle.properties
Gradle provides several options that make it easy to configure the Java process that will be used to execute your build. While it's possible to configure these in your local environment vi GRADLE_OPTS or JAVA_OPTS, certain settings like jvm memory settings, java home, daemon on/off can be more useful if they can versioned with the project in your VCS so that the entire team can work with consistent environment. Setting up a consistent environment for your build is as simple as placing those settings into a gradle.properties file. The configuration is applied in following order (in case an option is configured in multiple locations the last one wins):
from gradle.properties located in project build dir.
from gradle.properties located in gradle user home.
from system properties, e.g. when -Dsome.property is used in the command line.
The following properties can be used to configure the Gradle build environment:
org.gradle.daemon
When set to true the Gradle daemon is to run the build. For local developer builds this is our favorite property. The developer environment is optimized for speed and feedback so we nearly always run Gradle jobs with the daemon. We don't run CI builds with the daemon (i.e a long running process) as the CI environment is optimized for consistency and reliability.
org.gradle.java.home
Specifies the java home for the Gradle build process. The value can be set to either jdk or j location, however, depending on what does your build do, jdk is safer. Reasonable default is used if the setting is unspecified.
org.gradle.jvmargs
Specifies the jvmargs used for the daemon process. The setting is particularly useful for tweaking memory settings. At the moment the default settings are pretty generous with regards to memory.
Page 77 of 343
15.1.1. Forked java processes
Many settings (like the java version and maximum heap size) can only be specified when launching a new JVM for the build process. This means that Gradle must launch a separate JVM process to execute the build after parsing the various gradle.properties files. When running with the daemon, a JVM with the correct parameters is started once and reused for each daemon build execution. When Gradle is executed without the daemon, then a new JVM must be launched for every build execution, unless the JVM launched by the Gradle start script happens to have the same parameters.
This launching of an extra JVM on every build execution is quite expensive, which is why we highly recommend that you use the Gradle Daemon if you are specifying org.gradle.java.home or or
. See Chapter 13, The Gradle Daemon for more details.
15.2. Accessing the web via a proxy
Configuring an HTTP proxy (for example for downloading dependencies) is done via standard JVM system properties. These properties can be set directly in the build script; for example System.set for the proxy host. Alternatively, the properties can be specified in a gradle.properties file, either in the build's root directory or in the Gradle home directory.
Example 15.1. Configuring an HTTP proxy
gradle.properties
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
There are separate settings for HTTPS.
Example 15.2. Configuring an HTTPS proxy
gradle.properties
systemProp.https.proxyHost=www.somehost.org
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=userid
systemProp.https.proxyPassword=password systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost
We could not find a good overview for all possible proxy settings. One place to look are the constants in a file from the Ant project. Here a link to the Subversion view. The other is a Networking Properties page from the JDK docs. If anyone knows a better overview, please let us know via the mailing list.
Page 78 of 343
15.2.1. NTLM Authentication
If your proxy requires NTLM authentication, you may need to provide the authentication domain as well as the username and password. There are 2 ways that you can provide the domain for authenticating to a NTLM proxy:
Set the http.proxyUser system property to a value like domain/username. Provide the authentication domain via the http.auth.ntlm.domain system property.
Page 79 of 343
16
Writing Build Scripts
This chapter looks at some of the details of writing a build script.
16.1. The Gradle build language
Gradle provides a domain specific language, or DSL, for describing builds. This build language is based on Groovy, with some additions to make it easier to describe a build.
16.2. The Project API
In the tutorial in Chapter 7, Java Quickstart we used, for example, the apply() method. Where does this method come from? We said earlier that the build script defines a project in Gradle. For each project in the build creates an instance of type Project and associates this Project object with the build script. As the build script executes, it configures 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 thename property of the
Project object.
Getting help writing
build scripts
Don't forget that your build script is simply Groovy code that drives the Gradle API. And the Project interface is your starting point for accessing everything in the Gradle API. So, if you're wondering what 'tags' are available in your build script, you can start with the documentation for the Project interface.
Page 80 of 343
Example 16.1. Accessing property of the Project object
build.gradle
println name println project.name
Output of gradle -q check
> gradle -q check projectApi projectApi
Both println statements print out the same property. The first uses auto-delegation to the
Project object, for properties not defined in the build script. The other statement uses the projec property available to any build script, which returns 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.
16.2.1. Standard project properties
The Project object provides some standard properties, which are available in your build script. The following table lists a few of the commonly used ones.
Table 16.1. Project Properties
Name |
Type |
Default Value |
project |
Project |
The Project instance |
name |
String |
The name of the project directory. |
path |
String |
The absolute path of the project. |
description |
String |
A description for the project. |
projectDir |
File |
The directory containing the build script. |
buildDir |
File |
projectDir/build |
group |
Object |
unspecified |
version |
Object |
unspecified |
ant |
AntBuilder |
An AntBuilder instance |
16.3. The Script API
When Gradle executes a script, it compiles the script into a class which implements Script. This means that all of the properties and methods declared by the Script interface are available in your script.
Page 81 of 343
16.4. Declaring variables
There are two kinds of variables that can be declared in a build script: local variables and extra properties.
16.4.1. Local variables
Local variables are declared with the def keyword. They are only visible in the scope where they have been declared. Local variables are a feature of the underlying Groovy language.
Example 16.2. Using local variables
build.gradle
def dest = "dest"
task copy(type: Copy) { from "source"
into dest
}
16.4.2. Extra properties
All enhanced objects in Gradle's domain model can hold extra user-defined properties. Thi includes, but is not limited to, projects, tasks, and source sets. Extra properties can be added, read and set via the owning object'sext property.
Example 16.3. Using extra properties
build.gradle
apply plugin: "java"
sourceSets.all { ext.purpose = null }
sourceSets { main {
purpose = "production"
}
test {
purpose = "test"
}
plugin {
ext.purpose = "production"
}
}
task printProductionSourceDirs << {
sourceSets.matching { it.purpose == "production" }.each { println it.java.
}
In this example, a property named purpose is added to all source sets by setting ext.purpose to null (null is a permissible value). Once the property has been added, it can be read and set
Page 82 of 343
like a predefined property. Alternatively, ext. can be used as well.
By requiring special syntax for adding a property, Gradle can fail fast when an attempt is made to set a (predefined or extra) property but the property is misspelled or does not exist. [6] Extra properties can be accessed from anywhere their owning object can be accessed, giving them a wider scope than local variables. Extra properties on a parent project are visible from subprojects.
For further details on extra properties and their API, see ExtraPropertiesExtension.
16.5. Some Groovy basics
Groovy provides plenty of features for creating DSLs, and the Gradle build language takes advantage of these. Understanding how the build language works will help you when you write your build script, and in particular, when you start to write customs plugins and tasks.
16.5.1. Groovy JDK
Groovy adds lots of useful methods to JVM classes. For example, Iterable gets an each method, which iterates over the elements of the Iterable:
Example 16.4. Groovy JDK methods
build.gradle
// Iterable gets an each() method configurations.runtime.each { File f -> println f }
Have a look at http://groovy.codehaus.org/groovy-jdk/ for more details.
16.5.2. Property accessors
Groovy automatically converts a property reference into a call to the appropriate getter or setter method.
Example 16.5. Property accessors
build.gradle
//Using a getter method println project.buildDir
println getProject().getBuildDir()
//Using a setter method project.buildDir = 'target' getProject().setBuildDir('target')
16.5.3. Optional parentheses on method calls
Parentheses are optional for method calls.
Page 83 of 343