How to create gradle task which always runs? - gradle

I'm likely overlooking something pretty core/obvious, but how can I create a task that will always be executed for every task/target?
I can do something like:
task someTask << {
println "I sometimes run"
}
println "I always run"
But it would be much more desirable to have the always running part in a task.
The closest I've come is:
task someTask << {
println "I sometimes run"
}
println "I always run"
void helloThing() {
println "I always run too. Hello?"
}
helloThing()
So, using a method is an 'ok' solution, but I was hoping there'd be a way to specifically designate/re-use a task.
Hopefully somebody has a way to do this. :)

Assuming the goal is to print system information, you could either just always print the information in the configuration phase (outside a task declaration), and have a dummy task systemStatus that does nothing (because the information is printed anyway). Or you could implement it as a regular task, and make sure the task always gets run by adding ":systemStatus" as the first item of gradle.startParameter.taskNames (a list of strings), which simulates someone always typing gradle :systemStatus .... Or you could leverage a hook such as gradle.projectsLoaded { ... } to print the information there.

This attaches a closure to every task in every project in the given build:
def someClosure = { task ->
println "task executed: $task"
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
task << someClosure
}
}
If you need the function/closure to be called only once per build, before all tasks of all projects, use this:
task('MyTask') << {
println 'Pre-build hook!'
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.MyTask)
task.dependsOn rootProject.tasks.MyTask
}
}
If you need the function/closure to be called only once per build, after all tasks of all projects, use this:
task('MyTask') << {
println 'Post-build hook!'
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.MyTask)
task.finalizedBy rootProject.tasks.MyTask
}
}

What's wrong with invoking it straight from the root build.gradle?
task init << {
println "I always run"
}
tasks.init.execute()

Related

How to run certain task with gradle

I try to investigate a Gradle and follows some tutorials, but I have confused with the following:
I created are a couple of simple tasks:
task startProcess{
println 'startProcess'
}
task doStep2{
println 'Step2'
}
task doStep3{
println 'Step3'
}
task finishProcess{
println 'finishProcesss'
}
And try to execute one of them:
gradle finishProcess
Or with defaultTasks with command gradle build:
defaultTasks `finishProcess`
task startProcess{
println 'startProcess'
}
task doStep2{
println 'Step2'
}
task doStep3{
println 'Step3'
}
task finishProcess{
println 'finishProcesss'
}
In both options, I got the same result:
> Configure project :
startProcess
Step2
Step3
finishProcesss
BUILD SUCCESSFUL in 1s
How to execute exactly one of them?
You have to use register, I think if you did not use it, You're only asking Gradle to execute these tasks.
for example
tasks.register('startProcess') {
doLast {
println 'startProcess'
}
}
tasks.register('doStep2') {
doLast {
println 'Step2'
}
}
tasks.register('doStep3') {
doLast {
println 'Step3'
}
}
tasks.register('finishProcess') {
doLast {
println 'finishProcesss'
}
}
tasks.named("build") { finalizedBy("finishProcess") }
Registering these tasks, you will be able to call each one indivadually.
If you want to link a specific task, with a build task for example.
Then you can use finalizedBy like the following.
tasks.named("build") { finalizedBy("finishProcess") }
This will call the finishProcess task, whenever build is triggered.
I strongly recommend the official gradle documintation for more information about tasks.

Error using dependsOn to call task from another gradle file

I am working with a build.gradle file that has multiple ways to specify executions for a task - setup. To call a task from another gradle file - runtests.gradle, I created a task - testTask and added task dependency using dependsOn, but this implementation does not seem to work and giving out an error like :
Could not find property 'testTask' on root project 'GradleFile
My build file looks like this :
build.gradle
task setup(dependsOn: testTask) <<
{
println "In main execution"
}
// new task
task testTask(type: GradleBuild) {
if (getEnvironmentVariable('RUN_TEST').equalsIgnoreCase("true")) {
buildFile = "../Behave/runtests.gradle"
tasks = ['mainTask']
}
else {
println "Exiting runTests Task"
}
}
setup.doFirst {
println "In first execution"
}
setup.doLast {
println "In last execution"
}
D:\>gradle -q GradleFile/build.gradle setup
I am not looking to make much changes to existing tasks, so is there any other workaround I should try?
I have been through many links but could not find anything that suits this scenario. Looking for suggestions please.
Gradle is sensitive to the ordering of tasks in the build script if a task instance is given in the dependsOn. The task setup depends on task (instance) testTask which, at the moment the build script is compiled, doesn't exist yet. The most common options to solve the issue are:
Define task setup below testTask:
task testTask(type: GradleBuild) {
}
task setup(dependsOn: testTask) {
}
Use a relative path to the task, i.e. the task's name, in the dependsOn
task setup(dependsOn: 'testTask') {
}
task testTask(type: GradleBuild) {
}
Please find more details in Javadoc of Task.

Creating a task that runs before all other tasks in gradle

