Is there a way to run checkstyle on only files that have changes in VCS?

android-gradle-plugin, checkstyle, git, gradle, java

Solution

Recently I wrote a tool based on checkstyle to support style checks only on incremental changes of code lines, and you can add this tool to your Git pre-commit hook to trigger the check before every commit.

For details please see: https://github.com/yangziwen/diff-checkstyle

Though it is too late for your question, I still hope this can help you in the future.

Problem

I've recently begun helping out a young team to help improve their development practices and wanted them to run checkstyle before every commit. Unfortunately, their code is littered with errors and the only scalable way to implement it would be to run checkstyle on a small portion of files each time. Strategically, I wanted to run checkstyle on only those files that have been modified in the VCS. I wrote a Gradle script to make this happen, but it doesn't seem to work. Does anyone have tips on how to make this happen? ``` apply plugin: 'checkstyle' def getChangedFiles = { -> try { def stdout = new ByteArrayOutputStream() exec { commandLine 'git', 'diff', '--name-only' standardOutput = stdout } return stdout.toString().trim().split("\n") } catch (ignored) { return null; } } task checkstyle(type: Checkstyle) { configFile file("${project.rootDir}/quality/checkstyle/uncommon-checkstyle.xml") configProperties = [ 'checkstyle.cache.file': rootProject.file('build/checkstyle.cache'), 'checkstyleSuppressionsPath': file("${project.rootDir}/quality/checkstyle/suppressions.xml").absolutePath ] source 'src' String[] split = getChangedFiles() for (int i=0; i<split.length; i++){ include split[i] println split[i] } exclude '**/build/**' // Exclude everything inside build folders. exclude '**/test/**' // Exclude tests exclude '**/androidTest/**' // Exclude android test files. ignoreFailures = false // Don't allow the build to continue if there are warnings. classpath = files() } checkstyle { toolVersion '6.19' // set Checkstyle version here } ``` The print commands show the right set of files are being returned by getChangedFiles() and I've checked to ensure the included files are accurate as well, but the checkstyle itself doesn't seem to run on them.

Original source