Git – Applying a git post-commit hook to all current and future repos

gitgithookshook

I've written a Git post-commit hook and it works correctly. However, I want to add this hook to apply to all current (and future) git repositories I am working on. I tried adding the hook to my ~/.git/hooks/ instead of in the hooks directory in the project directory, however, this did not seem to work.

Is there any way to create global Git hooks that will apply to all repositories on my system (without having to copy them into each project directory)? If not, what would be the best solution going forward — perhaps a git-init template?

Best Answer

As of git 1.7.1, you can set init.templatedir in your gitconfig to tell git where to look for templates.

Set it like this:

git config --global init.templatedir '~/.git_template'

Afterward, new repositories you create or clone will use this directory for templates. Place the hooks you want in ~/.git_template/hooks. Existing repositories can be reinitialized with the proper templates by running git init in the same directory .git is in.

For git versions older than 1.7.1, running git init --template ~/.git_template will work if you're like me and still want to manage your .git_template dir along with the rest of your dot files. You can also use the $GIT_TEMPLATE_DIR environment to tell git init where your template directory is.