Git hooks are an easy way to have scripts execute based on specific events. Since this is just a simple introductory, we’ll only concern ourselves with a few hooks. Your scripts can do anything you imagine, just keep in mind that only a non-zero return status will stop the Git procedure from continuing.
- Called before your commit is written.
- Called before your push is accepted.
- Called after your commit is written.
- Called after your push is accepted.
Lets walk through an example. Pretend we have some small project with a few developers and we decided that we’ll set up some linting standards, to ensure the code base is formatted the same. We have a few options we could take:
- We trust our developers to run the linter before committing and pushing
- We use CICD to run our linting, which can block pull requests from merging
- We tap into git hooks to ensure all pushes are linted properly
For the sake of this dialogue, lets argue that option 3 above is the best solution for our team. We could look at the four events above and pick one that would work best for our developers. I’d pitch that we’d be choosing between
If we were to use
pre-commit, our linter would run every time our developer committed. Depending on the team, this may be considered a hassle, as the developers would have to satisfy the linter every time they commit. While the git history would always be clean, lets pretend like this would prove to be a hassle and result in our developers committing less often, which is a bad thing. That leaves us with
pre-receive, which would allow our devs to commit to their heart’s desire and only have to satisfy the linter upon pushing.
So how do we actual create our
pre-receive hook? Excellent question Greg. Inside the
.git folder in your project will be a
hooks folder. If you were to list that directory, you’ll see the following and more:
Each of these files is a sample commit. So for our sake, all we have to do is create a
pre-commit file and write our logic in there. Here’s an example
Now all we have to do is ensure our
pre-commit file is executable and we’re all set!
$ chmod +x pre-commit
In the future we’ll look at how to share these git hooks with our team mates!
As always, please reach out to me with any questions comments and feedback!