Setup pre-commit hook and check commit message
Git hooks are scripts that you can define to run automatically every time a particular event occurs in a Git repository. You can customise these scripts to trigger some actions at key points in the development life cycle.
This article is mainly about using git hooks to run quality check before adding a commit and check the commit message standards.
pre-commit to check coding convention:
Create a file to use as pre-commit hook, in this example, we setup the hook to run gradle checkStyle command.
mkdir git-hooks
touch git-hooks/pre-commit.sh
commit-msg.sh to check commit message standard
Create a file to use as commit-msg hook, in this example, we setup the hook to run check the commit message if it contains USxxxxx prefix using regex.
touch git-hooks/commit-msg.sh
Setup script to apply configuration to git repo
touch setup-pre-commit-hook.sh
Run setup command to apply hooks
sh ./setup-pre-commit-hook.sh
Check the config
After setting up all the hooks needed, we can perform a simple check by changing the code and try to commit
git commit -a -m “Invalid commit message”
You may see this error message: