I got it working by using some Node JS tools. Here is what I have:
Node JS Packaged
package.json
file:
{
"version": "1.0.0",
"scripts": {
"prepare": "husky install",
"pre-commit": "./scripts/pre-commit-run"
},
"license": "ISC",
"devDependencies": {
"husky": "^8.0.1",
"lint-staged": "^13.0.3"
}
}
Lint Staged Config
lint-staged.config.js
file:
const path = require('path');
module.exports = {
'**/*.java': (javaFiles) => {
const linters = [];
for (let i = 0; i < javaFiles.length; i++) {
const filePath = javaFiles[i];
const fileName = path.parse(filePath).base;
linters.push(`npm run pre-commit -- ${fileName}`);
}
return linters;
}
}
Pre-Commit Script
I couldn't make it work with lint-staged only. If you find a way, please share ;)
pre-commit-run
file:
#!/usr/bin/env sh
mvn checkstyle:check -Dcheckstyle.includes="**\\/$1"
Pre-Commit Git Hook
.husky/pre-commit
file:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
echo "Running pre-commit hook"
npx lint-staged
Checkstyle Maven Plugin
pom.xml
file (the part that matters):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.2.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.7.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<!-- Properties for "mvn checkstyle:check" to execute as part of maven build
They are conflicting with properties of checkstyle:checkstyle
so only one set should be used
-->
<configuration>
<configLocation>checkstyle.xml</configLocation>
<logViolationsToConsole>true</logViolationsToConsole>
<consoleOutput>true</consoleOutput>
<failOnViolation>true</failOnViolation>
<failsOnError>true</failsOnError>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Specifying configuration here will take effect
on the execution of "mvn site",
but will NOT take effect on the execution of "mvn checkstyle:check"
or "mvn checkstyle:checkstyle"
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<failOnViolation>false</failOnViolation>
</configuration>
</plugin>
</plugins>
</reporting>
</project>