Skip to content

Instantly share code, notes, and snippets.

@fejd
Last active February 6, 2020 09:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fejd/494091a8f93c0b3aa183d3064aabb5fd to your computer and use it in GitHub Desktop.
Save fejd/494091a8f93c0b3aa183d3064aabb5fd to your computer and use it in GitHub Desktop.
Gradle task for running checkstyle on changed files only
checkstyle {
toolVersion = "7.0"
ignoreFailures = true
configFile rootProject.file("checkstyle/checkstyle.xml")
configProperties = [ "checkstyleFilterFile" : file('checkstyle/filter.xml')]
}
task checkstyleChanged(type: Checkstyle, dependsOn: 'copyChangedFilesForCheckstyle') {
source 'changedfiles'
include '**/*.java'
classpath = files()
ignoreFailures = true
showViolations = true
reports {
html {
destination "${project.rootDir}/build/reports/checkstyle/checkstyle_changed.html"
}
xml {
destination "${project.rootDir}/build/reports/checkstyle/checkstyle_changed.xml"
}
}
}
/**
* Compares the current set of changed files to HEAD and copies them to a temporary
* folder. This is a prerequisite to run checkstyle on changed files only.
*/
task copyChangedFilesForCheckstyle() {
doLast {
ByteArrayOutputStream systemOutStream = new ByteArrayOutputStream()
("git diff --name-status HEAD~1").execute().waitForProcessOutput(systemOutStream, System.err)
def allFiles = systemOutStream.toString().trim().split('\n')
systemOutStream.close()
Pattern statusPattern = Pattern.compile("([^D])\\t+(.+)")
// Contains all files that are not deleted
ArrayList<String> files = new ArrayList<>()
for (file in allFiles) {
Matcher matcher = statusPattern.matcher(file)
if (matcher.find()) {
files.add(matcher.group(2))
}
}
String dst = "./changedfiles/"
String rootDir = "./"
new File(dst).deleteDir()
mkdir(dst)
for (file in files) {
File srcFile = new File(rootDir + file)
if (!srcFile.exists()) {
continue
}
String dstFileName = dst + file
String dstDirOnly = dstFileName.substring(0, dstFileName.lastIndexOf("/"))
File dstDir = new File(dstDirOnly)
File dstFile = new File(dstFileName)
dstDir.mkdirs()
Files.copy(srcFile.toPath(), dstFile.toPath())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment