DEV Community

Cover image for How to Configure Git Hooks: Stop Pushing Secrets and Broken Commits
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Configure Git Hooks: Stop Pushing Secrets and Broken Commits

The first time I watched a teammate push an AWS access key to a public GitHub repo, I learned two things. First, GitHub's secret scanning alerts are fast - we got the email in 47 seconds. Second, the team had a pre-commit hook that should have caught it. It just wasn't installed on her laptop, because hooks don't sync with the repo, and nobody had set up a way to make them sync. The four hours we spent rotating keys, scrubbing git history, and notifying downstream forks could have been prevented by 30 lines of YAML and a one-line install command.

Git hooks are the last line of defense between a developer and a mistake. They run on commit, on push, on receive - and they can block anything from a poorly-formatted commit message to a secret in a file. The catch is that git hooks are local by default, which means every developer has to install them manually, which means half your team won't have them, which means they don't actually protect anything. The patterns that work at scale are the ones that make hooks installable in one command, version-controlled, and consistent across every machine.

This is the article I wish I'd had before that AWS key hit main.

What Git Hooks Actually Are (and Aren't)

A git hook is an executable script that git runs at a specific point in its workflow. There are client-side hooks (run on the developer's machine: pre-commit, pre-push, commit-msg, prepare-commit-msg, post-commit) and server-side hooks (run on the git server: pre-receive, update, post-receive). Client-side hooks can be bypassed with --no-verify; server-side hooks cannot.

What hooks are: a fast, local check that catches obvious mistakes before they leave the developer's machine. Linting, formatting, secret scanning, commit message validation - all things you want to fail fast, locally, in 200ms, rather than 5 minutes later in CI.

What hooks aren't: a security boundary. Anything that runs on the client can be bypassed by the developer. If you need to enforce a rule for real (no direct pushes to main, no secrets in history), enforce it server-side. Client hooks are convenience; server hooks are policy.

Hook Side Trigger Use case
pre-commit Client git commit Lint, format, secret scan
pre-push Client git push Run tests, block push to protected branches
commit-msg Client After editor closes Validate commit message format
prepare-commit-msg Client Before editor opens Pre-fill message (branch name, ticket)
post-commit Client After commit Notify, log
pre-receive Server Before refs update Enforce policy (no force-push, no large files)
update Server Per-ref Per-branch policy
post-receive Server After refs update Trigger CI, deploy, notify

The mistake I see repeatedly: teams rely on pre-commit hooks for security ("they'll catch secrets!") and then a developer runs git commit --no-verify and pushes a key. Client hooks are speed bumps; server hooks are gates. Use both.

Prerequisites

  • Git 2.36+ (for core.hooksPath and modern hook features).
  • A repo you want to protect. Hooks work on any git repo - personal projects, monorepos, anything.
  • Python 3.8+ if you want to use the pre-commit framework (the standard for polyglot projects).
  • Node.js 18+ if you want to use Husky (the standard for JS/TS projects).
  • A secret scanner - detect-secrets (Yelp) or gitleaks are the two I recommend.
  • An understanding that hooks are a UX feature, not a security control.

You don't need a git server (GitHub, GitLab, Bitbucket) to use client hooks. Server hooks require either self-hosted git (gitea, forgejo, plain git daemon) or a hosted platform that supports them (GitHub Enterprise, GitLab self-hosted). GitHub.com's hosted product doesn't support server-side hooks; you use GitHub Actions or branch protection rules instead.

How Git Hooks Are Stored

Every git repo has a .git/hooks/ directory with sample scripts. Copy a sample, remove the .sample extension, make it executable, and it runs:

BashCopy

Enter fullscreen mode Exit fullscreen mode

ls .git/hooks/

applypatch-msg.sample pre-push.sample ...

cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
echo '#!/bin/sh\nnpm test' > .git/hooks/pre-commit

Enter fullscreen mode Exit fullscreen mode

This is the original mechanism. It has one massive problem: .git/ is not version-controlled, so hooks don't sync with the repo. Every developer has to install them manually. Half won't. The ones who do will have different versions. This is why every team that takes hooks seriously uses a framework.

The modern answer is core.hooksPath:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
git config core.hooksPath .githooks

Enter fullscreen mode Exit fullscreen mode


markdown

Now git runs hooks from .githooks/ in the repo (which is version-controlled). Every developer who runs that config command gets the same hooks. The remaining problem is making them run that config command - which is where the frameworks come in.

The pre-commit Framework: The Polyglot Standard

pre-commit is a Python-based framework that manages hooks declaratively. You write a .pre-commit-config.yaml, run pre-commit install once, and from then on every commit triggers the configured hooks. The framework handles installation, updates, virtualenvs for Python-based hooks, and caching for everything else.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
pip install pre-commit
cd my-repo
pre-commit install

Enter fullscreen mode Exit fullscreen mode


plaintext

Here's a real .pre-commit-config.yaml I use for Python projects:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.pre-commit-config.yaml

repos:
# Standard hygiene: trailing whitespace, end-of-file, large files

  • repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks:
  • id: trailing-whitespace
  • id: end-of-file-fixer
  • id: check-yaml
  • id: check-added-large-files args: ['--maxkb=500']
  • id: check-merge-conflict
  • id: detect-private-key

# Ruff: fast Python linter + formatter (replaces flake8 + black + isort)

# Type checking with mypy (only on changed files)

# Secret scanning with detect-secrets

# Conventional commit message validation

Enter fullscreen mode Exit fullscreen mode


plaintext

Install and run:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
pre-commit install
pre-commit install --hook-type commit-msg
pre-commit run --all-files # run on everything, useful for first-time setup

Enter fullscreen mode Exit fullscreen mode


plaintext

Three things to notice. First, rev: pins each hook to a specific version. Without pinning, hooks update unpredictably and your CI breaks. Pin everything. Second, the detect-secrets hook uses a baseline file - .secrets.baseline - that contains known false positives. Without a baseline, every existing "secret-looking" string (test tokens, example passwords) flags. Generate the baseline first:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
detect-secrets scan > .secrets.baseline
detect-secrets audit .secrets.baseline # review each finding

Enter fullscreen mode Exit fullscreen mode


plaintext

Third, the conventional-pre-commit hook runs at the commit-msg stage, not the default commit stage. This is because commit message validation needs the message file, which isn't available at pre-commit time. The stages: [commit-msg] configures this.

When a hook fails, pre-commit shows which hook and what file:

CodeCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
detect-secrets..............................................................Failed

  • hook id: detect-secrets
  • exit code: 1 .env: AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Enter fullscreen mode Exit fullscreen mode


markdown

The developer fixes the issue (removes the secret, runs detect-secrets audit to update the baseline if it's a false positive) and re-commits. The check is fast (sub-second for incremental commits), specific, and actionable.

Custom Hooks in Python or Bash

Sometimes the framework hooks don't do what you need. The pre-commit framework supports local hooks - your own scripts, in any language:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.pre-commit-config.yaml (add to the existing repos list)

  • repo: local hooks:
  • id: check-ticket-in-branch
    name: Ensure branch name has ticket ID
    entry: ./scripts/check_branch.sh
    language: script
    always_run: true
    stages: [commit]

  • id: pytest-fast
    name: Run fast tests
    entry: pytest
    args: [-m, "not slow", --tb=short, -q]
    language: system
    types: [python]
    pass_filenames: false

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

scripts/check_branch.sh

!/usr/bin/env bash

set -euo pipefail

branch=$(git rev-parse --abbrev-ref HEAD)
if [[ ! "$branch" =~ ^[A-Z]+-[0-9]+ ]]; then
echo "ERROR: Branch name must start with a ticket ID (e.g., PROJ-123-feature)"
echo "Current branch: $branch"
exit 1
fi

Enter fullscreen mode Exit fullscreen mode


plaintext

The language: script runs an executable file. language: system uses a binary on $PATH. types: [python] filters to only run when Python files are staged. pass_filenames: false tells pre-commit not to pass staged filenames as arguments (useful for test runners that find their own tests).

For more complex logic, write the hook in Python:

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

scripts/check_migration_numbering.py

!/usr/bin/env python3

"""Ensure new migration files don't conflict with existing ones."""
import re
import sys
from pathlib import Path

MIGRATIONS_DIR = Path("db/migrations")
PATTERN = re.compile(r"^(\d{4})[a-z]+.sql$")

def main() -> int:
if not MIGRATIONS_DIR.exists():
return 0
numbers = []
for f in MIGRATIONS_DIR.glob("*.sql"):
m = PATTERN.match(f.name)
if not m:
print(f"ERROR: migration filename doesn't match pattern: {f.name}")
print(f" expected: NNNN_description.sql (e.g., 0001_create_users.sql)")
return 1
numbers.append(int(m.group(1)))
if len(numbers) != len(set(numbers)):
dupes = sorted({n for n in numbers if numbers.count(n) > 1})
print(f"ERROR: duplicate migration numbers: {dupes}")
return 1
return 0

if name == "main":
sys.exit(main())

Enter fullscreen mode Exit fullscreen mode


plaintext

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.pre-commit-config.yaml

  • repo: local hooks:
  • id: check-migration-numbering name: Check migration file numbering entry: python3 scripts/check_migration_numbering.py language: system files: ^db/migrations/.*.sql$ pass_filenames: false
Enter fullscreen mode Exit fullscreen mode


markdown

The files: filter means this hook only runs when a file matching db/migrations/*.sql is staged. Most commits won't trigger it - the right behavior for a check that's only relevant to one kind of change.

Commit Message Conventions

A commit-msg hook validates the commit message format. Conventional Commits (feat:, fix:, chore:, etc.) is the most common, but you can enforce anything:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.git/hooks/commit-msg (or as a local pre-commit hook)

!/usr/bin/env bash

set -euo pipefail

msg_file="$1"
msg=$(cat "$msg_file")

Conventional commits: type(scope): description

pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(([a-z0-9_-]+))?!?: .{1,72}$'

if ! [[ "$msg" =~ $pattern ]]; then
echo "ERROR: Commit message doesn't follow Conventional Commits format."
echo ""
echo "Expected: type(scope): description"
echo " type: feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert"
echo " scope: optional, lowercase"
echo " description: 1-72 chars"
echo ""
echo "Got:"
echo " $msg"
echo ""
echo "Example: feat(auth): add OAuth2 login flow"
exit 1
fi

Optional: enforce body wraps at 72 chars

while IFS= read -r line; do
if [[ ${#line} -gt 72 ]]; then
echo "ERROR: commit message body line exceeds 72 chars:"
echo " $line"
exit 1
fi
done < <(tail -n +2 "$msg_file")

Enter fullscreen mode Exit fullscreen mode


plaintext

prepare-commit-msg is the sibling hook - it pre-fills the message before the editor opens. Useful for auto-injecting the ticket ID from the branch name:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.git/hooks/prepare-commit-msg

!/usr/bin/env bash

set -euo pipefail

msg_file="$1"
commit_source="${2:-}" # 'message', 'template', 'merge', 'squash', 'commit', or empty

Don't modify merge or squash commits

[[ -n "$commit_source" ]] && exit 0

branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$branch" =~ ^([A-Z]+-[0-9]+) ]]; then
ticket="${BASH_REMATCH[1]}"
existing=$(cat "$msg_file")
if ! grep -q "$ticket" "$msg_file"; then
echo "[$ticket] $existing" > "$msg_file"
fi
fi

Enter fullscreen mode Exit fullscreen mode


markdown

Now a developer on branch PROJ-123-add-login gets [PROJ-123] pre-filled in their editor. Saves 5 seconds per commit, saves 30 minutes per quarter when someone forgets to add the ticket and a PM has to dig through git log.

Husky for JavaScript Projects

For JS/TS projects, Husky is the equivalent of pre-commit's install step. It uses core.hooksPath under the hood and integrates with package.json.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
npm install --save-dev husky
npx husky init

Enter fullscreen mode Exit fullscreen mode


plaintext

This creates .husky/pre-commit and adds a prepare script to package.json:

JSONCopy

Enter fullscreen mode Exit fullscreen mode


json
{
"scripts": {
"prepare": "husky"
}
}

Enter fullscreen mode Exit fullscreen mode


plaintext

The prepare script runs automatically on npm install, which means every developer who clones the repo and runs npm install gets the hooks installed. No manual step. This is the pattern that solves the "hooks don't sync" problem for JS projects.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.husky/pre-commit

npm run lint
npm run format:check
npx tsc --noEmit

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.husky/commit-msg

npx --no -- commitlint --edit "$1"

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.husky/pre-push

npm test

Enter fullscreen mode Exit fullscreen mode


plaintext

For secret scanning, add gitleaks as a Husky hook:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.husky/pre-commit (append)

if command -v gitleaks >/dev/null 2>&1; then
gitleaks protect --staged --redact --config .gitleaks.toml
else
echo "WARNING: gitleaks not installed, skipping secret scan"
echo " brew install gitleaks (or download from https://github.com/gitleaks/gitleaks/releases)"
fi

Enter fullscreen mode Exit fullscreen mode


markdown

The command -v guard means the hook still works (with a warning) if gitleaks isn't installed. This is friendlier than failing hard - devs who haven't installed gitleaks get a warning, devs who have get the protection.

Team-Wide Enforcement with core.hooksPath

For non-JS projects, the equivalent of Husky's prepare script is a setup script that runs git config core.hooksPath:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

scripts/setup-hooks.sh

!/usr/bin/env bash

set -euo pipefail

cd "$(git rev-parse --show-toplevel)"
git config core.hooksPath .githooks

Make all hooks executable

chmod +x .githooks/*

echo "Git hooks installed. They'll run on commit and push."
echo "To bypass a hook (e.g., WIP commit), use: git commit --no-verify"

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.githooks/pre-commit

!/usr/bin/env bash

set -euo pipefail

echo "Running pre-commit checks..."

Lint with ruff

if command -v ruff >/dev/null 2>&1; then
ruff check --fix "$(git diff --cached --name-only -- '.py')"
ruff format "$(git diff --cached --name-only -- '
.py')"
git add -u # re-stage formatted files
fi

Secret scan

if command -v gitleaks >/dev/null 2>&1; then
gitleaks protect --staged --redact
fi

Enter fullscreen mode Exit fullscreen mode


plaintext

Document the setup in the README:

MarkdownCopy

Enter fullscreen mode Exit fullscreen mode


markdown

Setup

After cloning, run:

./scripts/setup-hooks.sh

This installs git hooks for linting, formatting, and secret scanning.

Enter fullscreen mode Exit fullscreen mode


plaintext

For maximum enforcement, add a check to CI: "if core.hooksPath is not set, fail." This catches the developers who skipped setup:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


shell

.github/workflows/verify-hooks.yml

  • name: Verify hooks are configured run: | if [[ -z "$(git config core.hooksPath)" ]]; then echo "ERROR: core.hooksPath not set. Run ./scripts/setup-hooks.sh" exit 1 fi
Enter fullscreen mode Exit fullscreen mode


markdown

This is a soft check - a developer can git config core.hooksPath .githooks without running setup, then bypass hooks with --no-verify. But it catches the "I forgot to set up" case, which is the most common.

Server-Side Hooks: Real Policy

Client hooks can be bypassed. Server hooks cannot. If you self-host git (gitea, forgejo, gitolite, plain git over SSH), you can enforce policy with pre-receive and update hooks.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

/srv/git/my-repo.git/hooks/pre-receive

!/usr/bin/env bash

set -euo pipefail

Read stdin: triples

while read -r old_sha new_sha ref_name; do
# Block force-push to main and release/* branches
if [[ "$ref_name" == "refs/heads/main" ]] || [[ "$ref_name" == refs/heads/release/* ]]; then
if [[ "$old_sha" != "0000000000000000000000000000000000000000" ]] && \
[[ "$new_sha" == "0000000000000000000000000000000000000000" ]]; then
echo "ERROR: branch deletion blocked: $ref_name"
exit 1
fi
# Check for force-push (non-fast-forward)
if ! git merge-base --is-ancestor "$old_sha" "$new_sha" 2>/dev/null; then
echo "ERROR: force-push blocked on protected branch: $ref_name"
exit 1
fi
fi

# Block commits by 'root' or other system users
author_emails=$(git log --format='%ae' "${old_sha}..${new_sha}" 2>/dev/null || true)
if echo "$author_emails" | grep -qE 'root@|admin@'; then
echo "ERROR: commits from system users not allowed: $author_emails"
exit 1
fi

# Block large files (>10 MB)
large_files=$(git rev-list --objects "${old_sha}..${new_sha}" 2>/dev/null \
| git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize) %(rest)' \
| awk '$2 == "blob" && $3 > 10485760 {print $4}')
if [[ -n "$large_files" ]]; then
echo "ERROR: files larger than 10 MB not allowed:"
echo "$large_files"
exit 1
fi

# Secret scan on the incoming commits
if command -v gitleaks >/dev/null 2>&1; then
if ! gitleaks protect --source . --log-opts "${old_sha}..${new_sha}" --redact; then
echo "ERROR: potential secrets detected in commits"
exit 1
fi
fi
done

exit 0

Enter fullscreen mode Exit fullscreen mode


markdown

This hook runs on the server before any ref is updated. The while read loop processes each ref being pushed. 0000...0000 is git's "no object" SHA - for new branches, old_sha is zeros; for deletions, new_sha is zeros.

The checks: no force-push to protected branches, no commits from system users (catches "I committed as root by mistake"), no large files (use Git LFS instead), no secrets (gitleaks scan of the incoming commit range).

For GitHub.com (hosted), you can't run server hooks. The equivalents are:

  • Branch protection rules (no force-push, no direct push to main) - settings UI
  • Required status checks (CI must pass before merge) - settings UI
  • GitHub Advanced Security secret scanning - paid feature
  • Rulesets (more granular than branch protection) - available on public repos

For GitLab self-hosted, server-side hooks are supported via "Custom Git Hooks" or "Server Hooks" in the admin UI.

When--no-verify Is OK (and When It Isn't)

git commit --no-verify bypasses client-side hooks. Developers will use it. The question is when it's acceptable.

OK to bypass:

  • WIP commits on a personal branch that you'll squash before merge.
  • Fixing a typo in a comment when the linter is being pedantic.
  • Emergency hotfix where every minute counts (and you've manually verified).

Never OK to bypass:

  • Committing secrets - --no-verify doesn't bypass server hooks or GitHub's secret scanning.
  • Committing to a shared branch.
  • Committing large files.
  • Bypassing hooks because they're slow - fix the speed, don't bypass.

The pattern I enforce: --no-verify is allowed on personal branches (anything that's not main/master/release/*). The pre-push hook checks the branch and refuses to push a --no-verify commit to a shared branch by re-running the checks. This is the closest you can get to "client-side enforcement" without server hooks.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

.githooks/pre-push

!/usr/bin/env bash

set -euo pipefail

Read stdin:

while read -r local_ref local_sha remote_ref remote_sha; do
if [[ "$remote_ref" == "refs/heads/main" ]] || [[ "$remote_ref" == refs/heads/release/* ]]; then
echo "ERROR: direct push to $remote_ref blocked. Use a PR."
exit 1
fi
done

Run full test suite before push

echo "Running tests before push..."
npm test || {
echo "ERROR: tests failed. Use --no-verify only on personal branches."
exit 1
}

Enter fullscreen mode Exit fullscreen mode


markdown

Testing Hooks

Hooks are code. They need tests. The pattern: write the hook as a function, test the function, and have a thin shim that calls it.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

scripts/check_migration_numbering.py (refactored for testability)

import re
import sys
from pathlib import Path

MIGRATIONS_DIR = Path("db/migrations")
PATTERN = re.compile(r"^(\d{4})[a-z]+.sql$")

def check_migrations(directory: Path = MIGRATIONS_DIR) -> list[str]:
"""Return list of errors, empty if all good."""
if not directory.exists():
return []
errors = []
numbers = []
for f in sorted(directory.glob("*.sql")):
m = PATTERN.match(f.name)
if not m:
errors.append(f"migration filename doesn't match pattern: {f.name}")
continue
numbers.append(int(m.group(1)))
if len(numbers) != len(set(numbers)):
dupes = sorted({n for n in numbers if numbers.count(n) > 1})
errors.append(f"duplicate migration numbers: {dupes}")
return errors

def main() -> int:
errors = check_migrations()
for e in errors:
print(f"ERROR: {e}", file=sys.stderr)
return 1 if errors else 0

if name == "main":
sys.exit(main())

Enter fullscreen mode Exit fullscreen mode


plaintext

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

tests/test_migration_hook.py

import pytest
from pathlib import Path
from scripts.check_migration_numbering import check_migrations

def test_clean_migrations(tmp_path: Path):
(tmp_path / "0001_init.sql").write_text("-- init")
(tmp_path / "0002_add_users.sql").write_text("-- users")
assert check_migrations(tmp_path) == []

def test_duplicate_numbers(tmp_path: Path):
(tmp_path / "0001_init.sql").write_text("-- init")
(tmp_path / "0001_oops.sql").write_text("-- oops")
errors = check_migrations(tmp_path)
assert len(errors) == 1
assert "duplicate" in errors[0]

def test_bad_filename(tmp_path: Path):
(tmp_path / "init.sql").write_text("-- init") # missing number
errors = check_migrations(tmp_path)
assert len(errors) == 1
assert "pattern" in errors[0]

def test_missing_dir(tmp_path: Path):
assert check_migrations(tmp_path / "nonexistent") == []

Enter fullscreen mode Exit fullscreen mode


plaintext

Run in CI:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.github/workflows/hooks-test.yml

  • name: Test git hooks run: pytest tests/test_migration_hook.py -v
Enter fullscreen mode Exit fullscreen mode


markdown

The hook logic is testable because it's a pure function. The .githooks/pre-commit shim is one line that calls it. Tests catch regressions when you add new validation rules.

CI/CD: Run Hooks in CI Too

Client hooks are bypassable. The fix: run the same checks in CI. The pre-commit framework has CI mode:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.github/workflows/pre-commit.yml

name: pre-commit
on:
pull_request:
push:
branches: [main]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:

  • uses: actions/checkout@v4
  • uses: actions/setup-python@v5 with: python-version: "3.12"
  • run: pip install pre-commit
  • name: Run pre-commit on all files run: pre-commit run --all-files --show-diff-on-failure
Enter fullscreen mode Exit fullscreen mode


markdown

--show-diff-on-failure shows the diff that the hooks would have applied, so devs can see exactly what to fix. For PRs from forks where hooks might not be installed, this is the safety net.

There's also pre-commit.ci, a hosted service that auto-fixes PRs (commits the formatting changes back to the PR branch). It's $15/repo/month for private repos, free for public. Worth it if your team commits a lot of formatting noise.

Common Mistakes (and How to Spot Them)

Hooks not installed. Symptom: a developer pushes broken code that "should have been caught." Fix: automated install (Husky prepare script, or setup-hooks.sh run on first clone).

Hooks too slow. Symptom: developers start using --no-verify because hooks take 30+ seconds. Fix: profile, parallelize, only run on changed files (pre-commit does this by default for file-filtered hooks), skip slow checks in pre-commit and move them to pre-push or CI.

Hooks that modify files without re-staging. Symptom: formatter fixes a file, commit succeeds with the unformatted version. Fix: git add -u after the formatter runs, or use a framework that handles this (pre-commit does).

Secret scanner without a baseline. Symptom: every commit flags 50 existing "secrets" (test tokens, example passwords). Fix: generate a baseline (detect-secrets scan > .secrets.baseline), audit it, commit it. New secrets flag; old ones don't.

Relying on client hooks for security. Symptom: a developer runs --no-verify and pushes a secret. Fix: server-side hooks for real enforcement, plus CI as a backup, plus a secret scanner with active revocation (GitHub Secret Scanning with push protection).

Pinned versions that drift. Symptom: a hook's rev: is a year old, security vulnerabilities have been fixed upstream but you're not getting them. Fix: pre-commit autoupdate monthly, review the diff, commit the bumps.

Hooks that fail without a clear message. Symptom: developer sees "pre-commit failed" with no explanation, gives up, uses --no-verify. Fix: every hook should print a clear error message and a suggested fix. "Run ruff format" not just "exit 1."

No tests for custom hooks. Symptom: a custom hook breaks after a refactor and nobody notices until it blocks a critical commit. Fix: test hook logic as pure functions.

Troubleshooting, From Real Production

"pre-commit: command not found". The framework isn't installed. pip install pre-commit, or use the standalone installer: curl https://pre-commit.com/install-local.py | python3.

"hook is not executable". The hook file lacks the executable bit. chmod +x .githooks/* or chmod +x .husky/*. Husky does this automatically on install.

"pre-commit says it's not installed in this repo". Run pre-commit install. If it complains about .git/hooks/pre-commit already existing, use pre-commit install --overwrite.

"Hook runs on the wrong files". Check the files: filter in the hook config. Default is all files; types: [python] filters by file type; files: ^src/ filters by path. Use pre-commit run <hook-id> --verbose to debug.

"detect-secrets flags a known false positive". detect-secrets audit .secrets.baseline, mark the finding as "not a secret," commit the updated baseline. The next commit won't flag it.

"Husky hooks don't run after npm install". Check that package.json has "prepare": "husky" in scripts. If you cloned with --no-clone-tags or similar, npm might not run prepare. Run npm run prepare manually.

"Server-side hook rejected push but error message is empty". The hook script has a syntax error or fails before the first echo. Run bash -x /srv/git/repo.git/hooks/pre-receive locally with sample stdin to debug.

"Hooks work for me but not for my teammate". They didn't run setup. For pre-commit, they need pre-commit install. For Husky, they need npm install (which triggers prepare). For core.hooksPath, they need ./scripts/setup-hooks.sh. Document this in the README and enforce in CI.

Cost Considerations

Git hooks themselves are free. The costs are developer time and CI minutes.

Concern Cost Mitigation
Slow hooks block dev workflow Seconds per commit × N commits × N devs Keep hooks <2s; move slow checks to pre-push
CI minutes for hook runs ~1-2 min per PR Use pre-commit run --all-files in CI; cache the pre-commit env
pre-commit.ci (auto-fix service) $15/repo/month (private), free (public) Worth it for teams >3 people
Secret scanner (gitleaks) Free (open source) Self-host; or use GitGuardian/GitHub Advanced Security for $
Server-side hooks (self-hosted git) Free if you self-host git Use Forgejo/Gitea/Gitolite

The biggest cost is the wrong one: hooks that are too slow get bypassed. Profile your hooks:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
time pre-commit run --all-files

Enter fullscreen mode Exit fullscreen mode

If it's >5 seconds on a clean repo, something's wrong. Common culprits: mypy on all files (use --incremental), eslint without cache (use --cache), pytest in pre-commit (move to pre-push).

Alternatives Comparison

Tool Language Approach Best for
pre-commit Python Framework, config-driven Polyglot projects, Python-heavy
Husky JS core.hooksPath + npm scripts JS/TS projects
lefthook Go Config-driven, fast Polyglot, parallel hooks
simple-git-hooks JS Minimalist Small JS projects
Vanilla .git/hooks Any Manual Personal projects, one-off
Server hooks Any Server-side Self-hosted git, real enforcement
GitHub branch protection SaaS UI-configured GitHub.com hosted repos
GitLab push rules SaaS UI-configured GitLab hosted repos

The choice I recommend: pre-commit for any project with mixed languages (it has hooks for everything), Husky for pure JS/TS, lefthook if you want speed and parallelism and don't mind a newer tool. Always pair client hooks with server-side enforcement (branch protection, server hooks, or CI checks).

Real-World Use Cases

  • Polyglot monorepo: pre-commit with ruff (Python), eslint (JS), gitleaks (secrets), and a custom hook that enforces per-package test coverage thresholds. Hooks run in <3s on incremental commits.
  • Open-source project: Husky + commitlint (conventional commits) + gitleaks. CI re-runs all hooks on PRs. Server-side branch protection prevents direct pushes to main.
  • Enterprise compliance: server-side pre-receive hook that blocks commits not signed by an approved GPG key, scans for PII patterns, and logs every push to an audit system.
  • Small team, fast iteration: lefthook with parallel hooks (lint, format, test) running in <2s. --no-verify allowed on feature branches, blocked by pre-push hook on main.
  • Migration from legacy: introduce hooks gradually - start with trailing-whitespace and end-of-file checks (zero false positives), then add linting, then secret scanning with a baseline. Big-bang hook adoption fails because the noise drowns the signal.

Conclusion

Git hooks are the cheapest, fastest feedback loop a developer has. They catch the obvious mistakes - trailing whitespace, broken YAML, secrets in .env, malformed commit messages - in milliseconds, before the commit leaves the laptop, before CI spins up, before anyone else sees the mess. The patterns that work are the ones that make hooks installable in one command, version-controlled, fast, and paired with server-side enforcement for the things that actually matter. Skip those patterns and you'll have hooks that work on three developers' machines and miss the fourth, where the secret lives. Get them right and your team stops pushing secrets, stops pushing broken code, and stops writing commit messages that look like "fix stuff."


Originally published on Mango Developer.

Top comments (0)