Create a global git commit hook

Recently found out about these git hooks and they work flawlessly but my only worry was that I had to copy all my hooks over every repo such that I could use them, which was a pain sometimes.

Then started reading about this so called global git hooks, and found a fix.

Usually the default template library is found at /usr/share/git-core/templates and we are going to use that directory for all our hooks.

1. Enable git templates:

git config --global init.templatedir '/usr/share/git-core/templates/'

This tells git to copy everything in /usr/share/git-core/templates/ to your per-project .git/ directory when you run git init.

2. Write your hooks in /usr/share/git-core/templates/hooks.

For example, here's an update hook (located in /usr/share/git-core/templates/hooks/update):


#!/bin/sh
# Prevent pushing changes to master branch
if [ $USER != "mmphego" ];
then
  if [ "$1" == refs/heads/master ];
  then
    echo "Manual pushing to this repo is restricted"
    exit 1
  fi
fi
4. Make sure the hook is executable.

chmod a+x /usr/share/git-core/templates/hooks/update

5. Re-initialize git in each existing repo you'd like to use this in:

git init

NOTE if you already have a hook defined in your local git repo, this will not overwrite it.