Installing git hooks stored in a project's repository

A project stored on a git repository might have its own useful hooks. These are usually stored in .git/hooks and are not committed to version control.

If these git hooks need to be shared between users then the following method can be used to ease installation for all contributors.

Firstly create a new directory in the repository called git-hooks or similar.

Then place all the git hooks specific to this project into this new directory and commit them to version control as normal.

Installation script

Next, create a script somewhere such as script/install_git_hooks.sh to install the git hooks:

#!/bin/bash
#Installs git hooks from repo into git dir, backing up older versions if different
set -e
echo "Installing git hooks..."
RUN_DATE=`date "+%Y%m%dT%H%M%SZ"`
DEST_DIR=".git/hooks"
SOURCE_DIR="git-hooks"

# Process all git hooks in the directory
for SOURCE in ${SOURCE_DIR}/*; do
SOURCE_NAME=`basename ${SOURCE}`
DESTINATION="${DEST_DIR}/${SOURCE_NAME}"

# If a hook of the same name already exists
if [ -e ${DESTINATION} ]; then

  # If the existing hook is different
  if ! cmp -s ${SOURCE} ${DESTINATION}; then
    DESTINATION_BACKUP="${DESTINATION}_backup_${RUN_DATE}"

    # Back it up
    mv -v ${DESTINATION} ${DESTINATION_BACKUP}
  fi

fi

cp -v ${SOURCE} ${DESTINATION}
done

The above script will check each file in the git-hooks directory and check if it is installed already for this project. If a different version of a hook is installed it will be backed up first.

This script should be executed by an initial build task such as from make or even by npm as follows.

Installing from NPM

Using the postinstall script with npm we can execute our git hook install script as soon as any packages have been installed. The section of a package.json shown below details this:

"scripts": {
  "postinstall": "script/install_git_hooks.sh"
},

The install script will now be run after npm install has finished.

Last updated: 01/06/2015