How to create a global git commit hook by Matt Venables
1 Enable git templates (This tells git to copy everything in ~/.git-templates to your per-project .git/ directory when you run git init):
git config --global init.templatedir '~/.git-templates'
2 Create a directory to hold the global hooks:
mkdir -p ~/.git-templates/hooks
3 Write your hooks in ~/.git-templates/hooks. For example, here's a post-merge hook (located in ~/.git-templates/hooks/post-merge):
vi ~/.git-templates/hooks/post-merge
#/usr/bin/env bash
# MIT © Sindre Sorhus - sindresorhus.com
# forked by Gianluca Guarini
# see https://gist.github.com/GianlucaGuarini/8001627
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
echo "$changed_files" | grep -E --quiet "$1" && eval "$2"
}
# `composer install` if the `composer.lock` file gets changed
# Using a fully qualified path to composer to make this work in SourceTree
check_run composer.lock "/usr/local/bin/composer install"
4 Make sure the hook is executable.
chmod a+x ~/.git-templates/hooks/post-merge
5 Repeat steps 3 and 4 above, but create a ~/.git-templates/hooks/post-checkout
file with the same contents so that this script is run whenever you checkout different branches.
6 Re-initialize git in each existing repo you'd like to use this in (NOTE if you already have a hook defined in your local git repo, this will not overwrite it):
git init
7 From now one, whenever you run git pull
, git merge XXXXXXX
, or git checkout
in your project, if there are changes to the composer.lock
file, the composer install
command will be run.