Skip to main content
Version: Next

Run detekt using the Compiler Plugin

You can integrate detekt in your project using the Detekt Compiler Plugin instead of the classic Detekt Gradle Plugin. Detekt offers a compiler plugin for K1 which allows you to run detekt as part of the Kotlin compilation process using type resolution. This allows you to run detekt on your code without having separate tasks to invoke and results in much faster execution of detekt, especially if you use type resolution with the Gradle plugin.

caution

Please note that Detekt Compiler Plugin is an experimental extension of detekt. We expect it to be stable with the upcoming release of detekt (2.x)

Using the Compiler Plugin

To use the detekt Compiler Plugin, you will have to add the following Gradle Plugin:

plugins {
id("io.github.detekt.gradle.compiler-plugin") version "1.23.1"
}

Configuring the Compiler Plugin

The compiler plugin can be configured using the detekt{} block in your gradle file.

The following options are allowed:

detekt {
// Define the detekt configuration(s) you want to use.
// Defaults to the default detekt configuration.
config.setFrom("path/to/config.yml")

// Applies the config files on top of detekt's default config file. `false` by default.
buildUponDefaultConfig = false

// Turns on all the rules. `false` by default.
allRules = false

// Specifying a baseline file. All findings stored in this file in subsequent runs of detekt.
baseline = file("path/to/baseline.xml")

// Disables all default detekt rulesets and will only run detekt with custom rules
// defined in plugins passed in with `detektPlugins` configuration. `false` by default.
disableDefaultRuleSets = false

// Adds debug output during task execution. `false` by default.
debug = false

// Kill switch to turn off the Compiler Plugin execution entirely.
enableCompilerPlugin.set(true)
}

Moreover, detekt reports can be configured at the Kotlin Compilation tasks level as follows

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
detekt {
reports {
xml.enabled.set(true)
txt.enabled.set(false)
create("custom") {
enabled.set(false)
}
}
}
}

Adding third party plugins

As for the Detekt Gradle Plugin, you can add third party plugins to the Compiler Plugin using the detektPlugins configuration.

dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.1")
}

Running the Compiler Plugin

The compiler plugin will run during your compileKotlin tasks execution:

$ ./gradlew compileKotlin

> Task :example:compileKotlin
w: Analysis failed with 1 weighted issues.
w: file:///.../example/src/main/java/Sample.kt:4:17 MagicNumber: This expression contains a magic number. Consider defining it to a well named constant.

BUILD SUCCESSFUL in 1s
5 actionable tasks: 1 executed, 4 up-to-date

Known Issues

  1. The rule InvalidPackageDeclaration is known to not be working well with the Compiler Plugin #5747.