Pieter VDE
Pieter VDE

Reputation: 2235

Controlling Gradle task execution

In my build.gradle script, I have a lot of tasks, each depending on zero or more other tasks.

There are three 'main' tasks which can be called: moduleInstallation, backupFiles and restoreFiles.

Here's the question: I would like to be able to tell Gradle which tasks to execute and which don't need to execute. For example, when calling moduleInstallation, I want all depending tasks to execute (regardless of their UP-TO-DATE flag), but not the restore tasks. I've tried altering the phase in which the tasks get executed (e.g. config phase, execution phase,...) and a couple of other things, but all tasks just keep getting executed.

A solution I've thought of was just stating in the main tasks that, when this main task is called (f.e. moduleInstallation), we set the UP-TO-DATE flag of all non-related tasks to false, so they don't get executed. Is that possible?

EDIT: Here's an example:

When moduleInstallation is called (which depends on backupFiles), restoreFiles (which depends on restoreFromDate) is executed too.

First main action

task moduleInstallation << {
    println "Hello from moduleInstallation"
}

task backupFiles {
    doLast {
        println "Hello from backupFiles"
    }
}

Second main action

task restoreFiles {
    println "Hello from restoreFiles"
}

task restoreFromDate {
    println "Hello from restoreFromDate"
}

Dependencies:

moduleInstallation.dependsOn backupFiles 
restoreFiles.dependsOn restoreFromDate

So when I type gradle moduleInstallation in the terminal, I get the following output:

Hello from restoreFromDate
Hello from restoreFiles
Hello from backupFiles
Hello from moduleInstallation 

Upvotes: 0

Views: 3064

Answers (1)

Peter Niederwieser
Peter Niederwieser

Reputation: 123996

The second snippet has to use doLast (or its << shortcut) like the first snippet. Otherwise, the code is configuration code and will always be evaluated, no matter which tasks are eventually going to be executed. In other words, it's not the restoreFiles and restoreFromDate tasks that are being executed here (as one can tell from the bits of command line output that you don't show), but (only) their configuration code.

To better understand what's going on here (which is crucial for understanding Gradle), I recommend to study the Build Lifecycle chapter in the Gradle User Guide.

Upvotes: 3

Related Questions