Stop your builds failing with git pre commit hooks
Have you ever happily pushed your latest piece of work ready for others to test only to have it fail the build on coding standards? If so, git pre commit hooks could be your friend!
by
saul.willers
/ 8 October 2020
It's pretty standard practice these days for CI build pipelines to include linting steps to ensure things like coding standards pass. Depending on how the build is configured, failing coding standards can result in the entire build failing.
Because linting is generally not resource intensive, running it locally can be a useful time saver. But it's an easy step to forget. Thankfully it can be automated to run before every git commit with a pre-commit hook.
First we need a script to fire before the commit. This is placed in the project repo somewhere like .git-hooks/pre-commit:
#!/bin/sh<br><br>make lint-php<br>exit $?
We use Makefiles to call our custom lint-php rule, but this could be a Robo command or any other task running which fires your coding standard check.
Next, the script needs to be executable:
chmod +x .git-hooks/pre-commit
Then let git know about this script by running the following command:
git config core.hooksPath .git-hooks
That's it, our coding standards check will now automatically run whenever we do a git commit and stop the commit from proceeding if there is a fail.
If you've got a WIP or something you wish to commit regardless of any errors use git commit --no-verify
Hopefully this saves you from pushing coding standard fails in the future.
Tagged