Git Hooks for Automation: Pre-commit, Pre-push and CI Integration

I pushed a commit at 4:47 PM on a Friday that broke the build for everyone. It wasn't a logic error. It was a single trailing whitespace fix that my linter would have caught, a console.log I left in, and an AWS key I'd accidentally hard-coded while testing an integration. Three separate failures that should never have left my machine. That Monday, I spent the morning writing the pre-commit and pre-push hooks I should have written months earlier. In my experience, teams treat Git hooks as a nice-to-have until they get burned. After that, they become the cheapest automated quality gate you will ever build.

Git hooks don't replace CI, code review, or testing. They move feedback to the moment it's cheapest to fix: before the commit is even created or before it leaves your machine. When implemented well, they are invisible. When implemented poorly, they become the friction that makes developers use git commit --no-verify for everything. This article covers how to build hooks that your team will actually keep enabled, how pre-commit and pre-push hooks differ in practice, and how to connect them to CI without duplicating logic or creating drift.

Anatomy of .git/hooks: How Git Hands Control to Your Scripts

Every new Git repository comes with a .git/hooks directory filled with sample scripts ending in .sample. Git will look for an executable file named after a specific event, like pre-commit or pre-push, and if it exists and is executable, Git will run it. If that script exits with a non-zero status, Git aborts the operation. That contract is the entire mechanism. There is no config file to enable hooks, no plugin system, just an executable that must return 0 to proceed.

I've found that understanding this simplicity is what makes debugging hooks easier. When a hook fails silently or doesn't run, it's almost always a permissions issue or a missing shebang. Git doesn't warn you that a hook is not executable; it just skips it. On Unix systems, that means you need chmod +x .git/hooks/pre-commit and a valid interpreter line like #!/usr/bin/env bash at the top. On Windows, you need to ensure your Git-for-Windows environment respects the executable bit or use a hook manager that abstracts it away.

Where Hooks Live and Why That Location Creates Problems

By default, hooks live inside .git, which is not versioned. That is intentional for security — you don't want a clone to automatically execute arbitrary code — but it means a fresh clone has no hooks. This is the number one reason teams think hooks don't work. You commit a script to scripts/hooks/pre-commit and wonder why no one else runs it. You need a mechanism to install hooks into .git/hooks after cloning. Native Git offers core.hooksPath since Git 2.9, which lets you point Git at a tracked directory, but I've seen teams struggle with that because it replaces the entire hooks path rather than merging.

Another subtlety is that Git hooks are not run in a fully interactive shell. Environment variables, PATH, and Node or Python versions may differ from your terminal. A hook that runs npm run lint perfectly in your shell might fail in the hook because nvm hasn't been sourced. The fix is to make hooks explicit about their environment: use absolute paths, invoke tools via npx --no-install or lockfile-aware runners, or wrap logic in a language-specific launcher that sets up the environment deterministically.

Exit Codes and stdin: The Contract Your Script Must Honor

Most client-side hooks use the exit code to decide whether to block the action. pre-commit and pre-push should exit 0 on success and non-zero on failure. Some hooks also receive information via stdin. pre-push, for example, receives lines on stdin in the form <local ref> <local sha> <remote ref> <remote sha> for each ref being pushed. pre-commit receives no arguments but you are expected to inspect the staging area yourself, typically with git diff --cached. Misunderstanding this input model leads to hooks that check the working directory instead of the staged changes, which is a common bug. A developer runs git add on half their changes, the hook lints the unstaged file, passes, and they commit broken staged code.

#!/usr/bin/env bash
# .git/hooks/pre-commit - example that lints only staged files
set -euo pipefail

# Get list of staged JS/TS files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|ts|tsx)$' || true)

if [ -z "$STAGED_FILES" ]; then
  exit 0
fi

echo "Running ESLint on staged files..."

# Stash unstaged changes so we lint what's actually being committed
git stash push --keep-index --message "pre-commit stash" --quiet

# Run linter on staged files only
echo "$STAGED_FILES" | xargs npx --no-install eslint --max-warnings=0
LINT_STATUS=$?

