Skip to content

Instantly share code, notes, and snippets.

@damienrg
Last active November 24, 2023 14:22
Show Gist options
  • Save damienrg/411f63a5120206bb887929f4830ad0d0 to your computer and use it in GitHub Desktop.
Save damienrg/411f63a5120206bb887929f4830ad0d0 to your computer and use it in GitHub Desktop.
Script to allow multi hooks per hook type for git
#!/usr/bin/env bash
# Allow multiple hooks.
#
# To use it copy this script with executable permission in ".git/hooks/hook-name"
# where hook-name is the name of the hook (see man githooks to know available hooks).
# Then place your scripts with executable permission in ".git/hooks/hook-name.d/".
hook_type=${BASH_SOURCE##*/}
case "$hook_type" in
applypatch-msg \
|commit-msg \
|fsmonitor-watchman \
|post-checkout \
|post-commit \
|post-merge \
|post-update \
|pre-applypatch \
|pre-commit \
|prepare-commit-msg \
|pre-push \
|pre-rebase \
|pre-receive \
|update)
IFS= read -rd '' stdin
for file in "${BASH_SOURCE[0]}.d"/*; do
"./$file" "$@" <<<"$stdin" || exit 2
done
exit 0
;;
*)
echo "unknown hook type: $hook_type"
exit 2
;;
esac
@Konfekt
Copy link

Konfekt commented Sep 28, 2021

By using "$file" instead of "./$file", running $file in line 28 works also when the $file path is absolute.

@StayPirate
Copy link

great idea, I changed it to return the exit status of the sub-command with "$file" || exit $?.

And removed the hook_type check, as I expect that the user is smart enough to search and realize that he's using an hook which does not exist. So the finale script is:

#!/usr/bin/env bash

# Allow multiple hooks.
#
# To use it copy this script in "~/.githooks" with the executable bit set. Then and set
# core.hooksPath to ~/.githooks: 'git config --global core.hooksPath ~/.githooks'.
# The name of the file, here described with the 'hook-name' placeholder, should be
# the name of the wanted hook (see man githooks to know available hooks).
# Then place your scripts with executable bit set in ".git/hooks/hook-name.d/".

for file in "${BASH_SOURCE[0]}.d"/*; do
    echo "##### GITHOOK: ${file}"
    "$file" || exit $?
done

Thank you all for the idea.

@Konfekt
Copy link

Konfekt commented Nov 24, 2023

Hello, for your possible interest, here's an adaption that also takes care of the global hooks (introduced in 2.9): https://gist.github.com/Konfekt/d9e86763b0f3febd7b2f7ca589f6c482

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment