How to skip a task if another task is executed in Gradle?

About

This page shows you how you can skip a task if another task is executed.

It can happen in a test development when you have some build task you don't want to execute in a dev setting but that you want to execute for a release or a test.

Example

  • The example below is written in kotlin
  • We will skip the task if the release task is not started.

The task to skip

This is a simple exec task that logs the word hello world

val halloWorldTask = tasks.register<Exec>("HelloWorld") {
   commandLine("cmd", "/c", "echo", "hello world")
}

The calling task

This task includes the dependent task based on a conditional value.

The conditional is true only if the task release is asked from the command line.

tasks.register<Exec>("ConditionalTask") {
  // gradle.startParameter.taskNames contains the name of tasks given at the command line
  val gradleReleaseTaskStarted = gradle.startParameter.taskNames.contains("release")
  if (gradleReleaseTaskStarted) {
    dependsOn(halloWorldTask)
  }
  commandLine("cmd", "/c", "echo", "hello from conditional")
}

Excluding the calling task

You can even go further and exclude the calling task

tasks.register<Exec>("ConditionalTask") {
  // gradle.startParameter.taskNames contains the name of tasks given at the command line
  val gradleReleaseTaskStarted = gradle.startParameter.taskNames.contains("release")
  if (gradleReleaseTaskStarted) {
    dependsOn(halloWorldTask)
  }
  commandLine("cmd", "/c", "echo", "hello from conditional")
  onlyIf {
     gradleReleaseTaskStarted
  }
}





Discover More
Gradle - Task

A build process execute a graph of tasks. Task may just be: container (lifecycle task) or provided by plugin In execution with the wrapper of the project Tasks themselves consist of:...



Share this page:
Follow us:
Task Runner