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-plugin
plugin.- Define
maven-git-code-format
plugin.- Define
spotbugs-maven-plugin
plugin.- Create
pre-commit.sh
file 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 cycleinstall
phase, content ofpre-commit.sh
will be copied topre-commit
file in.git/hooks
directory.- 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