I need to create an initialize task that will run before all other task when I execute it.
task A {
println "Task A"
}
task initializer {
println "initialized"
}
If I execute gradle -q A, the output will be:
>initialized
>Task A
Now if i'll add:
task B {
println "Task B"
}
Execute gradle -q B, and I get:
>initialized
>Task B
So it doesn't matter which task I execute, it always get "initialized" first.
You can make every Task who's name is NOT 'initializer' depend on the 'initializer' task. Eg:
task initializer {
doLast { println "initializer" }
}
task task1() {
doLast { println "task1" }
}
// make every other task depend on 'initializer'
// matching() and all() are "live" so any tasks declared after this line will also depend on 'initializer'
tasks.matching { it.name != 'initializer' }.all { Task task ->
task.dependsOn initializer
}
task task2() {
doLast { println "task2" }
}
Or you could add a BuildListener (or use one of the convenience methods eg: Gradle.buildStarted(...))
Seems like you aim execution phase, and you want a task precursing each task or just run as a first task in the execution phase?
If you want a task to always execute in every project before each other task after its being evaluated you can add a closure to he main build.gradle:
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.YourTask)
task.dependsOn rootProject.tasks.YourTask
}
}
or
tasks.matching {it != YourTask}.all {it.dependsOn YourTask}
You can also use the Task Execution Graph to define the lifecycle. There are few ways of achieving your goal, depending on your needs and a project structure.
The previously suggested solution with dependsOn works fine, but I don't like about it that it changes and clutters the task dependencies. The first solution coming to my mind is using Gradle Initialization Scripts. They are really cool. But, the usage is a bit tedious: currently there is no way to have a default project-local Gradle init script. You have to either explicitly specify the script(s) on command line, or place them in USER_HOME/GRADLE_HOME.
So another solution (already briefliy mentioned by #lance-java) which can be used to run some initialization, like a init task/script, is "build listeners". Depending on how early/late the initialization code should run, I use one of these two:
gradle.afterProject {
println '=== initialized in afterProject'
}
or
gradle.taskGraph.whenReady {
println '=== initialized in taskGraph.whenReady'
}
Here the docs of the Gradle interface and of BuildListener.
Note that some of the events occur very early, and you probably can't use them because of that, like e.g. beforeProject and buildStarted (explanations here and there).

Running the same task multiple times during execution in gradle

Is it possible to have some like the following in gradle
task enableMe() << {
println "Enable"
}
task disableMe() << {
shouldRunAfter 'taskAwork'
println "Disable"
}
task taskAwork(){
shouldRunAfter 'enableMe'
println "do work in A while disabled"
}
task taskA(dependsOn: disableMe, taskAwork, enableMe){
}
task taskBwork(){
shouldRunAfter 'enableMe'
println "do work in B while disabled"
}
task taskB(dependsOn: disableMe, taskBwork, enableMe){
}
task taskC(dependsOn: taskA, taskB){
}
So that when it runs the tasks are executed in the order
disableMe
taskAwork
enableMe
disableMe
taskBwork
enableMe
but currently, disableMe and enableMe only run once.. is there anyway to set there status so that they can run again.
The only way I can think to do this is to duplicate the tasks;
task enableMeA() << {
println "Enable"
}
task disableMeA() << {
shouldRunAfter 'taskAwork'
println "Disable"
}
task enableMeB() << {
println "Enable"
}
task disableMeB() << {
shouldRunAfter 'taskBwork'
println "Disable"
}
task taskAwork(){
shouldRunAfter 'enableMeA'
println "do work in A while disabled"
}
task taskA(dependsOn: disableMeA, taskAwork, enableMeA){
}
task taskBwork(){
shouldRunAfter 'enableMeB'
println "do work in B while disabled"
}
task taskB(dependsOn: disableMeB, taskBwork, enableMeB){
}
task taskC(dependsOn: taskA, taskB){
}
Seems, in your case, you have to implement TaskExecutionListener for your task and use it's beforeExecute and afterExecute methods to implement your logic.
This could look something like:
task taskAwork() << {
println "do work in A while disabled"
}
task taskBwork() << {
println "do work in B while disabled"
}
task doAllWorkTask(dependsOn: [taskAwork, taskBwork]){
}
gradle.taskGraph.addTaskExecutionListener new WorkTasksExecutionListener()
class WorkTasksExecutionListener implements TaskExecutionListener {
#Override
void afterExecute(final Task task, final TaskState state) {
if (task.name.contains('work')) {
println('Enabling smth before execution of work task')
}
}
#Override
void beforeExecute(final Task task) {
if (task.name.contains('work')) {
println('Disabling smth after execution of work task')
}
}
}
Here is specified 2 tasks, which do something and requires some common loigic to be run before and after each one. To implement this common logic, used WorkTasksExecutionListener implementing TaskExecutionListener interface and registered as a listener in the taskGraph.
WorkTasksExecutionListener implenets 2 methods of the TaskExecutionListener: beforeExecute and afterExecute. This methods are getting called before and after each tsk execution, so in it's implementation was added the condition to check whether the task do some work and if yes, then some additional logic executed.
Output in this case will be:
:taskAwork
Enabling smth after execution of work task
do work in A while disabled
Disabling smth before execution of work task
:taskBwork
Enabling smth after execution of work task
do work in B while disabled
Disabling smth before execution of work task
:doAllWorkTask
Gradle, by default, will not run a task which is up-to-date.
Task is considered up-to-date if it's TaskOutputs property hasn't been changed.
If you want to run a task several times during the same execution, you can use upToDateWhen property to define a predicate that will return false whenever you want the task to run again:
task myTask() {
outputs.upToDateWhen {some_condition}
// Do some stuff
}

Gradle: run a clean up task at every execution (test, build, etc.)

I have a simple custom task that cleans up some local properties files to work for the given dev environment. I'd like Gradle to run this task every time I run any command, e.g., test, build, clean, etc.
Is there a way to do so?
The standard way is to declare the dependency on every task such as:
task myclean() << {
println "myclean"
}
task mytask1(dependsOn: myclean) << {
println "mytask1"
}
task mytask2(dependsOn: myclean) << {
println "mytask2"
}
Alternatively you can add a dependency to every task after they have been declared:
task myclean() << {
println "myclean"
}
task mytask1() << {
println "mytask1"
}
task mytask2() << {
println "mytask2"
}
projects.tasks.findAll { it != myclean }.each { it.dependsOn << myclean }

Resources