Why gradle runs all JavaExec tasks? - gradle

I defined two tasks in my build.gradle
task a(type: JavaExec) {
}
task b(type: JavaExec) {
}
When I execute task a, b also runs. Is this normal?
gradle a

I'm sharing my own experience for others.
I am a newbie on groovy/gradle.
What I tried to achieve was using a shared function for getting project properties.
def projectProperty = {
if (!project.hasProperty(it)) {
throw new Exception...
}
return project.getProperty(it);
}
task a(type: JavaExec) {
do some with projectProperty(a);
}
task b(type: JavaExec) {
do some with projectProperty(b);
}
And I changed like this.
task a(type: JavaExec) {
if (project.hasProperty('a')) {
do some with projectProperty('a');
}
}
task b(type: JavaExec) {
if (project.hasProperty('b')) {
do some with projectProperty('b');
}
}

Related

Stop execution of finalizedBy task, or only execute follow-up task on a condition

I'm using the com.google.cloud.tools.appengine gradle plugin, which has a task appengineDeploy.
I have two tasks that configure the appengineDeploy task before executing it. My current solution looks something like that:
task deployTest() {
doFirst {
appengine.deploy {
version = 'test'
...
}
}
finalizedBy appengineDeploy
}
task deployProduction() {
doFirst {
appengine.deploy {
version = '7'
...
}
}
finalizedBy appengineDeploy
}
Now I wanted to add a security question before the deployProduction task is executed, like this:
println "Are you sure? (y/n)"
def response = System.in.newReader().readLine()
if (response != 'y') {
throw new GradleException('Task execution stopped')
}
The problem is, by defintion the finalizedBy task is executed even if my task throws an exception, and that is exactly the opposite of what I want.
I can't change it to appengineDeploy dependsOn deployTest and call appengineDeploy as I have two tasks with different configuration.
And I can't change the appengineDeploy task as it comes from a plugin.
Is there any other way I can either stop the execution of appengineDeploy, or use something other than finalizedBy to execute that task after my deploy task?
One option is to leverage onlyIf to decide whether to execute the task, for example by examining a project property.
Here's a litte demo, given that task appengineDeploy is a task contributed by a plugin (see comment for details):
plugins {
id 'base'
}
ext {
set('doDeploy', false)
}
appengineDeploy.configure {
onlyIf {
project.ext.doDeploy
}
}
task deployTest() {
doFirst {
println 'deployTest()'
project.ext.doDeploy = true
}
finalizedBy appengineDeploy
}
task deployProduction() {
doFirst {
println 'deployProduction()'
println "Are you sure? (y/n)"
def response = System.in.newReader().readLine()
if (response == 'y') {
project.ext.doDeploy = true
}
}
finalizedBy appengineDeploy
}
Another option is to disable the task, which goes like this:
task deployProduction() {
doFirst {
println 'deployProduction()'
println "Are you sure? (y/n)"
def response = System.in.newReader().readLine()
if (response != 'y') {
project.tasks.appengineDeploy.enabled = false
}
}
finalizedBy appengineDeploy
}
I modified the answer from thokuest a bit (thanks for the help!), to prevent executing any tasks inbetween.
I created it as extension method since I needed it more than once:
ext.securityQuestion = { project, task ->
println "Are you sure you want to execute ${project.name}:${task.name}? (y/n)"
def response = System.in.newReader().readLine()
if (response != 'y') {
project.tasks.each {
if (it != task)
it.enabled = false
}
throw new GradleException("Execution of ${project.name}:${task.name} aborted")
}
}
and my task now looks like this:
task deployProduction() { task ->
doFirst {
securityQuestion(this, task)
}
finalizedBy appengineDeploy
}

How to create and use a gradle task factory function

