Appearance
Git Hooks for DevOps: CI Enforcement, Secret Scan, Supply-Chain Integrity
Git hooks are executable scripts Git runs at predefined points in its workflow. For a DevOps engineer, they are the last line of defense before a commit reaches CI and the first line of enforcement on the server side.
This guide covers all hook types, server-side policy enforcement, shared hook distribution, CI-integrated hook testing, and the pitfalls that catch teams moving from manual to automated enforcement.
How hooks work
Hooks live in a directory Git checks before running the associated action. By default .git/hooks/ (not tracked). To version-control them, point core.hooksPath at a tracked directory:
bash
git config core.hooksPath .githooksEach hook is a plain script with the hook's name as the filename. Exit code 0 lets the action proceed. Non-zero blocks it (for blocking hooks) or signals failure (for non-blocking hooks).
Hook categories
Client-side hooks (local machine)
| Hook | When it fires | Blocking | Common use |
|---|---|---|---|
pre-commit | Before commit message is captured | Yes | Lint, secret scan, format check |
prepare-commit-msg | After initial message is created | No | Auto-insert branch name, ticket ID |
commit-msg | After editor saves message | Yes | Enforce Conventional Commits, DCO |
post-commit | After commit completes | No | Notify, log, trigger downstream |
pre-push | Before remote refs are updated | Yes | Block dirty branches, check CI status |
pre-rebase | Before rebase begins | Yes | Block rebase of shared branches |
post-checkout | After checkout/switch | No | Auto-install deps, update submodules |
post-merge | After merge completes | No | Regenerate lockfiles, update vendored deps |
pre-auto-gc | Before automatic garbage collection | Yes | Prevent GC during active CI runs |
post-rewrite | After rebase/amend rewrites history | No | Update notes, re-sign commits |
Server-side hooks (bare repos, receive-pack)
| Hook | When it fires | Blocking | Common use |
|---|---|---|---|
pre-receive | Before any refs are updated | Yes | Enforce branch policies, license checks |
update | Per-ref, before each ref update | Yes | Per-branch rules (no force-push to main) |
post-receive | After all refs are updated | No | Trigger CI, deploy, notify |
post-update | After refs are updated (deprecated) | No | Legacy notify, replaced by post-receive |
reference-transaction | On each reference transaction | No | Audit logging of ref changes |
Client-side hooks in depth
pre-commit: the quality gate
Run before every commit. Typical checks in order:
- Secret scan. Block commits containing API keys, tokens, credentials.
- Whitespace.
git diff --checkcatches trailing whitespace, merge conflict markers, and space-before-tab. - Lint. Syntax check changed files (eslint, pylint, shellcheck).
- Format. Enforce code style (prettier, black, gofmt).
- Large files. Block accidental binary commits.
- Submodule. Check that submodule pointers reference real commits.
bash
#!/bin/sh
# .githooks/pre-commit
set -euo pipefail
# Secret scan (gitleaks)
if command -v gitleaks >/dev/null 2>&1; then
gitleaks protect --staged --verbose
fi
# Whitespace check
git diff --cached --check || {
echo "ERROR: whitespace issues detected"
exit 1
}
# Lint staged files only (fast)
git diff --cached --name-only --diff-filter=ACMR | while read -r f; do
case "$f" in
*.py) python -m py_compile "$f" ;;
*.sh) shellcheck "$f" ;;
esac
doneprepare-commit-msg: ticket automation
Inject ticket IDs from branch names into commit messages. Saves developers from typing feat(JIRA-1234): manually.
bash
#!/bin/sh
# .githooks/prepare-commit-msg
# Detects branch name like feature/JIRA-1234-something and prepends [JIRA-1234]
COMMIT_MSG_FILE="$1"
COMMIT_SOURCE="$2"
if [ "$COMMIT_SOURCE" = "message" ]; then
exit 0
fi
BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || echo "")
TICKET=$(echo "$BRANCH" | grep -oE '[A-Z]+-[0-9]+' | head -1)
if [ -n "$TICKET" ] && ! grep -qi "$TICKET" "$COMMIT_MSG_FILE" 2>/dev/null; then
sed -i "1s/^/[$TICKET] /" "$COMMIT_MSG_FILE"
ficommit-msg: enforce Conventional Commits
Validates the final commit message against a policy. Rejects non-conforming messages before they land in the log.
bash
#!/bin/sh
# .githooks/commit-msg
# Conventional Commits validation (no external deps)
COMMIT_MSG_FILE="$1"
# Allowed types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert
PATTERN='^(feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert)(\(.+\))?!?: .{1,72}'
if ! grep -qE "$PATTERN" "$COMMIT_MSG_FILE" 2>/dev/null; then
echo "ERROR: commit message must match Conventional Commits format:"
echo " type(scope): description (max 72 chars)"
echo " Allowed types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert"
exit 1
fi
# Body lines (if any) must wrap at 72 chars
if grep -q '^#' "$COMMIT_MSG_FILE"; then
BODY=$(sed -e '/^#/d' "$COMMIT_MSG_FILE" | tail -n +2)
echo "$BODY" | grep -E '^.{73,}$' >/dev/null 2>&1 && {
echo "ERROR: body lines must wrap at 72 characters"
exit 1
}
fi
exit 0pre-push: the remote gate
Pre-push hooks block accidental force-pushes, unapproved merges, or branches with fixup commits. Unlike pre-commit, this runs when the developer explicitly intends to publish.
bash
#!/bin/sh
# .githooks/pre-push
set -euo pipefail
REMOTE="$1"
URL="$2"
# Block force-push to protected branches
while read -r local_ref local_sha remote_ref remote_sha; do
case "$remote_ref" in
refs/heads/main|refs/heads/master|refs/heads/release/*)
# Check if this is a force push (no common ancestor)
if ! git merge-base --is-ancestor "$local_sha" "$remote_sha" 2>/dev/null; then
# Allow if this is the initial push (remote sha is zeros)
if [ "$remote_sha" != "0000000000000000000000000000000000000000" ]; then
echo "ERROR: force-push to $remote_ref is blocked"
exit 1
fi
fi
;;
esac
# Block fixup/squash commits
if git log --oneline "$remote_sha..$local_sha" 2>/dev/null | grep -qE '^(fixup!|squash!)'; then
echo "ERROR: fixup! and squash! commits detected. Run git rebase -i --autosquash first."
exit 1
fi
done
exit 0post-commit and post-merge: automation triggers
Non-blocking hooks that run side effects. Common uses:
- Update a local changelog.
- Log commit SHA to an audit file.
- Trigger a local rebuild of affected docs.
- Notify a status channel.
bash
#!/bin/sh
# .githooks/post-commit
echo "$(git rev-parse HEAD) $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> .git/audit.logServer-side hooks in depth
Server-side hooks run on the bare repository during git receive-pack. They are the authoritative enforcement point because they cannot be bypassed by the client.
pre-receive: universal policy
Runs once per push, receives all ref updates on stdin. Use for global policies that apply to every branch.
bash
#!/bin/bash
# hooks/pre-receive — universal push policy
set -euo pipefail
while read -r oldrev newrev refname; do
# Skip deletions
if [ "$newrev" = "0000000000000000000000000000000000000000" ]; then
continue
fi
# Determine if this is a new ref or an update
if [ "$oldrev" = "0000000000000000000000000000000000000000" ]; then
# New branch/tag — allow
continue
fi
# Enforce DCO: all commits in push must have Signed-off-by trailer
for commit in $(git rev-list "$oldrev..$newrev" --first-parent 2>/dev/null); do
if ! git cat-file commit "$commit" | grep -q '^Signed-off-by:'; then
echo "ERROR: commit $commit missing Signed-off-by trailer (DCO)"
exit 1
fi
done
# Enforce GPG/SSH signatures on all commits to protected branches
case "$refname" in
refs/heads/main|refs/heads/release/*)
for commit in $(git rev-list "$oldrev..$newrev" --first-parent 2>/dev/null); do
if ! git verify-commit "$commit" 2>/dev/null; then
echo "ERROR: commit $commit to $refname must be signed"
exit 1
fi
done
;;
esac
done
exit 0update: per-branch policies
Runs once per ref being updated. Use for branch-specific rules like blocking force-push to release branches or enforcing naming conventions.
bash
#!/bin/bash
# hooks/update — per-ref policy
set -euo pipefail
REFNAME="$1"
OLDREV="$2"
NEWREV="$3"
# Block non-fast-forward updates to release branches
case "$REFNAME" in
refs/heads/release/*|refs/heads/main)
if ! git merge-base --is-ancestor "$OLDREV" "$NEWREV" 2>/dev/null; then
echo "ERROR: non-fast-forward push to $REFNAME is not allowed"
exit 1
fi
;;
esac
# Block tag deletion
case "$REFNAME" in
refs/tags/*)
if [ "$NEWREV" = "0000000000000000000000000000000000000000" ]; then
echo "ERROR: tag deletion is not allowed"
exit 1
fi
;;
esac
exit 0post-receive: CI trigger
Runs after all refs have been accepted. This is where you trigger CI pipelines, deploy webhooks, or mirror to another remote.
bash
#!/bin/bash
# hooks/post-receive — CI trigger and notification
set -euo pipefail
while read -r oldrev newrev refname; do
# Skip tag pushes (CI runs on branches only)
case "$refname" in
refs/heads/*) ;;
*) continue ;;
esac
BRANCH="${refname#refs/heads/}"
# Trigger CI via webhook
curl -sf -X POST \
-H "Content-Type: application/json" \
-d "{\"ref\":\"$refname\",\"before\":\"$oldrev\",\"after\":\"$newrev\"}" \
"https://ci.example.com/webhook/git" \
|| echo "WARN: CI webhook failed"
done
exit 0Shared hook distribution
Option 1: Tracked .githooks directory
Best for teams that want version-controlled hooks without external tooling.
bash
# One-time setup per clone
git config core.hooksPath .githooks
# In CI runner init
git clone --filter=blob:none https://github.com/org/repo.git
cd repo
git config core.hooksPath .githooks
git sparse-checkout set .githooksOption 2: pre-commit framework
The pre-commit framework manages hook installation, versioning, and auto-update. Hooks are declared in .pre-commit-config.yaml and fetched from a registry or git repository.
yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: detect-private-key
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
- repo: https://github.com/compilerla/conventional-pre-commit
rev: v3.2.0
hooks:
- id: conventional-pre-commit
stages: [commit-msg]Install:
bash
pip install pre-commit
pre-commit install
pre-commit install --hook-type commit-msg # for commit-msg hooksCI run on all files (not just staged):
bash
pre-commit run --all-filesOption 3: Template repository with installer script
For organizations that manage hook templates centrally:
bash
#!/bin/sh
# scripts/install-hooks.sh
# Fetches team hooks from a central repo and installs them
set -euo pipefail
HOOKS_REPO="https://git.local.sneakysquid.xyz/team/hooks.git"
HOOKS_DIR="$(git rev-parse --show-toplevel)/.githooks"
echo "Installing team hooks from $HOOKS_REPO"
git clone "$HOOKS_REPO" /tmp/team-hooks --depth 1 --single-branch \
--filter=blob:none 2>/dev/null
mkdir -p "$HOOKS_DIR"
cp /tmp/team-hooks/hooks/* "$HOOKS_DIR/"
chmod +x "$HOOKS_DIR"/*
rm -rf /tmp/team-hooks
git config core.hooksPath "$HOOKS_DIR"
echo "Team hooks installed. Active hooks:"
ls -la "$HOOKS_DIR"CI integration patterns
Pattern 1: Validate hooks on every CI run
Ensures the CI runner's hooks match the repository's expected configuration. Catches drift between developer and CI environments.
yaml
# .github/workflows/ci.yml
jobs:
hook-validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate hooks path
run: |
if [ "$(git config core.hooksPath)" != ".githooks" ]; then
git config core.hooksPath .githooks
fi
- name: Test pre-commit on all files
run: |
for hook in .githooks/pre-commit; do
if [ -x "$hook" ]; then
echo "Testing $hook..."
# Run with --dry-run semantics where possible
fi
donePattern 2: Server-side pre-receive in CI gate
For self-hosted Forgejo/Gitea/GitLab, the pre-receive hook can validate commits before CI even starts. This saves runner time by rejecting policy violations at the push level.
bash
# hooks/pre-receive — fast-fail on policy before CI starts
# Runs on the server, not in CI. Fast path: sub-second checks only.
while read -r oldrev newrev refname; do
# Fast check: commit message format
git rev-list "$oldrev..$newrev" --first-parent | while read -r commit; do
msg=$(git log --format=%s -1 "$commit")
if ! echo "$msg" | grep -qE '^(feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert)'; then
echo "ERROR: commit $commit does not follow Conventional Commits"
exit 1
fi
done
done
exit 0Pattern 3: post-receive deployment matrix
Generate a deployment matrix from the changes pushed. The post-receive hook detects which services changed and dispatches only relevant builds.
bash
# hooks/post-receive — generate CI matrix from diff
while read -r oldrev newrev refname; do
case "$refname" in
refs/heads/main)
changed=$(git diff-tree --no-commit-id -r --name-only "$oldrev..$newrev" \
| cut -d/ -f1 | sort -u | tr '\n' ',' | sed 's/,$//')
curl -X POST -H "Content-Type: application/json" \
-d "{\"changed_services\":\"$changed\"}" \
"https://ci.example.com/dispatch"
;;
esac
donePerformance considerations
- pre-commit hooks must be fast. Developers will bypass slow hooks. Keep sub-second for common paths. Push expensive checks to CI.
- pre-receive hooks must be stateless and sub-second. They block the push. Long-running pre-receive hooks cause SSH timeouts and frustrated developers.
- post-receive hooks should be non-blocking. Fork background jobs for CI triggers and notifications. Never hold the push stream.
- Server-side hooks run as the git user. Ensure the hook process has network access and write permissions to the directories it needs.
Pitfalls
- Skipping hooks.
git commit --no-verifybypasses pre-commit and commit-msg hooks. Server-side hooks are the only enforcement that cannot be skipped. - Hook path not shared.
core.hooksPathis a local config, not cloned. New clones will use.git/hooks/with no checks until they set the path. Automate this in setup scripts or container images. - Binary compatibility. Hooks must run on every OS your team uses. Avoid bash-specific syntax if team members use Windows. Ship
.shfiles with#!/bin/sh(POSIX) for maximum portability. - Stale hooks. Updating a hook in
.githooks/does not update existing clones. Developers must re-rungit config core.hooksPathor the installer script. CI runners rebuild from scratch so they always get the latest. - pre-receive exit code handling. A pre-receive hook that exits non-zero rejects the entire push, not just one ref. If you need per-ref granularity, use the
updatehook instead. - Empty push detection. When
oldrevis all zeros (new ref) ornewrevis all zeros (deletion), handle these cases explicitly. A script that assumes both are non-zero will crash on the first branch creation. - Tag push confusion. Tags have the same hook flow as branches but different semantics. A pre-receive hook that enforces DCO on every commit in a tag push may reject tags pointing to commits the tagger did not author. Check
refnamebefore applying commit-content policies. - SSH vs HTTP authentication. Server-side hooks cannot distinguish between authenticated users directly; they see only the remote refs being pushed. For user-level policy, use
$GL_USER(GitLab) or parse the SSH certificate (Gitea/Forgejo withSSH_ORIGINAL_COMMAND). - Hook script debugging.
set -xin a hook writes to stderr, which the client sees. This can leak repository information in error output. UseGIT_TRACEfor server-side debugging instead of verbose hooks. - pre-commit framework with monorepos. The framework's
files:andexclude:patterns match against file paths relative to the repo root. In a monorepo with multiple languages, use per-directory config files oralways_run: falsewithfiles:scoped to each language's directory.
Companion resources
- Script:
scripts/hooks-manage.sh— install, configure, test, and distribute hooks. - Recipe:
docs/recipes/hooks-quick.md— one-page cheat sheet for all hook types, commands, and CI snippets.