Search code examples
gradlebuild.gradle

Gradle Task Ordering with dependsOn mustRunAfter and doLast


I am working on creating a .gradle file to automate a bunch of manual operations during my project build.

I am trying to enforce task ordering using dependsOn, mustRunAfter, and doLast. However, I am not getting the desired output.

Here is my .gradle file with some dummy tasks and print statements to show what I have.

tasks.register('setupProjectTasks') {
    println 'Debug 1 sPT'
    dependsOn 'task1'
    doLast {
        exec {
            println 'Run shell script'
            commandLine '/path/a.sh'
        }
    }
}

tasks.register('task1') {
    println 'Debug 2 task'
    dependsOn 'someCleanup'
    dependsOn 'depA'
    tasks.findByName('depA').mustRunAfter('someCleanup')
    doLast {
        println 'restart' // Restart tomcat here
    }
}

tasks.register('someCleanup') {
    println 'Debug 3 some cleanup'
    dependsOn 'subTask1'
    dependsOn 'subTask2'
}

tasks.register('depA') {
    println 'depA'
    dependsOn 'subTaskA1'
    dependsOn 'subTaskA2'
    tasks.findByName('subTaskA2').mustRunAfter('subTaskA1')
    doLast {
        println 'depA done'
    }
}

tasks.register('subTask1') {
    println 'subtask 1'
}

tasks.register('subTask2') {
    println 'subtask 2'
}

tasks.register('subTaskA1') {
    println 'subtask A1'
}

tasks.register('subTaskA2') {
    println 'subtask A2'
}

This is the task order I wish to achieve.

- setupProjectTasks
  - task1 (First 'someCleanup', and then 'depA', and 'restart' at the end
    - someCleanup (the order between subTask1 and subTask2 doesn't matter)
    - depA (below should be executed in the exact order)
      - subTaskA1
      - subTaskA2
      - depA done (print line)
    - restart (print line)
  - Run shell script (print line and run shell script)

I always want to run all these tasks in the order specified. I understand how dependsOn and mustRunAfter works. But I don't seem to have them working the right way for me.

This is the output I get

Debug 1 sPT
Debug 2 task
depA
subtask A2
Debug 3 some cleanup
subtask A1
subtask 1
subtask 2

> Task :depA
depA done

> Task :task1
restart

> Task :setupProjectTasks
Run shell script
Hi

What am I missing here? Thanks in advance!


Solution

  • I suppose you misunderstood Gradle and its concept of tasks. Because tasks in Gradle cannot have hierarchy. Also you don't have the ability to run tasks inside another tasks. The task in Gradle should do one small or possibly big thing.

    Maybe it would be better to use methods instead of tasks.

    To order tasks you just need to use dependsOn. Here is an example that I created for you to show how could it be - link.