How to automate coding standards and enforce code coverage, code quality and code security in a Java project.
Goal:
- Format the code automatically as per Google Java Style Guide.
- Run test cases in the corresponding maven module and fail the commit, if minimum required code coverage is not met.
- Run static code analysis on staged files and fail the commit, if there are any critical issues.
Configuration required:
Define below plugins inpom.xml.
- Define
git-build-hook-maven-pluginplugin.- Define
maven-git-code-formatplugin.- Define
spotbugs-maven-pluginplugin.- Create
pre-commit.shfile in the root directory of the maven module and give it execute permission by runningchmod +x pre-commit.sh
How does it work?
- Run
mvn clean install
> - During maven life cycleinstallphase, content ofpre-commit.shwill be copied topre-commitfile in.git/hooksdirectory.- When files are committed pre-commit hook will be invoked by git and if the script returns a non zero exit code, commit will be failed.
Reference:
- Pre-commit hooks for maven project. https://github.com/rudikershaw/git-build-hook
- Code formatting as per Google Java StyleGuide.
- Code Coverage Check https://www.eclemma.org/jacoco/
- Code Quality and Code Security: https://spotbugs.readthedocs.io/en/stable/index.html