Last active
January 1, 2025 01:43
-
-
Save fejd/494091a8f93c0b3aa183d3064aabb5fd to your computer and use it in GitHub Desktop.
Gradle task for running checkstyle on changed files only
This file contains hidden or 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
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