Skip to content

Instantly share code, notes, and snippets.

@termosa
Last active September 25, 2020 08:39
Show Gist options
  • Save termosa/98535cf42b12986418ce3fb33a5a971a to your computer and use it in GitHub Desktop.
Save termosa/98535cf42b12986418ce3fb33a5a971a to your computer and use it in GitHub Desktop.
Make friends local and global Git hooks

How to make local hooks work when you have set Git core.hooksPath

If core.hooksPath is set in Git local .git/hooks won't be triggered.

I'm using husky quite often and I need global hooks at the same time. That was a pain for a while. Today I found a solution: I call my local hooks from the global hooks.

Instruction

Let's assume we have such setup in our .gitconfig:

[core]
  hooksPath = /path/to/home/dir/.config/git/hooks

I declare a function in my shell:

ch() {
  HOOK="$HOME/.config/git/hooks/$1"
  if [[ -f "$HOOK" ]]
  then
    echo "\n\nif [[ -f \"\$PWD/.git/hooks/$1\" ]]; then\n  /bin/bash \"\$PWD/.git/hooks/$1\"\nfi" >> "$HOOK"
  else
    touch "$HOOK"
    echo "#\!/bin/bash\n\nif [[ -f \"\$PWD/.git/hooks/$1\" ]]; then\n  /bin/bash \"\$PWD/.git/hooks/$1\"\nfi" >> "$HOOK"
    chmod +x "$HOOK"
  fi
}

This function will create a hook file if it is not existed and append given code if the file already exist:

if [[ -f "$PWD/.git/hooks/hook-name" ]]; then
  /bin/bash "$PWD/.git/hooks/hook-name"
fi

Then we call this function for all possible hooks:

ch applypatch-msg
ch commit-msg
ch post-applypatch
ch post-checkout
ch post-commit
ch post-merge
ch post-rewrite
ch post-update
ch pre-applypatch
ch pre-auto-gc
ch pre-commit
ch pre-merge-commit
ch pre-push
ch pre-rebase
ch prepare-commit-msg
ch push-to-checkout
ch sendemail-validate 

That's it! Now your global hooks will check if local hook is presented and if so, it executes it.

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