Skip to content

Instantly share code, notes, and snippets.

Last active Jan 27, 2022
What would you like to do?
Gradle task that runs detekt only over changed files
configurations { detekt }
dependencies { detekt "io.gitlab.arturbosch.detekt:detekt-cli:$detektVersion" }
task detektCi(type: JavaExec, group: "verification") {
description = "Run Kotlin static analysis on changed files."
group = "CI"
main = "io.gitlab.arturbosch.detekt.cli.Main"
classpath = configurations.detekt
doFirst {
def changedFilesList = getDiffedFilesFromBranch("main")
if (changedFilesList.isEmpty()) {
println("No kotlin files changed! Skipping task...")
// forces detekt to ignore all files
changedFilesList = "$rootDir/gradle"
} else {
println("Running detekt on the changed files:")
def reportDir = "${buildDir}/reports/detekt"
def params = [
"--input", "$changedFilesList",
"--excludes", "!**/src/**/*Test.kt, **/spotless.kt",
"--config", "$rootDir/ci-cd/detekt-config.yml",
"--report", "xml:$reportDir/detekt-checkstyle.xml",
"--report", "html:$reportDir/report.html"
private static String getDiffedFilesFromBranch(String branch) {
def outputStream = new ByteArrayOutputStream()
def cmd = "git diff --diff-filter=d --name-only origin/$branch --relative | grep '\\.kt\\?\$'"
execute(cmd, outputStream)
if (outputStream.toString().isEmpty()) return ""
// get comma separated string of files
return outputStream.toString()
.replace("\n", ",")
private static def execute(cmd, output) {
['sh', '-c', cmd].execute().waitForProcessOutput(output, System.err)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment