Hooks

Do something before or after a particular action

Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature - no need to download anything. Git hooks are run locally.

  • Server-side hooks: we can't use them because of Github. Use webhooks instead
  • Client-side hooks:
    • 'git am' hooks: we don't use 'am', so we don't care
    • Commit:
      • post-commit
      • commit-msg
      • prepare-commit-msg
      • pre-commit
    • Others
      • pre-rebase
      • post-checkout
      • post-merge
      • pre-push
      • pre-auto-gc
      • post-rewrite
# everything you need to know about each hook
man githooks

Practical

  • Hooks are stored in .git/hooks/ in your repo
  • Hooks can be scripts in any language, and can run any programs available on the system

View samples

$ cd .git/hooks/
# To view a list of sample hooks
$ ls
# To view the pre-commit example hook
$ less pre-commit.sample

Build our own hook

# Create a pre-commit file
$ touch pre-commit
# Open file in vi or editor of choice 
$ vi pre-commit

Now we will add a simple bash script to our pre-commit hook, which will return to us the current weather in Waterford. Copy the following script into the pre-commit hook

#!/usr/bin/sh
curl wttr.in/~Waterford

Now this hook will be triggered before we make a commit. Return to the git-workshop directory where we will make a change to our hello.txt file

# Make a change to hello.txt
$ echo 'I am going to trigger a hook' >> hello.txt
# Add hello.txt
$ git add hello.txt
# Commit hello.txt
$ git commit -m 'this should trigger a hook'

More on Hooks

Hooks can be an extremely powerful tool for a developer. For more information refer to https://githooks.com/