How to share Git hooks between multiple repositories

Share Git hooks between multiple repositories.

Use global Git hooks directory

This configuration will apply to every Git repository.

Create Git hooks directory.

$ mkdir -p ~/.git/hooks

Copy Git hooks to this directory, for example recently created Git hook to add Jira issue ID to the commit message.

Define global Git hooks directory.

$ git config --global core.hooksPath ~/.git/hooks

Inspect local Git configuration.

$ cat ~/.gitconfig 
[user]
        name = Milosz
        email = [email protected]
[core]
        hooksPath = /home/milosz/.git/hooks

From now on you will use only Git hooks from defined directory.

$ mkdir test-repo
$ cd test-repo/
$ git init
Initialized empty Git repository in /home/milosz/Projects/test-repo/.git/
$ git commit -m "init" --allow-empty
[master (root-commit) 24a9da6] init
$ git checkout -b "SMART-0001"
Switched to a new branch 'SMART-0001'
$ git commit -m "branch test" --allow-empty
[SMART-0001 63ce23c] SMART-0001: branch test

Use Git templates directory

This configuration can be used on per-repository basis.

Create Git templates directory.

$ mkdir -p ~/.git/templates

Copy Git hooks to this directory, for example recently created Git hook to add Jira issue ID to the commit message.

Define Git templates directory.

$ git config --global init.templatedir ~/.git/templates/hooks

Inspect local Git configuration.

$ cat ~/.gitconfig 
[user]
        name = Milosz
        email = [email protected]
[init]
        templatedir = /home/milosz/.git/templates

From now on you need to initialize new or reinitialize existing Git repository to copy Git hooks from template directory.

$ cd Projects/test-repo/
$ ls .git/hooks/
applypatch-msg.sample  fsmonitor-watchman.sample  pre-applypatch.sample  prepare-commit-msg.sample  pre-rebase.sample   update.sample
commit-msg.sample      post-update.sample         pre-commit.sample      pre-push.sample            pre-receive.sample
$ git init
Reinitialized existing Git repository in /home/milosz/temp/test-repo/.git/
$ ls .git/hooks/
applypatch-msg.sample  commit-msg.sample          post-update.sample     pre-commit.sample          pre-push.sample    pre-receive.sample
commit-msg             fsmonitor-watchman.sample  pre-applypatch.sample  prepare-commit-msg.sample  pre-rebase.sample  update.sample
$ git checkout -b "SMART-0002"
Switched to a new branch 'SMART-0002'
$ git commit -m "branch test" --allow-empty
[SMART-0002 f2a275d] SMART-0002: branch test

Additional notes

githooks - Hooks used by Git

git-config - Get and set repository or global options

git-init - Create an empty Git repository or reinitialize an existing one