gradle user guide

chap4
4.6. JVM options
GRADLE_OPTS
JAVA_OPTS


chap5
--no-daemon


chap6
task hello {
doLast { println 'Hello world!' }
}
gradle -q hello


task hello << {
println 'Hello world!'
}


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


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


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


4.times {
counter ->
task "task$counter" << {
println "I'm task number $counter"
}
}
task0.dependsOn task2, task3


task hello << {
println 'Hello Earth'
}
hello.doFirst {
println 'Hello Venus'
}
hello.doLast {
println 'Hello Mars'
}
hello << {
println 'Hello Jupiter'
}


task hello << {
println 'Hello world!'
}
hello.doLast {
println "Greetings from the $hello.name task."
}


task myTask {
ext.myProperty = "myValue"
}
task printTaskProperties << {
println myTask.myProperty
}


gradle -q printTaskProperties


6.10. Using Ant Tasks


defaultTasks 'clean', 'run'
task clean << {
println 'Default Cleaning!'
}
task run << {
println 'Default Running!'
}
task other << {
println "I'm not a default task!"
}


Example 6.16. Different outcomes of build depending on chosen tasks
build.gradle
task distribution << {
println "We build the zip with version=$version"
}
task release(dependsOn: 'distribution') << {
println 'We release now'
}
gradle.taskGraph.whenReady {
taskGraph ->
if (taskGraph.hasTask(release)) {
version = '1.0'
} else {
version = '1.0-SNAPSHOT'
}
}




chap7
apply plugin: 'java'


samples/java/quickstart


src/main/java
src/test/java
src/main/resources
src/test/resources
build
build/libs


gradle build
:compileJava
:processResources
:classes
:jar
:assemble
:compileTestJava
:processTestResources
:testClasses
:test
:check
:build


clean
Deletes the build directory, removing all built files.
assemble
Compiles and jars your code, but does not run the unit tests. Other plugins add more artifacts to this task.
For example, if you use the War plugin, this task will also build the WAR file for your project.
check
Compiles and tests your code. Other plugins add more checks to this task. For example, if you use the checkstyle
plugin, this task will also run Checkstyle against your source code.


repositories {
mavenCentral()
}


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


Example 7.5. Customization of MANIFEST.MF
build.gradle
sourceCompatibility = 1.5
version = '1.0'
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Quickstart',
'Implementation-Version': version
}
}


Example 7.6. Adding a test system property
build.gradle
test {
systemProperties 'property': 'value'
}


Example 7.7. Publishing the JAR file
build.gradle
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}


apply plugin: 'eclipse'


gradle eclipse


samples/java/multiproject


Build layout
multiproject/
api/
services/webservice/
shared/
services/shared/


Example 7.11. Multi-project build - settings.gradle file
settings.gradle
include "shared", "api", "services:webservice", "services:shared"


subprojects {
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.11'
}
version = '1.0'
jar {
manifest.attributes provider: 'gradle'
}
}


Example 7.13. Multi-project build - dependencies between projects
api/build.gradle
dependencies {
compile project(':shared')
}


Example 7.14. Multi-project build - distribution file
api/build.gradle
task dist(type: Zip) {
dependsOn spiJar
from 'src/dist'
into('libs') {
from spiJar.archivePath
from configurations.runtime
}
}
artifacts {
archives dist
}


samples/java




chap8
Example 8.1. Declaring dependencies
build.gradle
apply plugin: 'java'
repositories { mavenCentral() }
dependencies {
compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.7.Final'
testCompile group: 'junit', name: 'junit', version: '4.+'
}


8.3. Dependency configurations
compile
The dependencies required to compile the production source of the project.
runtime
The dependencies required by the production classes at runtime. By default, also includes the compile time
dependencies.
testCompile
The dependencies required to compile the test source of the project. By default, also includes the compiled
production classes and the compile time dependencies.
testRuntime
The dependencies required to run the tests. By default, also includes the compile, runtime and test compile
dependencies.


dependencies {
compile 'org.hibernate:hibernate-core:3.6.7.Final'
}


repositories {
mavenCentral()
}




repositories {
maven {
url "http://repo.mycompany.com/maven2"
}
}


repositories {
ivy {
url "http://repo.mycompany.com/repo"
}
}


repositories {
ivy {
// URL can refer to a local directory
url "../local-repo"
}
}


Example 8.8. Publishing to an Ivy repository
build.gradle
uploadArchives {
repositories {
ivy {
credentials {
username "username"
password "pw"
}
url "http://repo.mycompany.com"
}
}
}


Example 8.9. Publishing to a Maven repository
build.gradle
apply plugin: 'maven'
uploadArchives {
repositories {
mavenDeployer {
repository(url: "file://localhost/tmp/myRepo/")
}
}
}




chap9
apply plugin: 'eclipse'
apply plugin: 'groovy'
repositories { mavenCentral() }
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.6'
testCompile 'junit:junit:4.11'
}


chap11
Example 11.1. Executing multiple tasks
build.gradle
task compile << {
println 'compiling source'
}
task compileTest(dependsOn: compile) << {
println 'compiling unit tests'
}
task test(dependsOn: [compile, compileTest]) << {
println 'running unit tests'
}
task dist(dependsOn: [compile, test]) << {
println 'building the distribution'
}
gradle dist test


gradle dist -x test


--continue


Example 11.3. Abbreviated task name
Output of gradle di
> gradle di
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist


gradle compTest or even gradle cT
Output of gradle cT
> gradle cT
:compile
compiling source
:compileTest


Example 11.5. Selecting the project using a build file
subdir/myproject.gradle
task hello << {
println "using build file '$buildFile.name' in '$buildFile.parentFile.name'."
}
gradle -q -b subdir/myproject.gradle hello


Example 11.6. Selecting the project using project directory
gradle -q -p subdir hello


Example 11.7. Obtaining information about projects
gradle -q projects


Example 11.8. Providing a description for a project
build.gradle
description = 'The shared API for the application'


Example 11.9. Obtaining information about tasks
gradle -q tasks


