'Run both local and global git hooks

I have a global git hook post-commit which is situated under:

~/.git_templates/hooks/post-commit

I have made it global by

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

and using git init to update the settings for my git project.

Yet one project had its own post-commit hook under:

~/src/git.repo/.git/hooks/post-commit

The local one ran but prevented the global one from running. How can I achieve that both are run on post commit?

I want to avoid adding the command in the local post commit hook.



Solution 1:[1]

A possible workaround would be:

  • to make sure your global hook is deployed for all your users
  • modify your global hook to call a pre-agreed script which can be set by the users if they want to. For instance $GIT_DIR/hooks/my-post-commit

my-post-commit is not a standard client-side hook name, so it won't be run automatically by Git.
Only your global hook will, and it will call the client custom script setup by the user.

That doesn't change the fact that, if a local $GIT_DIR/hooks/post-commit does exist, that would still prevent your global hook to run.

Solution 2:[2]

You can set a global hook path.

git config --global core.hooksPath "$CONFIG_DIR/hooks"

This will ignore local hook?run global hook scripts only.

And if you want run both local & global hook, you can call local hook from global hook manualy.

For example: call this script from yout global pre-commit hook.

...
/path/to/run-local-hook pre-commit

run-local-hook file:

# Run local hook if exists
HOOK=$1
PROJECT_ROOT=$(git rev-parse --show-toplevel)

if [ -e "$PROJECT_ROOT/.git/hooks/$HOOK" ]; then
  $PROJECT_ROOT/.git/hooks/$HOOK "$@"
else
  exit 0
fi

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VonC
Solution 2