How do I create a function that create function or maybe I should ask to call it
// cant use this method see comment tagged ERROR further down
def webRollbackFactory(parentTask) {
tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) {
onlyIf { patentTask.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.${parentTask.name}.doLast"
}
}
}
// this task which do the same works with out problems
task webRollback_webPublish(type: Copy) {
onlyIf { webPublish.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.webPublish.doLast"
}
}
task webPublish(type: com.ullink.Msbuild) {
dependsOn msbuild, webBackup
projectFile = "${webPublishProjectDir}/${webPublishProjectFileName}"
targets = ['Publish']
parameters = [PublishProfile: webPublishProfile]
configuration = BUILD_TYPE
parameters.maxcpucount
doLast {
println '\nwebPublish.doLast'
}
// ERROR: fails with: Could not find method webRollbackFactoy() for arguments [task ':webAccessTest'] on task ':webAccessTest' of type org.gradle.api.tasks.Exec.
//finalizedBy webRollbackFactory(webPublish)
// the version that works
finalizedBy webRollback_webPublish
}
I am on Gradle 4.8
The reason you get that error is because the closure being evaluated does not find the function declared in the main file.
Try changing your function to a closure as a variabe reference and then it should work.
webRollbackFactory = { parentTask ->
tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) {
onlyIf { patentTask.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.${parentTask.name}.doLast"
}
}
}

How can I reference the outputs of multiple tasks with one name?

Or in other words: How do I gather outputs of multiple tasks?
I have a project with a number of tasks whose output I want to include in the distribution.
I also have a task that depends on all of them.
How can I avoid listing all the tasks?
Example build.gradle:
plugins {
id 'distribution'
}
task taskA0 {
...
}
task taskA1 {
...
}
task taskA2 {
...
}
task allA {
dependsOn (taskA0, taskA1, taskA2)
}
distributions {
main {
contents {
// this works but is tedious
from taskA0
from taskA1
from taskA2
// this doesn't work, as allA doesn't have any output
from allA
}
}
}
How's this?
task allA {
dependsOn (taskA0, taskA1, taskA2)
outputs.files(taskA0, taskA1, taskA2)
}
distributions {
main {
contents {
from allA
}
}
}

gradle pass parameter to dependsOn task

I have 3 gradle tasks: A, B, C.
B dependsOn A.
C dependsOn A.
If have an if check in A that I want to be true when B runs, false when C runs.
How do I do that?
For clarity, the real tasks are:
war { // task A
webAppDirName = 'src/main/webapp'
if (flag) {
rootSpec.exclude("**/*.json")
rootSpec.exclude("**/*.xml")
}
}
ospackage { // task B
buildRpm {
dependsOn war
}
}
task localTomcat { // task C
dependsOn war
}
I tried setting war.flag, war.ext.flag before dependsOn, in a doFirst action, but nothing...
I found a solution using a dependsOn chain and mustRunAfter.
Code:
task war4pkg {
doLast {
war.rootSpec.exclude("**/*.json")
war.rootSpec.exclude("**/*.xml")
}
}
war {
webAppDirName = 'src/main/webapp'
}
ospackage {
buildRpm {
dependsOn war4pkg, war # order doesn't matter
war.mustRunAfter war4pkg # order set here
}
}
task localTomcat {
dependsOn war # nothing here.
}

gradle tasks.withType does not find tasks defined in other file

I have two gradle files, setup.gradle and tests.gradle; each having two gradle tasks of custom type 'EMTest';
test.gradle applies the 'setup.gradle' as apply from: 'setup.gradle'
I want to configure all tasks of type EMTest; For that I added below code at end of tests.gradle
tasks.withType(EMTest) {
println it.name
}
But this only prints the name of tasks in the tests.gradle;
When I run
tasks.all {
println it.name + " " + it.class
}
It however lists the tasks name defined in setup.gradle and the type as EMTest_Decorated (for all 4 types)
NOTE: I use gradle 1.11 (no control over upgrade); What is the issue here ?
UPDATE On 09/Jun
Here is the main file :
apply plugin: 'java';
apply plugin: 'maven'
apply from: 'emcpsrvs_3n_setup.gradle'
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo" }
}
dependencies {
classpath group:"com.mycompany.myprod.mymodule", name: "TestInfraPlugin", version: "${testinfraVersion}", transitive: true
classpath group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.9.13'
classpath group: 'com.mycompany.myprod', name: 'common',version:'0.1'
classpath group: 'org.codehaus.jackson', name: 'jackson-core-asl', version:'1.9.13'
classpath group: 'com.oracle.weblogic',name: 'jettison-1.1', version: '12.1.2-0-0'
}
}
repositories {
/* To check if the jar is available in local maven repository */
mavenLocal()
maven {
url = "${artifactory_contextUrl}/repo"
}
}
apply plugin: 'TestInfraPlugin'
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
testConfig group:'com.mycompany.myprod',name:'ui-integ-tests', version: '1.+'
testConfig group: 'com.mycompany.myprod', name: 'emaas-platform-tenant-sdk', version: '0.1+'
}
task unitTests(type: EMTest){
}
// Three tests are disabled due to JIRA-900
task tenantMgmtUITests(type: EMTest,dependsOn: [cleanSmall_deploy_3n_block,small_deploy_3n_block]) {
useWebdriver = true
small_deploy_3n_block.mustRunAfter ([cleanSmall_deploy_3n_block])
options.suiteXmlBuilder().suite('parallel': 'none','name': 'TenantManagementUI') {
test('name': 'TenantManagementUI') {
classes([:]) {
'class'('name': 'com.mycompany.package.MyTest')
}
}
}
}
small_deploy_3n_cleanup.mustRunAfter ([tenantMgmtUITests])
task emcpsrvs_tenant_mgmt_ui_3n(dependsOn: [tenantMgmtUITests,small_deploy_3n_cleanup])
Here is the 'emcpsrvs_3n_setup.gradle' which is being applied above
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
classpath group: 'com.mycompany.myprod.emdi', name: 'TestInfraPlugin', version: "${testinfraVersion}", transitive: true
}
}
apply plugin: 'TestInfraPlugin'
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
ext.integDeployVersion='1.1+'
dependencies {
testConfig group: 'com.mycompany.myprod.test', name: 'smalldeployment', version: "${integDeployVersion}"
}
/* Setup EMaaS Small Deployment */
task small_deploy_3n_block(type: EMTest) {
outputs.upToDateWhen { false }
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'setupEmaasSmallDeploy')
}
}
}
}
}
useWebdriver = true
useRestAssured = true
}
/* Cleanup EMaaS Small Deployment */
task small_deploy_3n_cleanup(type: EMTest) {
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'logCollectionAndPostCleanup')
}
}
}
}
}
mustRunAfter ([small_deploy_3n_block])
}
And finally here is the snippet from TestInfraPlugin.groovy (The gradle plugin):
logger.debug "Configuring the EMTest task with default values."
project.afterEvaluate {
project.ext.testClassesDir = new File(project.properties['emdi.T_WORK'] + '/testClasses')
def testTasks = project.tasks.withType(EMTest)
if (testTasks != null && testTasks.size() == 0) {
logger.info "There are no tasks of type EMTest."
return
}
def extractTask = project.tasks.findByPath('extractTestClasses') ?:
project.task('extractTestClasses', type: ExtractConfiguration) {
configuration = project.configurations.testConfig
to = project.testClassesDir
}
/*
* 1. Adding the 'extractTask' to all EMTest, to ensure that 'extractTask' is run before any 'EMTest'.
* 2. For lazy evaluation of lrgConfig, we are NOT running the task here, but just adding as dependent task.
*/
testTasks.each { task ->
logger.debug "Adding dependsOn extractTask for task: ${task.name}"
task.dependsOn extractTask
}
} // end afterEvaluate
}
What is afterEvaluate{} block doing:
It checks if there are any tasks of type EMTest and if there are creates a task to extract a configuration (named testConfig). This extract task is added as dependency on all the tasks of type EMTest such that the extract task run as first task before running any other task.
What is happening
The extractTestClasses task is added as dependency to ONLY the two tasks unitTests and tenantMgmtUITests and thus the small_deploy_3n_block is getting executed before extractTestClasses resulting setup to fail, which in turn results test to fail.
When you reference tasks with no object it is implicitly using project.tasks.
tasks.withType(EMTest) {
println it.name
}
That is why you'll only get tasks from your current project.
To include all projects you can use:
allprojects {
tasks.withType(EMTest) { println it.name }
}
In this closure you are referencing it.tasks, where it loops over every individual project.
This will not work as expected since Gradle will probably not have loaded all of your sub-projects at this point, and not have reached every task define found during the full configuration phase. Therefore you must define the closure to run after all the projects are fully evaluated:
allprojects {
afterEvaluate {
tasks.withType(EMTest) { println it.name }
}
}

Resources