Example 11.10. Changing the content of the task report
build.gradle
dists {
description = 'Builds the distribution'
group = '


Example 11.11. Obtaining more information about tasks
gradle -q tasks --all


Example 11.12. Obtaining detailed help for tasks
gradle -q help --task libs


gradle dependencies
Example 11.13. Obtaining information about dependencies
gradle -q dependencies api:dependencies webapp:dependencies


Example 11.14. Filtering dependency report by configuration
gradle -q api:dependencies --configuration testCompile


Example 11.15. Getting the insight into a particular dependency
gradle -q webapp:dependencyInsight --dependency groovy --configuration compile


gradle properties
Example 11.16. Information about properties
gradle -q api:properties


--profile 
command line option will record some useful timing information while your build is running
and write a report to the build/reports/profile directory.
Builds which utilize a buildSrc directory will generate a second profile report for buildSrc in the buildSrc/build
directory.


gradle -m clean compile




chap12
gradle --gui




chap13
domain specific language, or DSL


println name
println project.name


Table 13.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


implements Script


Example 13.2. Using local variables
build.gradle
def dest = "dest"
task copy(type: Copy) {
from "source"
into dest
}


All enhanced objects in Gradle's domain model can hold extra user-defined properties. This includes, but is not
limited to, projects, tasks, and source sets.


Example 13.3. Using extra properties
build.gradle
apply plugin: "java"
ext {
springVersion = "3.1.0.RELEASE"
emailNotification = "build@master.org"
}
sourceSets.all { ext.purpose = null }
sourceSets {
main {
purpose = "production"
}
test {
purpose = "test"
}
plugin {
purpose = "production"
}
}
task printProperties << {
println springVersion
println emailNotification
sourceSets.matching { it.purpose == "production" }.each { println it.name }
}


Example 13.4. Groovy JDK methods
build.gradle
// Iterable gets an each() method
configurations.runtime.each { File f -> println f }


Example 13.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')


Example 13.6. Method call without parentheses
build.gradle
test.systemProperty 'some.prop', 'value'
test.systemProperty('some.prop', 'value')


Example 13.7. List and map literals
build.gradle
// List literal
test.includes = ['org/gradle/api/**', 'org/gradle/internal/**']
List<String> list = new ArrayList<String>()
list.add('org/gradle/api/**')
list.add('org/gradle/internal/**')
test.includes = list
// Map literal.
Map<String, String> map = [key1:'value1', key2: 'value2']
// Groovy will coerce named arguments
// into a single map argument
apply plugin: 'java'


Example 13.8. Closure as method parameter
build.gradle
repositories {
println "in a closure"
}
repositories() { println "in a closure" }
repositories({ println "in a closure" })


Example 13.9. Closure delegates
build.gradle
dependencies {
assert delegate == project.dependencies
testCompile('junit:junit:4.11')
delegate.testCompile('junit:junit:4.11')
}




chap14
Example 14.1. Directory creation with mkdir
build.gradle
def classesDir = new File('build/classes')
task resources << {
classesDir.mkdirs()
// do something
}
task compile(dependsOn: 'resources') << {
if (classesDir.isDirectory()) {
println 'The class directory exists. I can operate'
}
// do something
}
gradle -q compile


The -D option of the gradle command has the same effect as
the -D option of the java command.


GRADLE_USER_HOME


-P


ORG_GRADLE_PROJECT_prop=somevalue


systemProp.


Example 14.2. Setting properties with a gradle.properties file
gradle.properties
gradlePropertiesProp=gradlePropertiesValue
sysProp=shouldBeOverWrittenBySysProp
envProjectProp=shouldBeOverWrittenByEnvProp
systemProp.system=systemValue
build.gradle
task printProps << {
println commandLineProjectProp
println gradlePropertiesProp
println systemProjectProp
println envProjectProp
println System.properties['system']
}
> gradle -q -PcommandLineProjectProp=commandLineProjectPropValue -Dorg.gradle.project.systemProjectProp=commandLineProjectPropValue
gradlePropertiesValue
systemPropertyValue
envPropertyValue
systemValue


hasProperty('propertyName')


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


Example 14.4. Configuring arbitrary objects
build.gradle
task configure << {
def 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




Example 14.5. Configuring arbitrary objects using a script
build.gradle
task configure << {
def pos = new java.text.FieldPosition(10)
// Apply the script
apply from: 'other.gradle', to: pos
println pos.beginIndex
println pos.endIndex
}
other.gradle
Output of gradle -q configure
> gradle -q configure
1
5


--recompile-scripts




chap15
Gradle supports
enhanced tasks, which are tasks that have their own properties and methods.


task(hello) << {
println "hello"
}
task(copy, type: Copy) {
from(file('srcDir'))
into(buildDir)
}


Example 15.2. Defining tasks - using strings for task names
build.gradle
task('hello') << {
println "hello"
}
task('copy', type: Copy) {
from(file('srcDir'))
into(buildDir)
}
TaskContainer
Example 15.3. Defining tasks with alternative syntax
build.gradle
tasks.create(name: 'hello') << {
println "hello"
}
tasks.create(name: 'copy', type: Copy) {
from(file('srcDir'))
into(buildDir)
}


Example 15.4. Accessing tasks as properties
build.gradle
task hello
println hello.name
println project.hello.name


Example 15.5. Accessing tasks via tasks collection
build.gradle
task hello
println tasks.hello.name
println tasks['hello'].name


Example 15.6. Accessing tasks by path
build.gradle
project(':projectA') {
task hello
}
task hello
println tasks.getByPath('hello').path
println tasks.getByPath(':hello').path
println tasks.getByPath('projectA:hello').path
println tasks.getByPath(':projectA:hello').path


Example 15.7. Creating a copy task
build.gradle
task myCopy(type: Copy)


Example 15.8. Configuring a task - various ways
build.gradle
Copy myCopy = task(myCopy, type: Copy)
myCopy.from 'resources'
myCopy.into 'target'
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')


Example 15.9. Configuring a task - with closure
build.gradle
task myCopy(type: Copy)
myCopy {
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}


Line 3 of the example is just a shortcut for the tasks.getByName() method. if you pass a closure to the getByName() method, this closure is applied to configure
the task, not when the task executes.


Example 15.10. Defining a task with closure
build.gradle
task copy(type: Copy) {
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}


Example 15.11. Adding dependency on task from another project
build.gradle
project('projectA') {
task taskX(dependsOn: ':projectB:taskY') << {
println 'taskX'
}
}
project('projectB') {
task taskY << {
println 'taskY'
}
}


Example 15.12. Adding dependency using task object
build.gradle
task taskX << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
taskX.dependsOn taskY


Example 15.13. Adding dependency using closure
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 15.14. Adding a 'must run after' task ordering
build.gradle
task taskX << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
taskY.mustRunAfter taskX


Example 15.15. Adding a 'should run after' task ordering
build.gradle
task taskX << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
taskY.shouldRunAfter taskX


Example 15.17. A 'should run after' task ordering is ignored if it introduces an ordering cycle
build.gradle
task taskX << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
task taskZ << {
println 'taskZ'
}
taskX.dependsOn taskY
taskY.dependsOn taskZ
taskZ.shouldRunAfter taskX


Example 15.18. Adding a description to a task
build.gradle
task copy(type: Copy) {
description 'Copies the resource directory to the target directory.'
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}


Example 15.19. Overwriting a task
build.gradle
task copy(type: Copy)
task copy(overwrite: true) << {
println('I am the new one.')
}


Example 15.20. Skipping a task using a predicate
build.gradle
task hello << {
println 'hello world'
}
hello.onlyIf {
!project.hasProperty('skipHello')
}
Output of gradle hello -PskipHello


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.


Example 15.22. Enabling and disabling tasks
build.gradle
task disableMe << {
println 'This should not be printed if the task is disabled.'
}
disableMe.enabled = false


Example 15.24. Declaring the inputs and outputs of a task
build.gradle
task transform {
ext.srcFile = file('mountains.xml')
ext.destDir = new File(buildDir, 'generated')
inputs.file srcFile
outputs.dir destDir
doLast {
println "Transforming source file."
destDir.mkdirs()
def mountains = new XmlParser().parse(srcFile)
mountains.mountain.each {
mountain ->
def name = mountain.name[0].text()
def height = mountain.height[0].text()
def destFile = new File(destDir, "${name}.txt")
destFile.text = "$name -> ${height}\n"
}
}
}


The task's inputs property is of type TaskInputs. The task's outputs property is of type TaskOutputs


TaskOutputs.upToDateWhen()


Example 15.25. Task rule
build.gradle
tasks.addRule("Pattern: ping<ID>") {
String taskName ->
if (taskName.startsWith("ping")) {
task(taskName) << {
println "Pinging: " + (taskName - 'ping')
}
}
}
Output of gradle -q pingServer1
> gradle -q pingServer1
Pinging: Server1


Example 15.26. Dependency on rule based tasks
build.gradle
tasks.addRule("Pattern: ping<ID>") {
String taskName ->
if (taskName.startsWith("ping")) {
task(taskName) << {
println "Pinging: " + (taskName - 'ping')
}
}
}
task groupPing {
dependsOn pingServer1, pingServer2
}
Output of gradle -q groupPing
> gradle -q groupPing
Pinging: Server1
Pinging: Server2


Example 15.27. Adding a task finalizer
build.gradle
task taskX << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
taskX.finalizedBy taskY


Example 15.28. Task finalizer for a failing task
build.gradle
task taskX << {
println 'taskX'
throw new RuntimeException()
}
task taskY << {
println 'taskY'
}
taskX.finalizedBy taskY






chap16
Example 16.1. Locating files
build.gradle
// Using a relative path
File configFile = file('src/config.xml')
// Using an absolute path
configFile = file(configFile.absolutePath)
// Using a File object with a relative path
configFile = file(new File('src/config.xml'))


Example 16.2. Creating a file collection
build.gradle
FileCollection collection = files('src/file1.txt',new File('src/file2.txt'),['src/file3.txt', 'src/file4.txt'])


Example 16.3. Using a file collection
build.gradle
// Iterate over the files in the collection
collection.each {File file ->
println file.name
}
// Convert the collection to various types
Set set = collection.files
Set set2 = collection as Set
List list = collection as List
String path = collection.asPath
File file = collection.singleFile
File file2 = collection as File
// Add and subtract collections
def union = collection + files('src/file3.txt')
def different = collection - files('src/file3.txt')


Example 16.4. Implementing a file collection
build.gradle
task list << {
File srcDir
// Create a file collection using a closure
collection = files { srcDir.listFiles() }
srcDir = file('src')
println "Contents of $srcDir.name"
collection.collect { relativePath(it) }.sort().each { println it }
srcDir = file('src2')
println "Contents of $srcDir.name"
collection.collect { relativePath(it) }.sort().each { println it }
}


Some other types of things you can pass to files():FileCollection
These are flattened and the contents included in the file collection.
Task
The output files of the task are included in the file collection.
TaskOutputs
The output files of the TaskOutputs are included in the file collection.


Example 16.5. Creating a file tree
build.gradle
// Create a file tree with a base directory
FileTree tree = fileTree(dir: 'src/main')
// Add include and exclude patterns to the tree
tree.include '**/*.java'
tree.exclude '**/Abstract*'
// Create a tree using path
tree = fileTree('src').include('**/*.java')
// Create a tree using closure
tree = fileTree('src') {
include '**/*.java'
}
// Create a tree using a map
tree = fileTree(dir: 'src', include: '**/*.java')
tree = fileTree(dir: 'src', includes: ['**/*.java', '**/*.xml'])
tree = fileTree(dir: 'src', include: '**/*.java', exclude: '**/*test*/**')


Example 16.6. Using a file tree
build.gradle
// Iterate over the contents of a tree
tree.each {File file ->
println file
}
// Filter a tree
FileTree filtered = tree.matching {
include 'org/gradle/api/**'
}
// Add trees together
FileTree sum = tree + fileTree(dir: 'src/test')
// Visit the elements of the tree
tree.visit {element ->
println "$element.relativePath => $element.file"
}


Example 16.7. Using an archive as a file tree
build.gradle
// Create a ZIP file tree using path
FileTree zip = zipTree('someFile.zip')
// Create a TAR file tree using path
FileTree tar = tarTree('someFile.tar')
//tar tree attempts to guess the compression based on the file extension
//however if you must specify the compression explicitly you can:
FileTree someTar = tarTree(resources.gzip('someTar.ext'))


Example 16.8. Specifying a set of files
build.gradle
// Use a File object to specify the source directory
compile {
source = file('src/main/java')
}
// Use a String path to specify the source directory
compile {
source = 'src/main/java'
}
// Use a collection to specify multiple source directories
compile {
source = ['src/main/java', '../shared/java']
}
// Use a FileCollection (or FileTree in this case) to specify the source files
compile {
source = fileTree(dir: 'src/main/java').matching { include 'org/gradle/api/**' }
}
// Using a closure to specify the source files.
compile {
source = {
// Use the contents of each zip file in the src dir
file('src').listFiles().findAll {it.name.endsWith('.zip')}.collect { zipTree(it) }
}
}


Example 16.9. Specifying a set of files
build.gradle
compile {
// Add some source directories use String paths
source 'src/main/java', 'src/main/groovy'
// Add a source directory using a File object
source file('../shared/java')
// Add some source directories using a closure
source { file('src/test/').listFiles() }
}


Example 16.10. Copying files using the copy task
build.gradle
task copyTask(type: Copy) {
from 'src/main/webapp'
into 'build/explodedWar'
}


Example 16.11. Specifying copy task source files and destination directory
build.gradle
task anotherCopyTask(type: Copy) {
// Copy everything under src/main/webapp
from 'src/main/webapp'
// Copy a single file
from 'src/staging/index.html'
// Copy the output of a task
from copyTask
// Copy the output of a task using Task outputs explicitly.
from copyTaskWithPatterns.outputs
// Copy the contents of a Zip file
from zipTree('src/main/assets.zip')
// Determine the destination directory later
into { getDestDir() }
}


Example 16.12. Selecting the files to copy
build.gradle
task copyTaskWithPatterns(type: Copy) {
from 'src/main/webapp'
into 'build/explodedWar'
include '**/*.html'
include '**/*.jsp'
exclude { details -> details.file.name.endsWith('.html') &&
details.file.text.contains('staging') }
}


Example 16.13. Copying files using the copy() method without up-to-date check
build.gradle
task copyMethod << {
copy {
from 'src/main/webapp'
into 'build/explodedWar'
include '**/*.html'
include '**/*.jsp'
}
}


Example 16.14. Copying files using the copy() method with up-to-date check
build.gradle
task copyMethodWithExplicitDependencies{
// up-to-date check for inputs, plus add copyTask as dependency
inputs.file copyTask
outputs.dir 'some-dir' // up-to-date check for outputs
doLast{
copy {
// Copy the output of copyTask
from copyTask
into 'some-dir'
}
}
}


Example 16.15. Renaming files as they are copied
build.gradle
task rename(type: Copy) {
from 'src/main/webapp'
into 'build/explodedWar'
// Use a closure to map the file name
rename { String fileName ->
fileName.replace('-staging-', '')
}
// Use a regular expression to map the file name
rename '(.+)-staging-(.+)', '$1$2'
rename(/(.+)-staging-(.+)/, '$1$2')
}


Example 16.16. Filtering files as they are copied
build.gradle
import org.apache.tools.ant.filters.FixCrLfFilter
import org.apache.tools.ant.filters.ReplaceTokens
task filter(type: Copy) {
from 'src/main/webapp'
into 'build/explodedWar'
// Substitute property tokens in files
expand(copyright: '2009', version: '2.3.1')
expand(project.properties)
// Use some of the filters provided by Ant
filter(FixCrLfFilter)
filter(ReplaceTokens, tokens: [copyright: '2009', version: '2.3.1'])
// Use a closure to filter each line
filter { String line ->
"[$line]"
}
}


Example 16.17. Nested copy specs
build.gradle
task nestedSpecs(type: Copy) {
into 'build/explodedWar'
exclude '**/*staging*'
from('src/dist') {
include '**/*.html'
}
into('libs') {
from configurations.runtime
}
}


The Sync task extends the Copy task. When it executes, it copies the source files into the destination directory,
and then removes any files from the destination directory which it did not copy.


Example 16.18. Using the Sync task to copy dependencies
build.gradle
task libs(type: Sync) {
from configurations.runtime
into "$buildDir/libs"
}


Example 16.19. Creating a ZIP archive
build.gradle
apply plugin: 'java'
task zip(type: Zip) {
from 'src/dist'
into('libs') {
from configurations.runtime
}
}


chap18
Table 18.1. Log levels
Level Used for
ERROR Error messages
QUIET Important information messages
WARNING Warning messages
LIFECYCLE Progress information messages
INFO Information messages
DEBUG Debug messages


Table 18.2. Log level command-line options
Option Outputs Log Levels
no logging options LIFECYCLE and higher
-q or --quiet QUIET and higher
-i or --info INFO and higher
-d or --debug DEBUG and higher (that is, all log messages)


-s or --stacktrace
-S or --full-stacktrace


Example 18.1. Using stdout to write log messages
build.gradle
println 'A message which is logged at QUIET level'


Example 18.2. Writing your own log messages
build.gradle
logger.quiet('An info log message which is always logged.')
logger.error('An error log message.')
logger.warn('A warning log message.')
logger.lifecycle('A lifecycle info log message.')
logger.info('An info log message.')
logger.debug('A debug log message.')
logger.trace('A trace log message.')


Example 18.3. Using SLF4J to write log messages
build.gradle
import org.slf4j.Logger
import org.slf4j.LoggerFactory
Logger slf4jLogger = LoggerFactory.getLogger('some-logger')
slf4jLogger.info('An info log message logged using SLF4j')


Example 18.4. Configuring standard output capture
build.gradle
logging.captureStandardOutput LogLevel.INFO
println 'A message which is logged at INFO level'


Example 18.5. Configuring standard output capture for a task
build.gradle
task logInfo {
logging.captureStandardOutput LogLevel.INFO
doFirst {
println 'A task message which is logged at INFO level'
}
}


Example 18.6. Customizing what Gradle logs
init.gradle
useLogger(new CustomEventLogger())
class CustomEventLogger extends BuildAdapter implements TaskExecutionListener {
public void beforeExecute(Task task) {
println "[$task.name]"
}
public void afterExecute(Task task, TaskState state) {
println()
}
public void buildFinished(BuildResult result) {
d
println 'build completed'
if (result.failure != null) {
result.failure.printStackTrace()
}
}
}
Output of gradle -I init.gradle build










chap20
GRADLE_OPTS or JAVA_OPTS,


if an option is configured in multiple locations the last one
wins:
from gradle.properties in project build dir.
from gradle.properties in gradle user home.
from system properties, e.g. when -Dsome.property is set on the command line.


The following properties can be used to configure the Gradle build environment:
org.gradle.daemon
org.gradle.java.home
org.gradle.jvmargs
org.gradle.configureondemand
org.gradle.parallel


Example 20.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


Example 20.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


NTLM authentication




chap21
script plugins and binary plugins


Project.apply()


Example 21.1. Applying a script plugin
build.gradle
apply from: 'other.gradle'


Example 21.2. Applying a binary plugin
build.gradle
apply plugin: 'java'


using the short name 'java' to apply the
JavaPlugin.


Example 21.3. Applying a binary plugin by type
build.gradle
apply plugin: JavaPlugin


Example 21.4. Applying a core plugin
build.gradle
plugins {
id 'java'
}


Example 21.5. Applying a community plugin
build.gradle
plugins {
id "com.jfrog.bintray" version "0.4.1"
}


Example 21.6. Tasks added by a plugin
build.gradle
apply plugin: 'java'
task show << {
println relativePath(compileJava.destinationDir)
println relativePath(processResources.destinationDir)
}


Example 21.7. Changing plugin defaults
build.gradle
apply plugin: 'java'
compileJava.destinationDir = file("$buildDir/output/classes")
task show << {
println relativePath(compileJava.destinationDir)
}


Example 21.8. Plugin convention object
build.gradle
apply plugin: 'java'
sourceSets.main.output.classesDir = file("$buildDir/output/classes")
task show << {
println relativePath(compileJava.destinationDir)
}


chap23
23.3. Tasks
Table 23.1. Java plugin - tasks
Table 23.2. Java plugin - source set tasks
Table 23.3. Java plugin - lifecycle tasks
The following diagram shows the relationships between these tasks.


relationships between these tasks.
Figure 23.1. Java plugin - tasks


Table 23.4. Java plugin - default project layout
Directory Meaning
src/main/java Production Java source
src/main/resources Production resources
src/test/java Test Java source
src/test/resources Test resources
src/sourceSet/java Java source for the given source set
src/sourceSet/resources Resources for the given source set


Example 23.2. Custom Java source layout
build.gradle
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'src/resources'
}
}
}