# Restore unstaged changes
git stash pop --quiet || true

if [ $LINT_STATUS -ne 0 ]; then
  echo "Commit blocked: fix lint errors or use 'git commit --no-verify' to bypass (not recommended)."
  exit 1
fi

exit 0

This pattern — stashing unstaged changes, running checks, then restoring — is critical. Without it, you are not testing what you are committing. In my experience, the stash approach works for 95% of teams, though it can be confusing if the stash pop conflicts. The alternative is to use tools like lint-staged that handle this isolation more elegantly by passing only staged file contents to the linter.

Pre-commit Automation That Actually Saves You: Linting, Formatting, and Secret Scanning

Pre-commit is the most used hook for a reason. It runs before Git creates the commit object, so you can block a malformed commit before it ever enters history. The key is to keep it fast and deterministic. A pre-commit hook that takes 45 seconds will be bypassed within a week. I aim for under 5 seconds for the common case, and under 10 seconds worst-case. That constraint dictates what you should run here versus in pre-push or CI.

The best candidates for pre-commit are checks that are fast, have a clear auto-fix, and relate directly to the changed files: formatting with Prettier or Black, linting with ESLint or Ruff on changed files only, type checking on affected files if your toolchain supports it incrementally, and secret scanning. I deliberately avoid running the full test suite in pre-commit. It's too slow and it duplicates what pre-push and CI will do more thoroughly.

Fast, File-Scoped Checks That Developers Won't Disable

Formatting is the highest-value pre-commit check because it eliminates style debates entirely. Instead of blocking on formatting errors, a better hook auto-formats and re-adds the changes. Developers learn quickly that saving a file with incorrect formatting is fine — the hook fixes it. For secrets, tools like gitleaks or detect-secrets should run on the staged diff, not the entire repository. Running gitleaks protect --staged will catch an AWS access key in the diff before it becomes a permanent object in Git history, where removing it requires a history rewrite.

Commit message linting is often done in the commit-msg hook, but I prefer to include it as part of the pre-commit flow when using Conventional Commits: Automating Changelogs and Semantic Versioning. If your release pipeline depends on commit prefixes like feat: or fix:, catching a malformed message early prevents a confusing CI failure later. A simple regex check in commit-msg that validates against the Conventional Commits spec takes milliseconds and saves a lot of back-and-forth in pull requests.

What Not to Put in Pre-commit

I've seen teams try to run unit tests, integration tests, and even build Docker images in pre-commit. In theory, that catches bugs earliest. In practice, it trains everyone to use --no-verify. One team I worked with had a 90-second pre-commit hook that ran Jest across the whole monorepo. Within two sprints, --no-verify was in their shell history more often than git commit itself. We moved the test suite to pre-push and CI, kept only ESLint and Prettier in pre-commit, and bypass rates dropped to near zero.

The rule I use: if the check needs to read more than the staged files and takes longer than 10 seconds, it probably belongs in pre-push. If it needs network access or secrets from the environment, it definitely belongs in CI.

Client-Side Hooks Versus Server-Side Enforcement: Why Local Hooks Alone Fail

Client-side hooks like pre-commit and pre-push are voluntary. Any developer can skip them with --no-verify, and Git will not stop them. They are also not enabled by default after clone, as discussed. This is not a flaw in Git's design; it's a security boundary. But it means you cannot rely on client-side hooks for compliance, security scanning, or required quality gates. For those, you need server-side enforcement.

Server-side hooks (pre-receive, update, post-receive) run on the remote when someone pushes. On managed platforms like GitHub, GitLab, or Bitbucket, you don't have direct access to install pre-receive hooks on the server. Instead, you implement the same policies through branch protection rules, required status checks, and platform-native features like GitHub's push protection for secrets. The mental model is: client-side hooks give fast feedback, server-side rules provide the guarantee.

