git hooks

Posted December 31, 2020 by Adrian Wyssmann ‐ 2 min read

git

Did you ever pushed stuff to a git repo and then breaking your branch, just cause you did not checked beforehand, if all is fine. I'm sure you did. Wouldn't it be just cool if some checks ran automatically before committing or pushing?

With git you have this already at your hand with git-hooks: Git will fire off custom scripts when certain actions occur.

The scripts are to be placed under the hooks subdirectory i.e. .git/hooks. Alternatively you can also configure an alternative hooksPath e.g. by executing git config core.hooksPath path/to/the/scripts. The script file can be anything from bash to python, as long as it’s executable and is named after the hook. For example the script for the pre-commit hook is named pre-commit. When you initialized your git repo with git init you can find some examples under .git/hooks. The hook is considered successful if returns a zero and unsuccessful when returning non-zero.

The most important actions/hooks are the following ones - checkout https://www.git-scm.com/docs/githooks for a complete list:

You should also be aware that there are client-side hooks and server-side hooks. As per documentation they are divided into 3 categories: committing-workflow hooks, email-workflow scripts, and everything else. As mentioned above, client-side hooks live in a directory on the developers machine, thus they are not copied when cloning a repository and thus also not shared among developers.

So if you want to enforce certain policies for all developers you could use server-side hooks . The have to be configure by an administrator on the file system of the git server - see for example Gitlab Server Hooks. Server-side hooks run before and after pushes to the server - I’ve marked them in the list above explicitly.

However sometimes as a developer you want certain checks happen before one pushes the work to the server, so client-side is the better approach. But how to share git-hooks? Well there are a lot of generic and language-specific solution to manage git-hooks. Have a look at the list at projects at https://githooks.com/ which shows a nice lists of some existing solutions.

I recommend to look into the different tools/projects, they are quite interesting and I am sure you find one that suites you.