Table 23.5. Java plugin - dependency configurations


Table 23.6. Java plugin - source set dependency configurations
SourceSetContainer


properties of the project object
Table 23.7. Java plugin - directory properties


SourceSetContainer
Example 23.3. Accessing a source set
build.gradle
// Various ways to access the main source set
println sourceSets.main.output.classesDir
println sourceSets['main'].output.classesDir
sourceSets {
println main.output.classesDir
}
sourceSets {
main {
println output.classesDir
}
}
// Iterate over the source sets
sourceSets.all {
println name
}


Example 23.4. Configuring the source directories of a source set
build.gradle
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'src/resources'
}
}
}


Table 23.9. Java plugin - source set properties
Example 23.5. Defining a source set
build.gradle
sourceSets {
intTest
}


Example 23.6. Defining source set dependencies
build.gradle
sourceSets {
intTest
}
dependencies {
intTestCompile 'junit:junit:4.11'
intTestRuntime 'org.ow2.asm:asm-all:4.0'
}


for a source set called intTest, compiling the
classes for this source set is done by running gradle intTestClasses.
Example 23.7. Compiling a source set
Output of gradle intTestClasses


Example 23.8. Assembling a JAR for a source set
build.gradle
task intTestJar(type: Jar) {
from sourceSets.intTest.output
}
Generating Javadoc for a source set:
Example 23.9. Generating the Javadoc for a source set
build.gradle
task intTestJavadoc(type: Javadoc) {
source sourceSets.intTest.allJava
}
Adding a test suite to run the tests in a source set:
Example 23.10. Running tests in a source set
build.gradle
task intTest(type: Test) {
testClassesDir = sourceSets.intTest.output.classesDir
classpath = sourceSets.intTest.runtimeClasspath
}


