Reputation: 10335
I'm trying to add two "setup" and "cleanup" tasks that should be executed at the beginning and at the end of the build only if the build is invoked via a certain task.
In the following example, the setupTask
and cleanupTask
should only be executed, at the beginning and at the end of the build, if and only if the build was launched by the releaseX
task.
The line marked with (1)
makes the releaseX
task depend on the corresponding assembleX
task, so that a standard Android build is produced.
The line marked with (2)
is the key line that should make setupTask
to be invoked at the beginning of the build. This is the line for which I'm asking for help, because setupTask
is always invoked, and not only when launching the build via releaseX
as I would like.
The line marked with (3)
performs the cleanup jobs at the end of the build.
Can you help me?
apply plugin: 'com.android.application'
android {
//...
defaultConfig {
//...
}
signingConfigs {
//...
}
productFlavors {
//...
}
buildTypes {
//...
}
}
android.applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
def flavor = variant.productFlavors[0]
def releaseTask = tasks.create(name: "release" + flavor.name.capitalize(), type: Copy) << {
//...
}
releaseTask.dependsOn variant.assemble // (1)
variant.preBuild.dependsOn setupTask // (2)
releaseTask.finalizedBy cleanupTask // (3)
}
}
task setupTask << {
// ...
}
task cleanupTask << {
// ...
}
dependencies {
// ...
}
Upvotes: 1
Views: 765
Reputation: 10335
Another way is the following, albeit much less elegant than Henry's answer.
The dependency of preBuild
on setupTask
is always declared, but setupTask
is disabled if the task graph doesn't contain a releaseX
task.
android.applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
def flavor = variant.productFlavors[0]
def releaseTask = tasks.create(name: "release" + flavor.name.capitalize(), type: Copy) << {
//...
}
releaseTask.dependsOn variant.assemble
variant.preBuild.dependsOn setupTask
releaseTask.finalizedBy cleanupTask
gradle.taskGraph.whenReady {taskGraph ->
if (!(taskGraph.allTasks.any { it.name.startsWith("release") })) {
setupTask.enabled = false
}
}
}
}
Upvotes: 0
Reputation: 43738
You can specify, that releaseTask.dependsOn setupTask and that variant.preBuild.mustRunAfter setupTask.
The mustRunAfter specifies an ordering but not a dependency.
I did not try that, it may or may not work.
Upvotes: 2