Table of Contents

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 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
  }
}