Table 23.10. Java plugin - Javadoc properties


Table 23.11. Java plugin - Clean properties


Table 23.12. Java plugin - ProcessResources properties


Table 23.13. Java plugin - Compile properties


23.13. Test
maxParallelForks
forkEvery
ignoreFailures
TestLoggingContainer
Test.getDebug()
--debug-jvm


Example 23.11. Filtering tests in the build script
build.gradle
test {
filter {
//include specific method in any of the tests
includeTestsMatching "*UiCheck"
//include all tests from package
includeTestsMatching "org.gradle.internal.*"
//include all integration tests
includeTestsMatching "*IntegTest"
}
}


Some examples of using the command line option:
gradle test --tests org.gradle.SomeTest.someSpecificFeature
gradle test --tests *SomeTest.someSpecificFeature
gradle test --tests *SomeSpecificTest
gradle test --tests all.in.specific.package*
gradle test --tests *IntegTest
gradle test --tests *IntegTest*ui*
gradle someTestTask --tests *UiTest someOtherTestTask --tests *WebTest*ui


gradle -Dtest.single=ThisUniquelyNamedTest test
gradle -Dtest.single=a/b/ test
gradle -DintegTest.single=*IntegrationTest integTest
gradle -Dtest.single=:proj1:test:Customer build
gradle -DintegTest.single=c/d/ :proj1:integTest


scanForTestClasses


Example 23.12. JUnit Categories
build.gradle
test {
useJUnit {
includeCategories 'org.gradle.junit.CategoryA'
excludeCategories 'org.gradle.junit.CategoryB'
}
}


Example 23.13. Grouping TestNG tests
build.gradle
test {
useTestNG {
excludeGroups 'integrationTests'
includeGroups 'unitTests'
}
}


Example 23.14. Creating a unit test report for subprojects
build.gradle
subprojects {
apply plugin: 'java'
// Disable the test report for the individual test task
test {
reports.html.enabled = false
}
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/allTests")
// Include the results from the `test` task in all subprojects
reportOn subprojects*.test
}


Table 23.14. Java plugin - test properties


Example 23.15. Customization of MANIFEST.MF
build.gradle
jar {
manifest {
attributes("Implementation-Title": "Gradle",
"Implementation-Version": version)
}
}


Example 23.16. Creating a manifest object.
build.gradle
ext.sharedManifest = manifest {
attributes("Implementation-Title": "Gradle",
"Implementation-Version": version)
}
task fooJar(type: Jar) {
manifest = project.manifest {
from sharedManifest
}
}


Example 23.17. Separate MANIFEST.MF for a particular archive
build.gradle
task barJar(type: Jar) {
manifest {
attributes key1: 'value1'
from sharedManifest, 'src/config/basemanifest.txt'
from('src/config/javabasemanifest.txt',
'src/config/libbasemanifest.txt') {
eachEntry { details ->
if (details.baseValue != details.mergeValue) {
details.value = baseValue
}
if (details.key == 'foo') {
details.exclude()
}
}
}
}
}


You can easily write a manifest to disk.
Example 23.18. Separate MANIFEST.MF for a particular archive
build.gradle
jar.manifest.writeTo("$buildDir/mymanifest.mf")




chap51
To learn more about this API have a look at
ConfigurationContainer.
To define a configuration:
Example 51.1. Definition of a configuration
build.gradle
configurations {
compile
}


Example 51.2. Accessing a configuration
build.gradle
println configurations.compile.name
println configurations['compile'].name


Example 51.3. Configuration of a configuration
build.gradle
configurations {
compile {
description = 'compile classpath'
transitive = true
}
runtime {
extendsFrom compile
}
}
configurations.compile {
description = 'compile classpath'
}


Example 51.4. Module dependencies
build.gradle
dependencies {
runtime group: 'org.springframework', name: 'spring-core', version: '2.5'
runtime 'org.springframework:spring-core:2.5',
'org.springframework:spring-aop:2.5'
runtime(
[group: 'org.springframework', name: 'spring-core', version: '2.5'],
[group: 'org.springframework', name: 'spring-aop', version: '2.5']
)
runtime('org.hibernate:hibernate:3.0.5') {
transitive = true
}
runtime group: 'org.hibernate', name: 'hibernate', version: '3.0.5', transitive: true
runtime(group: 'org.hibernate', name: 'hibernate', version: '3.0.5') {
transitive = true
}
}


Example 51.5. Artifact only notation
build.gradle
dependencies {
runtime "org.groovy:groovy:2.2.0@jar"
runtime group: 'org.groovy', name: 'groovy', version: '2.2.0', ext: 'jar'
}
An artifact only notation creates a module dependency which downloads only the artifact file with the specified
extension. Existing module descriptors are ignored.


Example 51.6. Dependency with classifier
build.gradle
compile "org.gradle.test.classifiers:service:1.0:jdk15@jar"
otherConf group: 'org.gradle.test.classifiers', name: 'service', version: '1.0', classifier


Example 51.7. Iterating over a configuration
build.gradle
task listJars << {
configurations.compile.each {
File file -> println file.name
}
}


Example 51.8. Client module dependencies - transitive dependencies
build.gradle
dependencies {
runtime module("org.codehaus.groovy:groovy:2.3.6") {
dependency("commons-cli:commons-cli:1.0") {
transitive = false
}
module(group: 'org.apache.ant', name: 'ant', version: '1.9.3') {
dependencies "org.apache.ant:ant-launcher:1.9.3@jar",
"org.apache.ant:ant-junit:1.9.3"
}
}
}


Example 51.9. Project dependencies
build.gradle
dependencies {
compile project(':shared')
}


Example 51.10. File dependencies
build.gradle
dependencies {
runtime files('libs/a.jar', 'libs/b.jar')
runtime fileTree(dir: 'libs', include: '*.jar')
}


Example 51.11. Generated file dependencies
build.gradle
dependencies {
compile files("$buildDir/classes") {
builtBy 'compile'
}
}
task compile << {
println 'compiling classes'
}
task list(dependsOn: configurations.compile) << {
println "classpath = ${configurations.compile.collect {File file -> file.name}}"
}


Example 51.12. Gradle API dependencies
build.gradle
dependencies {
compile gradleApi()
}


Example 51.13. Gradle's Groovy dependencies
build.gradle
dependencies {
compile localGroovy()
}


Example 51.14. Excluding transitive dependencies
build.gradle
configurations {
compile.exclude module: 'commons'
all*.exclude group: 'org.gradle.test.excludes', module: 'reports'
}
dependencies {
compile("org.gradle.test.excludes:api:1.0") {
exclude module: 'shared'
}
}


Example 51.15. Optional attributes of dependencies
build.gradle
dependencies {
runtime ":junit:4.10", ":testng"
runtime name: 'testng'
}


Example 51.16. Collections and arrays of dependencies
build.gradle
List groovy = ["org.codehaus.groovy:groovy-all:2.3.6@jar",
"commons-cli:commons-cli:1.0@jar",
"org.apache.ant:ant:1.9.3@jar"]
List hibernate = ['org.hibernate:hibernate:3.0.5@jar',
'somegroup:someorg:1.0@jar']
dependencies {
runtime groovy, hibernate
}


Example 51.17. Dependency configurations
build.gradle
dependencies {
runtime group: 'org.somegroup', name: 'somedependency', version: '1.0', configuration: 'someConfiguration'
}


Example 51.18. Dependency configurations for project
build.gradle
dependencies {
compile project(path: ':api', configuration: 'spi')
}


Example 51.19. Configuration.copy
build.gradle
configurations {
sealife
alllife
}
dependencies {
sealife "sea.mammals:orca:1.0", "sea.fish:shark:1.0", "sea.fish:tuna:1.0"
alllife configurations.sealife
alllife "air.birds:albatross:1.0"
}


Example 51.20. Accessing declared dependencies
build.gradle
task dependencies << {
configurations.alllife.dependencies.each { dep -> println dep.name }
println()
configurations.alllife.allDependencies.each { dep -> println dep.name }
println()
configurations.alllife.allDependencies.findAll { dep -> dep.name != 'orca' }
.each { dep -> println dep.name }
}


Example 51.21. Configuration.files
build.gradle
task allFiles << {
configurations.sealife.files.each { file ->
println file.name
}
}


Example 51.22. Configuration.files with spec
build.gradle
task files << {
configurations.sealife.files { dep -> dep.name == 'orca' }.each { file ->
println file.name
}
}


Example 51.23. Configuration.copy
build.gradle
task copy << {
configurations.alllife.copyRecursive { dep -> dep.name != 'orca' }
.allDependencies.each { dep -> println dep.name }
println()
configurations.alllife.copy().allDependencies
.each { dep -> println dep.name }
}


Example 51.23. Configuration.copy
build.gradle
task copy << {
configurations.alllife.copyRecursive { dep -> dep.name != 'orca' }
.allDependencies.each { dep -> println dep.name }
println()
configurations.alllife.copy().allDependencies
.each { dep -> println dep.name }
}


Example 51.25. Declaring a Maven and Ivy repository
build.gradle
repositories {
maven {
url "http://repo.mycompany.com/maven2"
}
ivy {
url "http://repo.mycompany.com/repo"
}
}


Example 51.26. Providing credentials to a Maven and Ivy repository
build.gradle
repositories {
maven {
url "sftp://repo.mycompany.com:22/maven2"
credentials {
username 'user'
password 'password'
}
}
ivy {
url "sftp://repo.mycompany.com:22/repo"
credentials {
username 'user'
password 'password'
}
}
}


Example 51.27. Adding central Maven repository
build.gradle
repositories {
mavenCentral()
}


Example 51.31. Adding custom Maven repository
build.gradle
repositories {
maven {
url "http://repo.mycompany.com/maven2"
}
}


Example 51.32. Adding additional Maven repositories for JAR files
build.gradle
repositories {
maven {
// Look for POMs and artifacts, such as JARs, here
url "http://repo2.mycompany.com/maven2"
// Look for artifacts here if not found at the above location
artifactUrls "http://repo.mycompany.com/jars"
artifactUrls "http://repo.mycompany.com/jars2"
}
}


Example 51.33. Accessing password protected Maven repository
build.gradle
repositories {
maven {
credentials {
username 'user'
password 'password'
}
url "http://repo.mycompany.com/maven2"
}
}


Example 51.34. Flat repository resolver
build.gradle
repositories {
flatDir {
dirs 'lib'
}
flatDir {
dirs 'lib1', 'lib2'
}
}


Example 51.41. Accessing a repository
build.gradle
println repositories.localRepository.name
println repositories['localRepository'].name
To configure a repository:
Example 51.42. Configuration of a repository
build.gradle
repositories {
flatDir {
name 'localRepository'
}
}
repositories {
localRepository {
dirs 'lib'
}
}
repositories.localRepository {
dirs 'lib'
}


Example 51.44. Forcing consistent version for a group of libraries
build.gradle
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.gradle') {
details.useVersion '1.4'
}
}
}


Example 51.45. Using a custom versioning scheme
build.gradle
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.version == 'default') {
def version = findDefaultVersionInCatalog(details.requested.group, details.requested.details.useVersion version
}
}
}
def findDefaultVersionInCatalog(String group, String name) {
//some custom logic that resolves the default version into a specific version
"1.0"
}


