Skip to content

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 .githooks

Each 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) ​

HookWhen it firesBlockingCommon use
pre-commitBefore commit message is capturedYesLint, secret scan, format check
prepare-commit-msgAfter initial message is createdNoAuto-insert branch name, ticket ID
commit-msgAfter editor saves messageYesEnforce Conventional Commits, DCO
post-commitAfter commit completesNoNotify, log, trigger downstream
pre-pushBefore remote refs are updatedYesBlock dirty branches, check CI status
pre-rebaseBefore rebase beginsYesBlock rebase of shared branches
post-checkoutAfter checkout/switchNoAuto-install deps, update submodules
post-mergeAfter merge completesNoRegenerate lockfiles, update vendored deps
pre-auto-gcBefore automatic garbage collectionYesPrevent GC during active CI runs
post-rewriteAfter rebase/amend rewrites historyNoUpdate notes, re-sign commits

Server-side hooks (bare repos, receive-pack) ​

HookWhen it firesBlockingCommon use
pre-receiveBefore any refs are updatedYesEnforce branch policies, license checks
updatePer-ref, before each ref updateYesPer-branch rules (no force-push to main)
post-receiveAfter all refs are updatedNoTrigger CI, deploy, notify
post-updateAfter refs are updated (deprecated)NoLegacy notify, replaced by post-receive
reference-transactionOn each reference transactionNoAudit logging of ref changes

Client-side hooks in depth ​

pre-commit: the quality gate ​

Run before every commit. Typical checks in order:

  1. Secret scan. Block commits containing API keys, tokens, credentials.
  2. Whitespace. git diff --check catches trailing whitespace, merge conflict markers, and space-before-tab.
  3. Lint. Syntax check changed files (eslint, pylint, shellcheck).
  4. Format. Enforce code style (prettier, black, gofmt).
  5. Large files. Block accidental binary commits.
  6. 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
done

prepare-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"
fi

commit-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 0

pre-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 0

post-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.log

Server-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 0

update: 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 0

post-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 0

Shared 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 .githooks

Option 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 hooks

CI run on all files (not just staged):

bash
pre-commit run --all-files

Option 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
          done

Pattern 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 0

Pattern 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
done

Performance 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 ​

  1. Skipping hooks. git commit --no-verify bypasses pre-commit and commit-msg hooks. Server-side hooks are the only enforcement that cannot be skipped.
  2. Hook path not shared. core.hooksPath is 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.
  3. Binary compatibility. Hooks must run on every OS your team uses. Avoid bash-specific syntax if team members use Windows. Ship .sh files with #!/bin/sh (POSIX) for maximum portability.
  4. Stale hooks. Updating a hook in .githooks/ does not update existing clones. Developers must re-run git config core.hooksPath or the installer script. CI runners rebuild from scratch so they always get the latest.
  5. 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 update hook instead.
  6. Empty push detection. When oldrev is all zeros (new ref) or newrev is all zeros (deletion), handle these cases explicitly. A script that assumes both are non-zero will crash on the first branch creation.
  7. 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 refname before applying commit-content policies.
  8. 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 with SSH_ORIGINAL_COMMAND).
  9. Hook script debugging. set -x in a hook writes to stderr, which the client sees. This can leak repository information in error output. Use GIT_TRACE for server-side debugging instead of verbose hooks.
  10. pre-commit framework with monorepos. The framework's files: and exclude: patterns match against file paths relative to the repo root. In a monorepo with multiple languages, use per-directory config files or always_run: false with files: 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.

Git Master — Git Reference for Every Skill Level