Skip to content

Instantly share code, notes, and snippets.

@ealebed
Created February 6, 2020 09:19
Show Gist options
  • Save ealebed/b032ba09e31d9df50057f1b5e998f94e to your computer and use it in GitHub Desktop.
Save ealebed/b032ba09e31d9df50057f1b5e998f94e to your computer and use it in GitHub Desktop.
Gradle checkstyleOnlyChangedFiles task
import java.nio.file.Paths
plugins {
id 'checkstyle'
}
checkstyleMain {
source = 'src/main/java'
}
checkstyleTest {
source = 'src/test/java'
}
checkstyle {
toolVersion = '8.27'
ignoreFailures = true
showViolations = true
configFile = file("${rootDir}/.checkstyle/rules.xml")
reportsDir = file("${buildDir}/checkstyleReports")
}
task checkstyleChanged(type: Checkstyle) {
source "${project.rootDir}"
def changedFiles = getChangedFiles()
if (changedFiles) {
// include changed files only
include changedFiles
} else {
// if no changed Java files detected, exclude all
exclude "**/*"
}
classpath = files()
ignoreFailures = true
showViolations = true
// Cleanup previous generated reports
(new File(Paths.get("${buildDir}/checkstyleReports/changedFiles.html").toString())).delete()
(new File(Paths.get("${buildDir}/checkstyleReports/changedFiles.xml").toString())).delete()
// Define the output folder for the generated reports
reports {
html {
enabled true
destination rootProject.file("${buildDir}/checkstyleReports/changedFiles.html")
}
xml {
enabled true
destination rootProject.file("${buildDir}/checkstyleReports/changedFiles.xml")
}
}
}
def getChangedFiles() {
ByteArrayOutputStream systemOutStream = new ByteArrayOutputStream()
ArrayList<String> files = new ArrayList<>()
("git diff --name-only --diff-filter=d HEAD~1").execute().waitForProcessOutput(systemOutStream, System.err)
def allFiles = systemOutStream.toString().trim().split('\n')
systemOutStream.close()
// Collect only *.java-files from all changed files
for (file in allFiles) {
if (file.endsWith(".java")) {
files.add(file)
}
}
files
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment