Tasks - pford68/gradle-examples GitHub Wiki
Configuration vs. Execution
Within a Gradle file you have can configuration blocks (dependencies, allprojects, task configurations, plugin configurations, etc.), and you can have task and functions. Any statement (say, a log statement like println) inside the former will always be executed, because it is part of the configuration of the task/plugin/etc. at that point. Anything inside a task or function will only be executed when the task is invoked.
Therefore, doing something like this will yield surprising results:
task deploy(type:Copy){
println 'Inside the deploy task...'
into('some/place'){
from('some/other/place')
}
}
While this looks like the declaration of a new task, it is actually the configuration of a task that extends Copy. So the print statement will be executed whenever the gradle build is run, whether the task is used or not.
One way to fix this would be to use doFirst or doLast:
task deploy(type:Copy){
doFirst {
println 'Inside the deploy task...'
}
into('some/place'){
from('some/other/place')
}
}
The doFirst block puts the print statement in the execution phase.
Custom Tasks
Again, this code creates a new Copy task, and is configuring that task:
task deploy(type:Copy){
into('some/place'){
from('some/other/place')
}
}
This next piece of code is creating a new task which will be evaluated while the task is being run. << is exactly the same as invoking doLast method on Task's object. You can add many actions.
task hello << {
println 'Hello!!!'
}
class GreetingToFileTask extends DefaultTask {
def destination
File getDestination() {
project.file(destination)
}
@TaskAction
def greet() {
def file = getDestination()
file.parentFile.mkdirs()
file.write "Hello!"
}
}
task greet(type: GreetingToFileTask) {
destination = { project.greetingFile }
}
task sayGreeting(dependsOn: greet) {
doLast {
println file(greetingFile).text
}
}
ext.greetingFile = "$buildDir/hello.txt"