Lesson 13 advanced

Git Hooks

Automate checks with Git hooks: which hooks exist, writing pre-commit and commit-msg scripts, sharing hooks with core.hooksPath, the new config-based hooks from Git 2.54, running hooks in parallel with Git 2.55, the pre-commit framework and server-side enforcement.

A hook is a program Git runs automatically at a certain moment: before a commit is created, after a checkout, before a push. Hooks catch problems where they are cheapest to fix, on the developer’s machine, seconds after the mistake. For Orbit you will block commits that contain secrets, enforce a commit message format and run the tests before every push.

The hooks you will use

Git supports more than twenty hooks. These cover most needs:

HookRunsCan blockTypical use
pre-commitBefore the commit is createdYesLinters, formatters, secret scanning
prepare-commit-msgBefore the message editor opensYesPre-fill the issue number from the branch name
commit-msgAfter the message is writtenYesEnforce a message format
post-commitAfter the commitNoNotifications
post-checkoutAfter switching branchesNoInstall dependencies if the lockfile changed
pre-pushBefore data is sent to the remoteYesRun the test suite
pre-receiveOn the server, before accepting a pushYesEnforce rules for everyone

A hook blocks the operation by exiting with a non-zero code. Anything it prints is shown to the user, so make the message say how to fix the problem.

A hook as a script

The traditional way is an executable file named after the hook in .git/hooks/. Git creates sample files there (ending in .sample) in every new repository.

Here is a pre-commit hook that refuses to commit anything that looks like a private key or an AWS access key:

#!/usr/bin/env bash
# .git/hooks/pre-commit: block obvious secrets
if git diff --cached -U0 | grep -E -q 'BEGIN (RSA|OPENSSH|EC) PRIVATE KEY|AKIA[0-9A-Z]{16}'; then
  echo "pre-commit: possible secret in staged changes. Remove it, or use a secret manager." >&2
  exit 1
fi
$ chmod +x .git/hooks/pre-commit
$ git commit -m "Add deploy key"
pre-commit: possible secret in staged changes. Remove it, or use a secret manager.

And a commit-msg hook that enforces a Conventional Commits subject (lesson 17). Git passes the path of the message file as the first argument:

#!/usr/bin/env bash
# .git/hooks/commit-msg
if ! head -n1 "$1" | grep -E -q '^(feat|fix|docs|chore|refactor|test|ci|perf)(\(.+\))?!?: .{1,72}$'; then
  echo "commit-msg: use 'type(scope): summary', for example 'fix(api): raise login timeout'" >&2
  exit 1
fi

Sharing hooks with the team

Files in .git/hooks/ are not versioned or cloned, so each developer would have to install them by hand. The usual fix is to commit the hooks in a normal folder and point Git at it:

$ mkdir .githooks && cp .git/hooks/pre-commit .git/hooks/commit-msg .githooks/
$ git config core.hooksPath .githooks
$ git add .githooks && git commit -m "chore: share Git hooks"

Each developer still runs the git config line once after cloning, often from a setup script or make bootstrap. Git never runs code from a repository automatically on clone, by design.

Hooks defined in config (Git 2.54)

Git 2.54 introduced a second way to define hooks: in configuration, by name, without placing files in a hooks folder. Several hooks can run for the same event, and they can live in your global config so they apply to every repository.

# ~/.gitconfig
[hook "no-secrets"]
    event = pre-commit
    command = ~/bin/scan-secrets --staged

[hook "lint"]
    event = pre-commit
    command = npm run lint --silent

Or from the command line:

$ git config set --global hook.no-secrets.event pre-commit
$ git config set --global hook.no-secrets.command "~/bin/scan-secrets --staged"
$ git hook list pre-commit
global  no-secrets  ~/bin/scan-secrets --staged
global  lint        npm run lint --silent
  • hook.<name>.event is the hook it runs for, and hook.<name>.command is what it runs.
  • Hooks for the same event run in the order they appear in configuration.
  • A traditional script in the hooks folder still runs too, last.
  • hook.<name>.enabled = false turns one off without deleting it, for example in one repository that does not need it.

This is a clean way to give every repository on your laptop the same secret scanner, while each project keeps its own linters.

Running hooks in parallel (Git 2.55)

Slow hooks make people skip them. Git 2.55 can run independent hooks for the same event at the same time. Each hook must declare that it is safe to run in parallel, and you choose how many jobs run at once:

$ git config set hook.unit-tests.event pre-push
$ git config set hook.unit-tests.command "npm test --silent"
$ git config set hook.unit-tests.parallel true
$ git config set hook.image-scan.event pre-push
$ git config set hook.image-scan.command "./scripts/scan-dockerfile.sh"
$ git config set hook.image-scan.parallel true
$ git config set hook.jobs 4

hook.<event>.jobs sets the limit for one event, and git hook run -j sets it on the command line. Hooks that need a shared, stable state, such as commit message hooks or hooks that inspect the index and working tree, still run one after another. Only mark a hook as parallel when it does not write files that another hook reads.