In my experience, the healthiest setup is to run the exact same checks locally and in CI, but enforce them only in CI. That way, developers get immediate feedback if they have hooks installed, but the build still fails if they bypass them. If your CI runs ESLint and Prettier on the entire changed file set, it doesn't matter that a developer skipped the local hook — the pull request will be blocked. This duplication might seem wasteful, but it is the only way to get both speed and trust. You can keep the implementations DRY by sharing configuration. Your .eslintrc, pyproject.toml, and secret scanning configs should be the single source of truth for both contexts.

One anti-pattern to avoid is making client-side hooks more strict than CI. If your pre-commit hook blocks commits that CI would pass, developers will feel punished for having hooks enabled. Keep parity. If CI allows a warning, your hook should allow it too. If CI requires 80% test coverage, don't enforce that in pre-commit where the developer can't easily see the coverage report yet.

Pre-push Hooks as Your Last Line of Defense Before Remote History Gets Polluted

Pre-push runs after commits are created but before they are sent to the remote. It is your last chance to catch problems that are too expensive for pre-commit but too important to leave for CI alone. I think of pre-push as the hook for repository-level invariants: tests pass, branch is up to date, commit history is clean, and no protected files are being pushed accidentally.

Where pre-commit is file-scoped, pre-push is branch-scoped. That difference changes what you can reasonably do. Running a focused test suite related to changed packages is feasible in pre-push, especially in a monorepo where you can use affected-graph analysis to run only the tests for changed projects. Blocking a push that contains a failing test saves CI resources and prevents a broken branch from being visible to others. For teams using trunk-based development or short-lived feature branches, a broken push to main can block deployments, so this gate matters.

Practical Pre-push Checks I Actually Use

First, verify that the branch is not behind its upstream. Pushing a branch that is behind often results in a forced non-fast-forward error or, worse, a merge bubble that could have been avoided with a rebase. A simple git rev-list --left-right --count origin/main...HEAD can detect divergence and prompt the developer to pull first. Second, run the relevant tests. In a JavaScript monorepo, that might be npx nx affected --target=test --base=origin/main. In Python, it might be pytest --failed-first -q scoped to changed modules.

Third, enforce history hygiene if your team cares about it. If you follow a strategy where you rebase to keep history linear — a topic covered well in Git Rebase vs Merge: Understanding the Trade-offs — a pre-push hook can block pushes that contain merge commits or fixup commits that should have been squashed. This is much friendlier than failing in CI after the push, because the developer can fix it with an interactive rebase before anyone else sees it.

#!/usr/bin/env bash
# .git/hooks/pre-push
set -euo pipefail

# $1 is remote name, $2 is remote URL; stdin contains ref info
remote="$1"
url="$2"

