Last active
April 22, 2024 11:14
-
-
Save iurysza/dada9047da83d101a6c4b63ed8407cb3 to your computer and use it in GitHub Desktop.
Gradle task that runs ktlint only over changed files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
configurations { ktlint } | |
dependencies { ktlint "com.pinterest:ktlint:$ktlintVersion" } | |
task ktlintCi(type: JavaExec, group: "verification") { | |
description = "Run Kotlin linter on changed files." | |
group = "CI" | |
main = "com.pinterest.ktlint.Main" | |
classpath = configurations.ktlint | |
doFirst { | |
def changedFilesList = getDiffedFilesFromBranch("main") | |
def ignoredFiles = "!**/src/**/*Test.kt" | |
if (changedFilesList.isEmpty()) { | |
println("No kotlin files changed! Ignoring all files...") | |
ignoredFiles = "!**/src/**" | |
} else { | |
println("Running ktlint on the changed files:") | |
changedFilesList.each { println(it) } | |
} | |
def reportDir = "$buildDir/reports/ktlint" | |
def params = [ | |
*changedFilesList, | |
ignoredFiles, | |
"--format", | |
"--relative", | |
"--reporter=checkstyle,output=$reportDir/ktlint-checkstyle.xml", | |
"--reporter=html,output=$reportDir/report.html" | |
] | |
args(params) | |
} | |
} | |
private static List<String> getDiffedFilesFromBranch(String branch) { | |
def cmd = "git diff --diff-filter=d --name-only origin/$branch --relative | grep '\\.kt\\?\$'" | |
def outputStream = new ByteArrayOutputStream() | |
['sh', '-c', cmd].execute().waitForProcessOutput(outputStream, System.err) | |
return mapOutputToStringList(outputStream) | |
} | |
//get double quoted, comma separated list of files | |
private static List<GString> mapOutputToStringList(ByteArrayOutputStream outputStream) { | |
if (outputStream.toString().isEmpty()) return [] | |
return outputStream.toString() | |
.split("\\.kt\n") | |
.collect { "${it}.kt" } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!