5

I have added Detekt to my Gradle project. My intention was to invoke detekt on demand only, since it creates a lot of false positives. However, the detekt task is active by default (and breaks the build). How can I avoid this dependency?

What I tried: I have added a gradle.taskGraph.beforeTask block that sets enabled = false conditionally:

gradle.taskGraph.beforeTask {
    val containsDetektTaskCall = gradle.startParameter.taskNames.contains("detekt")
    if (name.startsWith("detekt") && !containsDetektTaskCall) {
        logger.lifecycle("Skipping all 'detekt-plugin' tasks")
        enabled = false
    }
}

I have the feeling that these 7 lines of code are really a bit much just to override a task dependency. I would appreciate a general Gradle answer as well as some Detekt-specific way.

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112

1 Answers1

4

There are a lot of ways to skip the task. The easiest one is to add onlyIf condition for your task. For example:

task detect {
    doFirst {
        println 'detect'
    }
}

detect.onlyIf { project.hasProperty('runDetect') }

The detect task will be executed only when the onlyIf condition is true.

./gradlew detect -PrunDetect

Please take a look here for details https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:skipping_tasks

Max
  • 766
  • 9
  • 19
  • 4
    For reference: For the Kotlin DSL, it’s `tasks.getByPath("detekt").onlyIf { project.hasProperty("runDetekt") }`. – Michael Piefel Nov 28 '19 at 09:41
  • 4
    And, better still, since it is awkward to add one more command line parameter: `tasks.getByPath("detekt").onlyIf { gradle.startParameter.taskNames.contains("detekt") }` – Michael Piefel Nov 28 '19 at 09:45
  • Yet better, you can put it in any order or any subproject (like :mysubproject:detekt): `tasks.getByPath("detekt").onlyIf { gradle.startParameter.taskNames.any { it.contains("detekt") } } ` – cocorossello Aug 14 '21 at 16:42