while read local_ref local_sha remote_ref remote_sha
do
  # Only check pushes to main or release branches
  if [[ "$remote_ref" == "refs/heads/main" ]] || [[ "$remote_ref" == refs/heads/release/* ]]; then
    echo "Direct push to $remote_ref detected. Checking history..."
    # Block merge commits on main
    if git rev-list --merges --count "$remote_sha..$local_sha" | grep -qv "^0$"; then
      echo "Push blocked: merge commits are not allowed on $remote_ref. Please rebase."
      exit 1
    fi
  fi
done

# Run affected tests - adjust for your stack
if command -v nx > /dev/null; then
  echo "Running affected tests..."
  npx nx affected --target=test --base=origin/main --head=HEAD --parallel=2
  if [ $? -ne 0 ]; then
    echo "Push blocked: tests failed. Fix them before pushing."
    exit 1
  fi
else
  echo "Running quick test suite..."
  npm test -- --passWithNoTests --findRelatedTests $(git diff --name-only origin/main...HEAD | tr '\n' ' ') 2>/dev/null || true
fi

exit 0

Performance is still a concern. A pre-push hook that runs a 4-minute test suite will be tolerated far more than a 4-minute pre-commit hook, because pushes happen less often than commits, but you should still optimize. Use caching, affected analysis, and parallelization. Provide a clear escape hatch for emergencies — for example, check for an environment variable like SKIP_PUSH_TESTS=1 so a developer can push a work-in-progress branch without waiting, while still blocking pushes to main.

Bridging Local Hooks and CI: Preventing the "Works on My Machine" Drift

The most common failure mode I see is local hooks and CI diverging. The hook runs Prettier 2.8, CI runs Prettier 3.0, and a developer's commit that passes locally fails in the pipeline. Or the hook lints only staged files while CI lints the whole project and flags an unrelated file. This drift erodes trust in both systems.

The solution is to make CI and hooks share the same toolchain and configuration, and to version that toolchain explicitly. Pin your formatter, linter, and scanning tools in your lockfile (package-lock.json, poetry.lock, requirements.txt) and invoke them through the package manager in both contexts. In GitHub Actions, that means npx --no-install eslint . rather than a globally installed eslint. In a pre-commit hook, it means the same command, not a different binary from PATH.

For containerized projects, a pattern I like is to run the exact same Docker image in CI and in the hook. The hook can invoke docker run --rm -v $(pwd):/app my-lint-image lint so the environment is identical. It's slower to start, but it guarantees parity. A lighter alternative is to use the pre-commit framework's Docker integration or use a tool like act to run GitHub Actions locally, though I've found that to be heavy for day-to-day use.

Using CI to Verify Hooks Were Run

Some teams want CI to know whether hooks were run locally. You shouldn't try to enforce that — it's easy to fake — but you can make CI fast-fail on issues hooks should have caught and give a helpful message. For example, if your CI runs prettier --check . and it fails, the error message can say: "Formatting check failed. Run 'npx prettier --write .' locally or enable Git hooks with 'npm run prepare'." That nudges developers toward enabling hooks without mandating it.

Another bridge is to generate the hook configuration from the same source as CI. If your CI workflow is defined in .github/workflows/ci.yml and your hooks are defined in .pre-commit-config.yaml, consider a small script that validates both refer to the same tool versions. At the very least, document the relationship in your README so a version bump in one place reminds you to update the other. For more on keeping versioning and branching consistent across this pipeline, see Git Branching Strategies: Trunk-Based, GitFlow and Ship/Show/Ask, which also covers how branch policies complement local checks.

According to the MDN Web Docs, consistent tooling and automation reduces cognitive load by moving style and correctness checks out of human review, which matches what I've observed: teams with parity between hooks and CI spend pull request time discussing design, not formatting.

Managing Hooks at Scale: Husky, pre-commit Framework, and Native Git Config

Once a team grows past three people, manually copying hooks into .git/hooks breaks down. You need a hook manager that versions hooks, installs them automatically, and works across operating systems. The three options I recommend most often are Husky for JavaScript/Node projects, the Python pre-commit framework for polyglot repositories, and the native core.hooksPath approach for teams that want zero dependencies.

Husky is the dominant choice in the Node ecosystem. It installs hooks via an npm run prepare script that runs after npm install, and it stores hook scripts as versioned files in .husky/. Developers don't need to remember to run anything. The DX is excellent because Husky hooks are just shell scripts that call lint-staged, which in turn runs linters only on staged files with proper isolation. The downside is it assumes Node is available and adds a Node-specific layer to a generic Git feature.

The pre-commit framework (from pre-commit.com) is language-agnostic and declarative. You define hooks in .pre-commit-config.yaml and it manages isolated environments for each tool, even if those tools are written in Python, Go, or Ruby. This is my go-to for Python projects or monorepos with multiple languages. It has a large marketplace of ready-made hooks and it handles the stash/unstaged logic correctly. The trade-off is a Python dependency and slower first-time installs as it builds environments.

Native core.hooksPath is the simplest: you commit hooks to hooks/ and set git config core.hooksPath hooks. Git then reads hooks from that tracked directory. No manager, no install step if you check in the config via include or setup script. I use this for small utilities or when I want to avoid adding dependencies. The limitation is that it replaces the hooks path entirely, so you can't easily combine managed hooks with local custom hooks without additional scripting.

# .pre-commit-config.yaml - declarative hooks with shared versions
repos:
  - repo: https://github.com/pre-commit/mirrors-prettier
    rev: v3.1.0
    hooks:
      - id: prettier
        types: [javascript, typescript, css, markdown]

  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks
        name: detect secrets in staged changes

  - repo: https://github.com/pycqa/isort
    rev: 5.13.2
    hooks:
      - id: isort
        files: \.py$

  - repo: local
    hooks:
      - id: eslint-staged
        name: eslint on staged JS
        entry: npx --no-install eslint --max-warnings=0
        language: system
        types: [javascript]
        pass_filenames: true

Installation and maintenance matter more than the manager you choose. Whichever you pick, make hook installation part of your standard setup. For Husky, ensure "prepare": "husky install" is in package.json. For the pre-commit framework, add pre-commit install && pre-commit install --hook-type pre-push to your onboarding script or Makefile. For native paths, add a scripts/setup.sh that runs git config core.hooksPath .githooks. Document it once, automate it, and you won't have to remind people again.

Performance at scale requires more than fast checks. In a large monorepo, running a hook on every commit can still be slow if you scan the whole repository. Tools like Monorepo Tooling: Nx, Turborepo and Bazel for Large Codebases integrate with hooks to run tasks only on affected projects, which keeps even pre-push hooks under 30 seconds. If you don't have that infrastructure, a simple git diff --name-only filter to limit tools to changed files is often enough.

Approach Best For Install Mechanism Performance Note
Husky + lint-staged Node / JS / TS projects npm run prepare runs husky install automatically Fastest for JS; runs only on staged files via lint-staged
pre-commit Framework Python, polyglot, or mixed-language repos pre-commit install creates hooks; manages tool envs Slower cold start but isolated, reproducible environments
Native core.hooksPath Small teams, zero-dependency needs git config core.hooksPath <dir> in setup script No overhead; you manage isolation manually
Server-side / CI only Compliance and guarantees Branch protection + required status checks Enforced remotely; no local install needed

One final concern is security. Hooks are arbitrary code execution. If you point core.hooksPath at a tracked directory, cloning a malicious repository and running your setup script could execute untrusted code. Treat hook installation like any other code execution: review hook scripts in pull requests, avoid curl-piping hook installers, and don't auto-install hooks from forks without review. I also recommend keeping hooks readable and short. A hook that is 200 lines of bash is hard to review and likely doing too much. Extract logic into versioned scripts under scripts/ and have the hook call them.

Frequently Asked Questions

Should I run my full test suite in a pre-commit hook?

No, in most cases you should not. Pre-commit should stay under 5-10 seconds and focus on staged files: formatting, linting, and secret scanning. Full test suites belong in pre-push where you can scope them to affected projects or in CI where you have more resources. If you put a slow test suite in pre-commit, developers will bypass it with --no-verify and you lose the benefit of the fast checks too.

How do I share Git hooks with my team so everyone uses them?

Git does not sync hooks automatically because .git/hooks is not versioned. Use a manager: Husky with lint-staged for Node projects, the pre-commit framework for Python or polyglot repos, or set core.hooksPath to a tracked directory. Ensure installation is automatic — via npm prepare, a Makefile target, or an onboarding script — so a fresh clone gets hooks without manual steps. Pair this with CI enforcement so the checks still block merges even if someone skips the local hook.

What's the difference between pre-commit and pre-push, and when should I use each?

Pre-commit runs before a commit is created and is ideal for fast, file-scoped checks like formatting and linting on staged files. Pre-push runs after commits are made but before they are sent to the remote, so it can enforce branch-level invariants like tests passing, history being linear, and the branch being up to date. I use pre-commit for instant feedback and pre-push for more expensive validations that you want to catch before CI.

Can Git hooks replace CI checks?

No. Client-side hooks are voluntary and can be skipped with --no-verify, and they are not present after a fresh clone until installed. Use hooks for fast local feedback and CI for guaranteed enforcement. Keep the tooling and configuration identical between both — same linter versions, same config files — so developers see the same result locally as they will in the pipeline.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards