Including Hooks in a Git Repository

Why Share Hooks?

For certain projects it may be useful to share git hooks with other team members. This can help to encourage the practice of development policies across a team. An example could be a hook to run unit tests before acceptance of a commit.

Configuration

By default hooks are stored in .git/hooks outside of the working tree and are thus not shared between users of the repository. The hooks can be included in a directory within the repository and then each developer can set Git up to use them.

Git versions >= 2.9 provide a helpful configuration option which changes the path Git looks for hooks in. This makes the setup very easy.

git config core.hooksPath <hooks-dir>

For earlier versions of Git symlinks can be created from the .git/hooks directory to the new hooks directory in the repository.

For example if we wish to enforce the use of a pre-commit hook we could set up a symlink as follows:

ln -sf ../../<hooks-dir>/pre-commit .git/hooks/pre-commit

A good way to make it easier for others to set up their repository is to include a script in the repository which creates the necessary configuration. This is especially true if you wish to set up more than one symlink or perform other commands for new users of the repository.

A Potential Drawback

One potential disadvantage of this approach is that checking out an old version of your code could result in you also using an earlier version of your hooks. If this may be a problem an alternative could be to version the hooks in a separate repository and supply a script to configure the project repository to use this repository as its hooks directory. Either way ensures the hooks are version controlled and easier to share across a team which can only be a positive.

Tags: Git