Bypassing hooks

git commit --no-verify and git push --no-verify skip the pre-commit, commit-msg and pre-push hooks. That is sometimes necessary, for example to commit a work-in-progress, and it means client-side hooks are a convenience, not a guarantee. Anything that must always hold, such as tests passing or no secrets on main, must also be checked on the server or in CI.

The pre-commit framework

Many teams manage hooks with the pre-commit framework (a separate open-source tool, written in Python). You list ready-made checks in a file and it installs them and their dependencies:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: check-yaml
      - id: detect-private-key
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.28.0
    hooks:
      - id: gitleaks
$ pipx install pre-commit
$ pre-commit install            # writes the .git/hooks/pre-commit entry
$ pre-commit run --all-files    # run every check on the whole repository

Pin rev to real release tags of each project and update them with pre-commit autoupdate. Run the same pre-commit run --all-files in CI so nobody can skip it.

Server-side enforcement

On a self-hosted Git server, pre-receive and update hooks run on every push and can reject it for everyone. Hosting services replace them with settings:

  • Branch protection and rulesets: required reviews, required status checks, no force pushes (lesson 11).
  • Push rules on GitLab: reject commit messages that do not match a pattern, block files by name or size.
  • Secret scanning and push protection on GitHub and GitLab: block pushes that contain known credential formats.

Quick reference

TaskCommand or setting
Hook as a scriptexecutable .git/hooks/<hook-name>
Share versioned hooksgit config core.hooksPath .githooks
Define a hook in config (2.54)hook.<name>.event and hook.<name>.command
List hooks for an eventgit hook list <event>
Run a hook by handgit hook run <event>
Disable one config hookhook.<name>.enabled = false
Allow parallel runs (2.55)hook.<name>.parallel = true, hook.jobs = 4
Skip hooks oncegit commit --no-verify

Exercise

You put a useful pre-commit script in .git/hooks/ and pushed. Your teammates cloned the repository, but the hook never runs for them. Why?

  1. The .git directory, including .git/hooks, is not versioned or cloned
  2. Hooks only run on Linux
  3. Hooks must be signed before Git runs them
  4. The script needs a .sh extension
Show answer

Answer: A. Nothing inside .git is pushed. Commit the hooks in a normal folder such as .githooks and have each developer run git config core.hooksPath .githooks, or use config-based hooks or the pre-commit framework.

Exercise

You want the same secret scanner to run before every commit in all repositories on your laptop, using Git 2.54 or later. What is the simplest way?

  1. Copy the script into .git/hooks of every repository
  2. Add the scanner to every repository’s .gitignore
  3. Set core.hooksPath to a different folder in each repository
  4. Define hook.<name>.event = pre-commit and hook.<name>.command in your global config
Show answer

Answer: D. Config-based hooks, added in Git 2.54, can live in ~/.gitconfig and apply to every repository, alongside any project hooks. git hook list pre-commit shows them.

Exercise

A developer commits a secret with git commit –no-verify, bypassing your pre-commit hook. What stops the secret from reaching main?

  1. Nothing can, hooks are the only protection
  2. Server-side checks: secret scanning or push protection, and CI checks required by branch protection
  3. A second pre-commit hook
  4. Setting hook.jobs to 1
Show answer

Answer: B. Client-side hooks can always be skipped. Rules that must hold for everyone need enforcement on the server or in required CI checks.

Key takeaways

  • Hooks run programs at fixed moments; a non-zero exit blocks commits and pushes.
  • Script hooks live in .git/hooks, which is not shared; use core.hooksPath with a versioned folder.
  • Git 2.54 lets you define named hooks in config, several per event, even globally; git hook list shows them.
  • Git 2.55 runs hooks marked parallel concurrently, limited by hook.jobs.
  • Client hooks can be skipped with --no-verify, so enforce critical rules in CI and on the server too.

FAQ

In which language can I write a hook?

Any. Git only needs an executable file (with a shebang line on Linux and macOS) or, for config hooks, a command. Bash, Python, Node.js and compiled binaries all work. Keep them fast: a pre-commit hook that takes a minute will be skipped.

Are hooks a security risk?

Hooks run with your permissions, which is why Git never installs them from a cloned repository on its own. Read what a project’s hook setup script does before running it, as you would any script.

Do config-based hooks replace .git/hooks scripts?

No, they add to them. Both work together; the script in the hooks folder runs after the configured ones. Choose config hooks when you want several hooks per event or global hooks, and scripts when you want something simple and local.

Why does my hook work in the terminal but not in my IDE?

GUI applications often start with a different PATH, so commands like npm or python are not found. Use full paths in the hook or load your environment at the top of the script.

Should tests run in pre-commit or pre-push?

Fast checks (formatting, linting, secret scanning) fit pre-commit. The full test suite usually belongs in pre-push or in CI, so committing stays instant.

↑ ↓ navigate Enter open Esc close