Original article: https://www.ethancarlsson.dev/blog/githooks
If you're looking to set up a simple way to run
code before each commit in a
pre-commit hook for
Hooks don't actually depend on anything other than git, but
yarn in this project.
It would work the same with any build tool,
and if you use
npm just replace
yarn [command] with
npm run [command].
For the hook to work you need to write this code in
So to get started write one of the following into your
terminal from your project root:
For VS Code:
Or create and edit the file in whatever other way you like.
#!/bin/bash yarn lint linting_result=$? if [[ $linting_result -ne 0 ]] then echo "LINT FAILED!" echo 'Please fix linting problems before committing.' exit 1 fi yarn test test_result=$? if [[ $test_result -ne 0 ]] then echo "TESTS FAILED!" echo 'Please make sure tests pass before committing.' exit 1 fi
yarn test and
yarn lint commands work exactly the same as
they do when called from the command line at the root of my project.
I get the exit code and check to see if it equals zero here:
linting_result=$? if [[ $linting_result -ne 0 ]]
if it doesn't equal 0 (
-ne 0), I echo a message
and exit the bash code with another non-zero exit code,
then echo "LINT FAILED!" echo 'Please fix linting problems before committing.' exit 1 fi
If either the tests or the linter fail they exit
with a code of 1. But if it exits with a different code
I'd like to know why, so I exit with anything non-zero and don't
let the commit go forward.
All you need to do now is run
chmod +x .git/hooks/pre-commit, to make the code executable,
and the code will run on every commit.
Check out the documentation and add
whatever other hooks you like. I run the same code on push as well using
pre-push hook for example