Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gradle: calling a task from another task

Tags:

gradle

groovy

I am aware that the currently supported method for invoking a task from another task is to use dependsOn or finalizedBy, but I run into an issue with this.

I have a task, taskA, that is usable on it's own. I have another task, taskB, which, when called, will depend upon taskA. The problem is that taskB has additional conditions that require the task be skipped if they fail. Here is the workflow I am going for:

$ gradle taskA
:taskA

BUILD SUCCESSFUL
$ gradle taskB
checking condition 1... PASS
checking condition 2... PASS
:taskA
:taskB

BUILD SUCCESSFUL
$ gradle taskB
checking condition 1... PASS
checking condition 2... FAIL
:taskA SKIPPED
:taskB SKIPPED

BUILD SUCCESSFUL

If called directly, or as a doFirst or dependsOn or something from a different task, taskA should execute regardless of the conditions. But if taskB is called, the conditions must pass before taskA is executed. Here's what I've tried:

project.tasks.create(name: "taskB", type: MyTask, dependsOn: "taskA")
project.taskB{
  onlyIf {
    if (!conditionA()){
      return false
    }
    if (!conditionB()){
      return false
    }
    return true
  }
}

The problem here is that taskA will execute before the onlyIf is checked on taskB, so even if a condition fails, taskA will execute.

How can I accomplish this?

like image 982
ewok Avatar asked Dec 11 '25 05:12

ewok


1 Answers

It seems that it can be configured no sooner than after task's graph has been resolved. At the earlier stages all conditions will be evaluated on configuration phase which is too early. Have a look at this:

task a {
  doLast {
      println 'a'
  }
}

task b {
  dependsOn a
  doLast {
      println 'b'
  }
}

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(b)) {
        a.enabled = b.enabled = check1() && check2()
    }
}

boolean check1() {
  def ok = project.hasProperty('c')
  println "check 1: ${ok ? 'PASS' : 'FAIL'}"
  ok
}

boolean check2() {
  def ok = project.hasProperty('d')
  println "check 2: ${ok ? 'PASS' : 'FAIL'}"
  ok
}

And the output:

 ~/tutorial/stackoverflow/40850083/ [master] gradle a
:a
a

BUILD SUCCESSFUL

Total time: 1.728 secs

 ~/tutorial/stackoverflow/40850083/ [master] gradle b
check 1: FAIL
:a SKIPPED
:b SKIPPED

BUILD SUCCESSFUL

Total time: 1.739 secs

 ~/tutorial/stackoverflow/40850083/ [master] gradle b -Pc
check 1: PASS
check 2: FAIL
:a SKIPPED
:b SKIPPED

BUILD SUCCESSFUL

Total time: 1.714 secs

 ~/tutorial/stackoverflow/40850083/ [master] gradle b -Pc -Pd
check 1: PASS
check 2: PASS
:a
a
:b
b

BUILD SUCCESSFUL

Total time: 1.745 secs
like image 169
Opal Avatar answered Dec 14 '25 10:12

Opal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!