Example 51.46. Blacklisting a version with a replacement
build.gradle
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.software' && details.requested.name == 'some-library' //prefer different version which contains some necessary fixes
details.useVersion '1.2.1'
}
}
}


Example 51.47. Changing dependency group and/or name at the resolution
build.gradle
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.name == 'groovy-all') {
//prefer 'groovy' over 'groovy-all':
details.useTarget group: details.requested.group, name: 'groovy', version: details.requested.}
if (details.requested.name == 'log4j') {
//prefer 'log4j-over-slf4j' over 'log4j', with fixed version:
details.useTarget "org.slf4j:log4j-over-slf4j:1.7.7"
}
}
}


Example 51.48. Declaring module replacement
build.gradle
dependencies {
modules {
module("com.google.collections:google-collections") {
replacedBy("com.google.guava:guava")
}
}
}


Example 51.50. 'Latest' version selector
build.gradle
dependencies {
config1 "sea.fish:tuna:latest.integration"
config2 "sea.fish:tuna:latest.release"
}
task listFish << {
configurations.config1.each { println it.name }
println()
configurations.config2.each { println it.name}
}


Example 51.51. Custom status scheme
build.gradle
dependencies {
config3 "air.birds:albatross:latest.silver"
components {
eachComponent { ComponentMetadataDetails details ->
if (details.id.group == "air.birds") {
details.statusScheme = ["bronze", "silver", "gold", "platinum"]
}
}
}
}
task listBirds << {
configurations.config3.each { println it.name }
}


Example 51.53. Component selection rule
build.gradle
configurations {
rejectConfig {
resolutionStrategy {
componentSelection {
// Accept the highest version matching the requested version that isn't '1.5'
all { ComponentSelection selection ->
if (selection.candidate.group == 'org.sample' && selection.candidate.module selection.reject("version 1.5 is broken for 'org.sample:api'")
}
}
}
}
}
}
dependencies {
rejectConfig "org.sample:api:1.+"
}


Example 51.54. Component selection rule with module target
build.gradle
configurations {
targetConfig {
resolutionStrategy {
componentSelection {
withModule("org.sample:api") { ComponentSelection selection ->
if (selection.candidate.version == "1.5") {
selection.reject("version 1.5 is broken for 'org.sample:api'")
}
}
}
}
}
}


Example 51.55. Component selection rule with metadata
build.gradle
configurations {
metadataRulesConfig {
resolutionStrategy {
componentSelection {
// Reject any versions with a status of 'experimental'
all { ComponentSelection selection, ComponentMetadata metadata ->
if (selection.candidate.group == 'org.sample' && metadata.status == 'experimental') selection.reject("don't use experimental candidates from 'org.sample'")
}
}
// Accept the highest version with either a "release" branch or a status of 'milestone'
withModule('org.sample:api') { ComponentSelection selection, IvyModuleDescriptor if (descriptor.branch != "release" && metadata.status != 'milestone') {
selection.reject("'org.sample:api' must have testing branch or milestone }
}
}
}
}
}


Example 51.56. Component selection rule using a rule source object
build.gradle
class RejectTestBranch {
@Mutate
void evaluateRule(ComponentSelection selection, IvyModuleDescriptor ivy) {
if (ivy.branch == "test") {
selection.reject("reject test branch")
}
}
}
configurations {
ruleSourceConfig {
resolutionStrategy {
componentSelection {
all new RejectTestBranch()
}
}
}
}


Example 51.57. Dynamic version cache control
build.gradle
configurations.all {
resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
}


Example 51.58. Changing module cache control
build.gradle
configurations.all {
resolutionStrategy.cacheChangingModulesFor 4, 'hours'
}




chap52
Example 52.1. Defining an artifact using an archive task
build.gradle
task myJar(type: Jar)
artifacts { archives myJar }


Example 52.2. Defining an artifact using a file
build.gradle
def someFile = file('build/somefile.txt')
artifacts { archives someFile }


Example 52.3. Customizing an artifact
build.gradle
task myTask(type: MyTaskType) { destFile = file('build/somefile.txt') }
artifacts {
archives(myTask.destFile) {
name 'my-artifact'
type 'text'
builtBy myTask
}
}


Example 52.4. Map syntax for defining an artifact using a file
build.gradle
task generate(type: MyTaskType) {
destFile = file('build/somefile.txt')
}
artifacts {
archives file: generate.destFile, name: 'my-artifact', type: 'text', builtBy: generate
}


Example 52.5. Configuration of the upload task
build.gradle
repositories {
flatDir {
name "fileRepo"
dirs "repo"
}
}
uploadArchives {
repositories {
add project.repositories.fileRepo
ivy {
credentials {
username "username"
password "pw"
}
url "http://repo.mycompany.com"
}
}
}


chap56
Example 56.1. Single project build
settings.gradle
println 'This is executed during the initialization phase.'
build.gradle
println 'This is executed during the configuration phase.'
task configured { println 'This is also executed during the configuration phase.' }
task test << { println 'This is executed during the execution phase.' }
task testBoth {
doFirst { println 'This is executed first during the execution phase.' }
doLast { println 'This is executed last during the execution phase.' }
println 'This is executed during the configuration phase as well.'
}


Settings class
Example 56.2. Hierarchical layout
settings.gradle
include 'project1', 'project2:child', 'project3:child1'


Example 56.3. Flat layout
settings.gradle
includeFlat 'project3', 'project4'


Example 56.4. Modification of elements of the project tree
settings.gradle
println rootProject.name
println project(':projectA').name


Example 56.5. Modification of elements of the project tree
settings.gradle
rootProject.name = 'main'
project(':projectA').projectDir = new File(settingsDir, '../my-project-a')
project(':projectA').buildFileName = 'projectA.gradle'


Example 56.6. Adding of test task to each project which has certain property set
build.gradle
allprojects {
afterEvaluate {
project ->
if (project.hasTests) {
println "Adding test task to $project"
project.task('test') << {
println "Running tests for $project"
}
}
}
}
projectA.gradle
hasTests = true


Example 56.7. Notifications
build.gradle
gradle.afterProject {
project, projectState ->
if (projectState.failure) {
println "Evaluation of $project FAILED"
} else {
println "Evaluation of $project succeeded"
}
}


Example 56.8. Setting of certain property to all tasks
build.gradle
tasks.whenTaskAdded {
task ->
task.ext.srcDir = 'src/main/java'
}
task a
println "source dir is $a.srcDir"


Example 57.1. Multi-project tree - water & bluewhale projects
Build layout
water/
build.gradle
settings.gradle
bluewhale/


settings.gradle
include 'bluewhale'


Example 57.2. Build script of water (parent) project
build.gradle
Closure cl = { task -> println "I'm $task.project.name" }
task hello << cl
project(':bluewhale') { task hello << cl }


Example 57.3. Multi-project tree - water, bluewhale & krill projects
Build layout
water/
build.gradle
settings.gradle
bluewhale/
krill/


settings.gradle
include 'bluewhale', 'krill'


Example 57.4. Water project build script
build.gradle
allprojects {
task hello << { task -> println "I'm $task.project.name" }
}


Example 57.5. Defining common behavior of all projects and subprojects
build.gradle
allprojects {
task hello << {task -> println "I'm $task.project.name" }
}
subprojects { hello << {println "- I depend on water"} }


Example 57.6. Defining specific behaviour for particular project
build.gradle
allprojects {
task hello << {
task -> println "I'm $task.project.name"
}
}
subprojects {
hello << {
println "- I depend on water"
}
}
project(':bluewhale').hello << {
println "- I'm the largest animal that has ever lived on this planet."
}


Example 57.7. Defining specific behaviour for project krill
Build layout
water/
build.gradle
settings.gradle
bluewhale/
build.gradle
krill/
build.gradle


settings.gradle
include 'bluewhale', 'krill'
bluewhale/build.gradle
hello.doLast {
println "- I'm the largest animal that has ever lived on this planet."
}
krill/build.gradle
hello.doLast {
println "- The weight of my species in summer is twice as heavy as all human beings."
}
build.gradle
allprojects {
task hello << {
task -> println "I'm $task.project.name"
}
}
subprojects {
hello << {
println "- I depend on water"
}
}




Example 57.8. Adding custom behaviour to some projects (filtered by project name)
Build layout
water/
build.gradle
settings.gradle
bluewhale/
build.gradle
krill/
build.gradle
tropicalFish/


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


Example 57.9. Adding custom behaviour to some projects (filtered by project properties)
Build layout
water/
build.gradle
settings.gradle
bluewhale/
build.gradle
krill/
build.gradle
tropicalFish/
build.gradle


settings.gradle
include 'bluewhale', 'krill', 'tropicalFish'
bluewhale/build.gradle
ext.arctic = true
hello.doLast {
println "- I'm the largest animal that has ever lived on this planet."
}
krill/build.gradle
ext.arctic = true
hello.doLast {
println "- The weight of my species in summer is twice as heavy as all human beings."
}
tropicalFish/build.gradle
ext.arctic = false
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 57.11. Evaluation and execution of projects
bluewhale/build.gradle
ext.arctic = true
hello << {
println "- I'm the largest animal that has ever lived on this planet."
}
task distanceToIceberg << {
println '20 nautical miles'
}
krill/build.gradle
ext.arctic = true
hello << {
println "- The weight of my species in summer is twice as heavy as all human beings."
}
task distanceToIceberg << {
println '5 nautical miles'
}


Example 57.13. Running tasks by their absolute path
Output of gradle -q :hello :krill:hello hello


Example 57.14. Dependencies and execution order
Build layout
messages/
settings.gradle
consumer/
buil d.gradle
producer/
bui ld.gradle


settings.gradle
include 'consumer', 'producer'
consumer/build.gradle
task action << {
println("Consuming message: ${rootProject.producerMessage}")
}
producer/build.gradle
task action << {
println "Producing message:"
rootProject.producerMessage = 'Watch the order of execution.'
}


Example 57.15. Dependencies and execution order
Build layout
messages/
settings.gradle
aProducer/
build.gradle
consumer/
build.gradle
settings.gradle
include 'consumer', 'aProducer'
aProducer/build.gradle
task action << {
println "Producing message:"
rootProject.producerMessage = 'Watch the order of execution.'
}
consumer/build.gradle
task action << {
println("Consuming message: ${rootProject.producerMessage}")
}


Example 57.17. Declaring dependencies
Build 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/which is in both the binary and source distributions of Gradle.
settings.gradle
include 'consumer', 'producer'
consumer/build.gradle
task action(dependsOn: ":producer:action") << {
println("Consuming message: ${rootProject.producerMessage}")
}
producer/build.gradle
task action << {
println "Producing message:"
rootProject.producerMessage = 'Watch the order of execution.'
}


Example 57.19. Cross project task dependencies
consumer/build.gradle
task consume(dependsOn: ':producer:produce') << {
println("Consuming message: ${rootProject.producerMessage}")
}
producer/build.gradle
task produce << {
println "Producing message:"
rootProject.producerMessage = 'Watch the order of execution.'
}


Example 57.20. Configuration time dependencies
consumer/build.gradle
def message = rootProject.producerMessage
task consume << {
println("Consuming message: " + message)
}
producer/build.gradle
rootProject.producerMessage = 'Watch the order of evaluation.'
Output of gradle -q consume
> gradle -q consume
Consuming message: null


Example 57.21. Configuration time dependencies - evaluationDependsOn
consumer/build.gradle
evaluationDependsOn(':producer')
def message = rootProject.producerMessage
task consume << {
println("Consuming message: " + message)
}


Example 57.22. Configuration time dependencies
consumer/build.gradle
task consume << {
println("Consuming message: ${rootProject.producerMessage}")
}


Example 57.23. Dependencies - real life example - crossproject configuration
Build layout
webDist/
settings.gradle
build.gradle
date/
src/main/java/
org/gradle/sample/
DateServlet.java
hello/
src/main/java/
org/gradle/sample/
HelloServlet.java


settings.gradle
include 'date', 'hello'
build.gradle
allprojects {
apply plugin: 'java'
group = 'org.gradle.sample'
version = '1.0'
}
subprojects {
apply plugin: 'war'
repositories {
mavenCentral()
}
dependencies {
compile "javax.servlet:servlet-api:2.5"
}
}
task explodedDist(dependsOn: assemble) << {
File explodedDist = mkdir("$buildDir/explodedDist")
subprojects.each {
project ->
project.tasks.withType(Jar).each {
archiveTask ->
copy {
from archiveTask.archivePath
into explodedDist
}
}
}
}


Example 57.24. Project lib dependencies
Build layout
java/
settings.gradle
build.gradle
api/
src/main/java/
org/gradle/sample/
api/
Person.java
apiImpl/
PersonImpl.java
services/personService/
src/
main/java/
org/gradle/sample/services/
PersonService.java
test/java/
org/gradle/sample/services/
PersonServiceTest.java
shared/
src/main/java/
org/gradle/sample/shared/
Helper.java


Example 57.25. Project lib dependencies
settings.gradle
include 'api', 'shared', 'services:personService'
build.gradle
subprojects {
apply plugin: 'java'
group = 'org.gradle.sample'
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
testCompile "junit:junit:4.11"
}
}
project(':api') {
dependencies {
compile project(':shared')
}
}
project(':services:personService') {
dependencies {
compile project(':shared'), project(':api')
}
}


