Member-only story
No more failing builds!
Prevent red builds on your CI with Git Hooks

Have you ever pushed a commit without running unit tests locally? Probably, the answer is yes and your CI turned red.
This happens to everyone — it’s virtually impossible to remember to do it manually every time.
Thankfully, GIT has a brilliant feature called Hooks. With Hooks, we can trigger scripts before or after certain actions in our repository, check our code, use some APIs, log something, or do anything else we wish.
We want to use a custom Git Hook that will reject new commits if our unit tests fail. We’ll run unit tests each time just before committing and check if the result is positive. Unit tests should be lightweight and fast, so they should not influence our workflow too much. This approach would be much more problematic with integration or e2e tests. We don’t recommend automatically running these before each commit.
We start by creating the hooks
directory and pre-commit
script in .git folder at the root of the project. This is a directory used locally by GIT.
mkdir .git/hooks
touch .git/hooks/pre-commit
This is very straightforward and only fires the script pre-commit.sh
script in the root directory.
#!/usr/bin/env bash./pre-commit.sh
Now let’s create a run_tests.sh
script that will run unit tests. This file will look different depending on the tools we use. In Python, this file could look like this:
# Pytest
py.test test# unittest
python -m unittest
If we were using PHP, depending on the tools we choose it could be:
# PHPUnit
phpunit test# Codeception
php vendor/bin/codecept run unit
pre-commit.sh
is the brain of the whole operation:
#!/usr/bin/env bash
./run_tests.sh
RESULT=$?
if [[ ${RESULT} -ne 0 ]]
then
RED='\033[0;31m'
printf "${RED}Unit tests failed. Commit rejected"
fi
exit ${RESULT}
In bash =$?
gives us the status code of the last executed script. We then checked if the result was something other than 0. Exit code 0 means there were no errors — all tests passed. If the unit tests fail we print a proper message in red to make it look more serious.
This was very little work and gave us a nice feature that can be really helpful in day-to-day development. The full source code is available here: