Intro to git hooks

Git hooks are scripts that Git executes before or after events such as: commit, push, and branch. Git hooks are ran locally and is a native feature so no additional dependencies.

Using hooks are really trivial and the scripts themselves are limited only by your imagination.

Below is a quick rundown on how to work with git hooks.

mkdir mygit-workflow
cd mygit-workflow
git init

Git init creates an empty repository and a handful of example hooks are copied into the .git\hooks directory. However these are disabled by default. Lets take a look at them.

cd .git\hooks\
ls
Name
----
applypatch-msg.sample
commit-msg.sample
post-commit.sample
post-receive.sample
post-update.sample
pre-applypatch.sample
pre-commit.sample
pre-push.sample
pre-rebase.sample
prepare-commit-msg.sample
update.sample

Now although these are just samples they can be pretty useful out of the box. For example if we take a look at the pre-commit.sample.

cat pre-commit.sample

This basically does a diff on the changed files and prevents you from checking in filenames with non-ascii characters. This can be helpful when a project is running over different platforms.

To enable one of the sample hooks. Just remove .sample from the filename.

mv pre-commit.sample pre-commit

These are the current hooks you can write a script to attach to:

Use cases

Like i've mentioned the usage of git hooks are limited only by imagination however I would advise to proceed with caution and remember to try and choose the right tool for the job. Just because you can, it doesn't always mean you should.

I've know of scenarios whereby teams use the post-receive hook to publish code to a production environment. Typically this isnt advised as there are better products/ solutions to manage your CI/CD strategy.

With this in mind, here are a couple.

  • pre-commit - Check commit message and enforce project message rules
  • post-commit - Create a slack notification to notify the team of pending changes to the remote.

Im going to follow this post up with a working example soon, until then you might find this one useful to get you started.