12

I added a task to my gradle project:

task deploy() {
    dependsOn "build"
    // excludeTask "test"  <-- something like this

    doFirst {
       // ...
    }
}

Now the build task always runs before the deploy task. This is fine because the build task has many steps included. Now I want to explicitly disable one of these included tasks.

Usually I disable it from command line with

gradle deploy -x test

How can I exclude the test task programmatically?

Opal
  • 81,889
  • 28
  • 189
  • 210
Marcel
  • 4,054
  • 5
  • 36
  • 50

3 Answers3

18

You need to configure tasks graph rather than configure the deploy task itself. Here's the piece of code you need:

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(deploy)) {
        test.enabled = false
    }
}

WARNING: this will skip the actions defined by the test task, it will NOT skip tasks that test depends on. Thus this is not the same behavior as passing -x test on the command line

Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76
Opal
  • 81,889
  • 28
  • 189
  • 210
  • Hi, I know this was answered a long time ago, but I am trying this now, using gradle 6.0.1 and I don't manage to get that working. My scenario is a bit different, would you be able to check https://stackoverflow.com/questions/60460651/gradle-custom-task-that-depends-on-build-task-without-testing? Thank you – user1002065 Feb 29 '20 at 19:20
  • Note that this will still execute tasks that `test` declared as depending on. Thus this is not the same behavior as passing `-x test` on the command line. I haven't found a way to skip a task and all its "dependencies", I would love to know one – Vic Seedoubleyew Feb 15 '21 at 17:02
3

I don't know what your deploy task does, but it probably just shouldn't depend on the 'build' task. The 'build' task is a very coarse grained lifecycle task that includes tons of stuff you probably don't want.

Instead it should correctly define its inputs (probably the artifacts that you wanna deploy) and then Gradle will only run the necessary tasks to build those inputs. Then you no longer need any excludes.

Stefan Oehme
  • 449
  • 2
  • 7
1

I ran into a similar problem. Here is how I prevent "test" from running when I run "intTest" and want the ITs to run alone:

test {
    onlyIf { !gradle.startParameter.taskNames.contains("intTest") }
}

An alternative that doesn't depend on certain tasks being run explicitly:

test {
    onlyIf { !gradle.taskGraph.hasTask(":intTest") || gradle.taskGraph.hasTask(":check") }
}
Lucas Ross
  • 1,049
  • 8
  • 17