Lesson 47 +20 XP

Git Hooks

Git Hooks

Hooks are scripts that Git runs automatically at certain moments, like before a commit or after a merge.

Where hooks live

Hooks live in the .git/hooks folder. Git ships with examples like .git/hooks/pre-commit.sample.

Common hooks

HookRuns when
pre-commitbefore a commit is created
commit-msgafter the message is written
pre-pushbefore pushing
post-mergeafter a merge completes

Example: block bad commits

A pre-commit hook can run your tests and refuse the commit if they fail:

# .git/hooks/pre-commit
if ! npm test; then
  echo "Tests failed, commit blocked"
  exit 1
fi

Exiting with a non-zero code cancels the operation.

Enable a hook

  1. Remove the .sample extension.
  2. Make the file executable.
  3. Git runs it automatically from then on.

Note: hooks are local

Hooks live inside .git, so they are not shared with other people unless you use a tool like Husky to sync them.

TL;DR

  • Hooks are scripts Git runs at specific moments.
  • Common ones: pre-commit, commit-msg, pre-push.
  • A non-zero exit code cancels the operation.
  • Hooks live in .git/hooks and are not shared by default.