Example 57.26. Fine grained control over dependencies
build.gradle
subprojects {
apply plugin: 'java'
group = 'org.gradle.sample'
version = '1.0'
}
project(':api') {
configurations {
spi
}
dependencies {
compile project(':shared')
}
task spiJar(type: Jar) {
baseName = 'api-spi'
dependsOn classes
from sourceSets.main.output
include('org/gradle/sample/api/**')
}
artifacts {
spi spiJar
}
}
project(':services:personService') {
dependencies {
compile project(':shared')
compile project(path: ':api', configuration: 'spi')
testCompile "junit:junit:4.11", project(':api')
}
}


Test.setMaxParallelForks()


Example 57.27. Build and Test Single Project
Output of gradle :api:build


Example 57.28. Partial Build and Test Single Project
Output of gradle -a :api:build


Example 57.29. Build and Test Depended On Projects
Output of gradle :api:buildNeeded


Example 57.30. Build and Test Dependent Projects
Output of gradle :api:buildDependents


app_D.txt
The gradle command has the following usage:
gradle [option...] [task...]
The command-line options available for the gradle command are listed below:
-?, -h, --help
Shows a help message.
-a, --no-rebuild
Do not rebuild project dependencies.
--all
Shows additional detail in the task listing. See Section 11.6.2, “Listing tasks”.
-b, --build-file
Specifies the build file. See Section 11.5, “Selecting which build to execute”.
-c, --settings-file
Specifies the settings file.
--continue
Continues task execution after a task failure.
--configure-on-demand (incubating)
Only relevant projects are configured in this build run. This means faster builds for large multi-projects. See
Section 57.1.1.1, “Configuration on demand”.
-D, --system-prop
Sets a system property of the JVM, for example -Dmyprop=myvalue. See Section 14.2, “Gradle properties
and system properties”.
-d, --debug
Log in debug mode (includes normal stacktrace). See Chapter 18, Logging.
-g, --gradle-user-home
Specifies the Gradle user home directory. The default is the .gradle directory in the user's home directory.
--gui
Launches the Gradle GUI. See Chapter 12, Using the Gradle Graphical User Interface.
Page 433 of 443
-I, --init-script
Specifies an initialization script. See Chapter 61, Initialization Scripts.
-i, --info
Set log level to info. See Chapter 18, Logging.
-m, --dry-run
Runs the build with all task actions disabled. See Section 11.7, “Dry Run”.
--no-color
Do not use color in the console output.
--offline
Specifies that the build should operate without accessing network resources. See Section 51.9.2, “Command line
options to override caching”.
-P, --project-prop
Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle
properties and system properties”.
-p, --project-dir
Specifies the start directory for Gradle. Defaults to current directory. See Section 11.5, “Selecting which build
to execute”.
--parallel (incubating)
Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use. This
option should only be used with decoupled projects (see Section 57.9, “Decoupled Projects”).
--parallel-threads (incubating)
Build projects in parallel, using the specified number of executor threads. For example--parallel-threads=3
. This option should only be used with decoupled projects (see Section 57.9, “Decoupled Projects”).
--profile
Profiles build execution time and generates a report in the buildDir/reports/profile directory. See
Section 11.6.7, “Profiling a build”.
--project-cache-dir
Specifies the project-specific cache directory. Default value is .gradle in the root project directory. See
Section 14.6, “Caching”.
-q, --quiet
Log errors only. See Chapter 18, Logging.
--recompile-scripts
Specifies that cached build scripts are skipped and forced to be recompiled. See Section 14.6, “Caching”.
--refresh-dependencies
Refresh the state of dependencies. See Section 51.9.2, “Command line options to override caching”.
Page 434 of 443
--rerun-tasks
Specifies that any task optimization is ignored.
-S, --full-stacktrace
Print out the full (very verbose) stacktrace for any exceptions. See Chapter 18, Logging.
-s, --stacktrace
Print out the stacktrace also for user exceptions (e.g. compile error). See Chapter 18, Logging.
-u, --no-search-upwards
Don't search in parent directories for a settings.gradle file.
-v, --version
Prints version info.
-x, --exclude-task
Specifies a task to be excluded from execution. See Section 11.2, “Excluding tasks”.
The above information is printed to the console when you execute gradle -h.


