I am struggling to let a task only execute when a specific value is defined.
I'm using Gradle 3.5.
task signJar(type: SignJar, dependsOn: reobfJar) {
onlyIf {
project.hasProperty('mod_keystore')
}
keyStore = project.keyStore
alias = project.keyStoreAlias
storePass = project.keyStorePass
keyPass = project.keyStoreKeyPass
inputFile = jar.archivePath
outputFile = jar.archivePath
}
As you can see, I already tried the onlyIf statement, but the task still runs. This results into a crash:
Could not get unknown property 'keyStore' for root project 'JustAnotherEnergy' of type org.gradle.api.Project.
The property 'mod_keystore' is no where defined, but the code get's executed.
task signJar(type: SignJar, dependsOn: reobfJar) {
if(project.hasProperty('mod_keystore')) {
keyStore = project.keyStore
alias = project.keyStoreAlias
storePass = project.keyStorePass
keyPass = project.keyStoreKeyPass
inputFile = jar.archivePath
outputFile = jar.archivePath
}
}
This works. The code does not get executed, but I'm running into other problems: If the property 'mod_keystore' is not defined, Gradle can't set a value for the for example 'keyStore' property, but the task SignJar requires this values to be set.
This means this task should only be executed when the property 'mod_keystore' is defined. If it is not defined, the task should be skipped.
As you can see, I already tried the onlyIf statement, but the task still runs.
No, the task does not run. You need to distinguish between the configuration phase and the execution phase. The task closure, where you are setting your task properties, is executed during the configuration phase, right after the task is created. Only task actions (defined by the task type) and closures added via doFirst
or doLast
are executed during the execution phase.
If you disable or skip a task via onlyIf
or enabled
, you only disable / skip the execution (phase) of the task, not its configuration (phase).
As a solution for your specific problem, you can rely on your first approach with the onlyIf
condition, but add a fail-safe way to access your project properties:
task signJar(type: SignJar, dependsOn: reobfJar) {
onlyIf {
hasProperty('mod_keystore')
}
keyStore = findProperty('keyStore')
alias = findProperty('keyStoreAlias')
storePass = findProperty('keyStorePass')
keyPass = findProperty('keyStoreKeyPass')
inputFile = jar.archivePath
outputFile = jar.archivePath
}