app_E.txt
import org.gradle.*
import org.gradle.api.*
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.cache.*
import org.gradle.api.artifacts.component.*
import org.gradle.api.artifacts.dsl.*
import org.gradle.api.artifacts.ivy.*
import org.gradle.api.artifacts.maven.*
import org.gradle.api.artifacts.query.*
import org.gradle.api.artifacts.repositories.*
import org.gradle.api.artifacts.result.*
import org.gradle.api.component.*
import org.gradle.api.distribution.*
import org.gradle.api.distribution.plugins.*
import org.gradle.api.dsl.*
import org.gradle.api.execution.*
import org.gradle.api.file.*
import org.gradle.api.initialization.*
import org.gradle.api.initialization.dsl.*
import org.gradle.api.invocation.*
import org.gradle.api.java.archives.*
import org.gradle.api.logging.*
import org.gradle.api.plugins.*
import org.gradle.api.plugins.announce.*
import org.gradle.api.plugins.antlr.*
import org.gradle.api.plugins.buildcomparison.gradle.*
import org.gradle.api.plugins.jetty.*
import org.gradle.api.plugins.osgi.*
import org.gradle.api.plugins.quality.*
import org.gradle.api.plugins.scala.*
import org.gradle.api.plugins.sonar.*
import org.gradle.api.plugins.sonar.model.*
import org.gradle.api.publish.*
import org.gradle.api.publish.ivy.*
import org.gradle.api.publish.ivy.plugins.*
import org.gradle.api.publish.ivy.tasks.*
import org.gradle.api.publish.maven.*
import org.gradle.api.publish.maven.plugins.*
import org.gradle.api.publish.maven.tasks.*
import org.gradle.api.publish.plugins.*
import org.gradle.api.reporting.*
import org.gradle.api.reporting.components.*
import org.gradle.api.reporting.dependencies.*
import org.gradle.api.reporting.plugins.*
import org.gradle.api.resources.*
import org.gradle.api.specs.*
import org.gradle.api.tasks.*
import org.gradle.api.tasks.ant.*
import org.gradle.api.tasks.application.*
import org.gradle.api.tasks.bundling.*
import org.gradle.api.tasks.compile.*
import org.gradle.api.tasks.diagnostics.*
import org.gradle.api.tasks.incremental.*
import org.gradle.api.tasks.javadoc.*
import org.gradle.api.tasks.scala.*
import org.gradle.api.tasks.testing.*
import org.gradle.api.tasks.testing.junit.*
import org.gradle.api.tasks.testing.testng.*
import org.gradle.api.tasks.util.*
import org.gradle.api.tasks.wrapper.*
import org.gradle.buildinit.plugins.*
import org.gradle.buildinit.tasks.*
import org.gradle.external.javadoc.*
import org.gradle.ide.cdt.*
import org.gradle.ide.cdt.tasks.*
import org.gradle.ide.visualstudio.*
import org.gradle.ide.visualstudio.plugins.*
import org.gradle.ide.visualstudio.tasks.*
import org.gradle.jvm.*
import org.gradle.jvm.platform.*
import org.gradle.jvm.plugins.*
import org.gradle.jvm.toolchain.*
import org.gradle.language.*
import org.gradle.language.assembler.*
import org.gradle.language.assembler.plugins.*
import org.gradle.language.assembler.tasks.*
import org.gradle.language.base.*
import org.gradle.language.base.artifact.*
import org.gradle.language.base.plugins.*
import org.gradle.language.c.*
import org.gradle.language.c.plugins.*
import org.gradle.language.c.tasks.*
import org.gradle.language.cpp.*
import org.gradle.language.cpp.plugins.*
import org.gradle.language.cpp.tasks.*
import org.gradle.language.java.*
import org.gradle.language.java.artifact.*
import org.gradle.language.java.plugins.*
import org.gradle.language.java.tasks.*
import org.gradle.language.jvm.*
import org.gradle.language.jvm.plugins.*
import org.gradle.language.jvm.tasks.*
import org.gradle.language.nativeplatform.*
import org.gradle.language.nativeplatform.tasks.*
import org.gradle.language.objectivec.*
import org.gradle.language.objectivec.plugins.*
import org.gradle.language.objectivec.tasks.*
import org.gradle.language.objectivecpp.*
import org.gradle.language.objectivecpp.plugins.*
import org.gradle.language.objectivecpp.tasks.*
import org.gradle.language.rc.*
import org.gradle.language.rc.plugins.*
import org.gradle.language.rc.tasks.*
import org.gradle.nativeplatform.*
import org.gradle.nativeplatform.platform.*
import org.gradle.nativeplatform.plugins.*
import org.gradle.nativeplatform.tasks.*
import org.gradle.nativeplatform.test.*
import org.gradle.nativeplatform.test.cunit.*
import org.gradle.nativeplatform.test.cunit.plugins.*
import org.gradle.nativeplatform.test.cunit.tasks.*
import org.gradle.nativeplatform.test.plugins.*
import org.gradle.nativeplatform.test.tasks.*
import org.gradle.nativeplatform.toolchain.*
import org.gradle.nativeplatform.toolchain.plugins.*
import org.gradle.platform.base.*
import org.gradle.platform.base.binary.*
import org.gradle.platform.base.component.*
import org.gradle.platform.base.test.*
import org.gradle.plugin.use.*
import org.gradle.plugins.ear.*
import org.gradle.plugins.ear.descriptor.*
import org.gradle.plugins.ide.api.*
import org.gradle.plugins.ide.eclipse.*
import org.gradle.plugins.ide.idea.*
import org.gradle.plugins.javascript.base.*
import org.gradle.plugins.javascript.coffeescript.*
import org.gradle.plugins.javascript.envjs.*
import org.gradle.plugins.javascript.envjs.browser.*
import org.gradle.plugins.javascript.envjs.http.*
import org.gradle.plugins.javascript.envjs.http.simple.*
import org.gradle.plugins.javascript.jshint.*
import org.gradle.plugins.javascript.rhino.*
import org.gradle.plugins.javascript.rhino.worker.*
import org.gradle.plugins.signing.*
import org.gradle.plugins.signing.signatory.*
import org.gradle.plugins.signing.signatory.pgp.*
import org.gradle.plugins.signing.type.*
import org.gradle.plugins.signing.type.pgp.*
import org.gradle.process.*
import org.gradle.sonar.runner.*
import org.gradle.sonar.runner.plugins.*
import org.gradle.sonar.runner.tasks.*




































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值