Enforce Repo Standards with Pre-Commit Hooks in Git

Set up pre-commit hooks for a team: config file, formatters, linters, secret scanning, local hooks and CI enforcement so checks cannot be skipped.

Aug 30, 2025 - 11:44
Nov 5, 2026 - 12:20
 0  165
Enforce Repo Standards with Pre-Commit Hooks in Git

To enforce repository standards with pre-commit hooks, add a .pre-commit-config.yaml file listing the checks (formatters, linters, secret scanners), have each developer run pre-commit install, and run the same checks in CI with pre-commit run --all-files. Local hooks give fast feedback; the CI run is what actually enforces the rules, because local hooks can be skipped.

This is a practical setup guide. If you first want to know why Git hooks exist and which hook types are available, read why Git hooks are useful for enforcing standards. This page focuses on rolling hooks out across a team and making them stick.

Key takeaways

  • Native Git hooks live in .git/hooks, which is not version controlled. Use the pre-commit framework or core.hooksPath to share them.
  • The pre-commit framework installs each tool in an isolated environment at a pinned version, so every developer runs identical checks.
  • Keep the commit-time hooks fast. Move slow checks such as full test suites to pre-push or CI.
  • Anyone can bypass local hooks with git commit --no-verify. Enforce in CI and protect the main branch.
  • Secret scanning at commit time catches leaks before they reach the remote, where removal is much harder.

Native Git hooks vs the pre-commit framework

Git runs executable scripts in .git/hooks at specific points. The pre-commit hook runs before the commit message is requested, and a non-zero exit aborts the commit. Other client-side hooks include prepare-commit-msg, commit-msg and pre-push.

The catch is that .git/hooks is not cloned. Teams have three ways to share hooks:

ApproachHow it worksStrengthsWeaknesses
pre-commit frameworkA config file in the repo lists hook repositories and versions; pre-commit install writes a small shim into .git/hooksLanguage agnostic, pinned versions, isolated tool environments, large hook ecosystem, runs only on staged filesNeeds Python to install the tool itself; first run downloads environments
core.hooksPathgit config core.hooksPath .githooks points Git at a tracked directory of scriptsNo extra tools, built into GitYou maintain the scripts and tool versions yourself
Language-specific managersFor example Husky with lint-staged in JavaScript projectsInstalls automatically through the package managerTied to one ecosystem

The rest of this guide uses the pre-commit framework because it works across languages and is widely used in DevOps repositories that mix Terraform, YAML, shell and Python.

Step 1: Install pre-commit

pip install pre-commit        # or: pipx install pre-commit
# macOS alternative: brew install pre-commit
pre-commit --version

Step 2: Write the configuration

Create .pre-commit-config.yaml in the repository root. Each entry points to a repository that publishes hooks, a pinned rev and the hook IDs to run. The rev values below are placeholders; run pre-commit autoupdate to set them to the latest tags.

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-json
      - id: check-merge-conflict
      - id: check-added-large-files
        args: ["--maxkb=500"]
      - id: detect-private-key

  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.0
    hooks:
      - id: ruff
        args: ["--fix"]
      - id: ruff-format

  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.96.1
    hooks:
      - id: terraform_fmt
      - id: terraform_validate

  - repo: https://github.com/shellcheck-py/shellcheck-py
    rev: v0.10.0.1
    hooks:
      - id: shellcheck

Pick only the hooks your repository needs. A Python service does not need Terraform hooks, and an infrastructure repo may not need a Python formatter.

Step 3: Install the hooks and run them once

pre-commit install                    # installs the pre-commit hook
pre-commit install --hook-type commit-msg --hook-type pre-push   # if you use those stages
pre-commit autoupdate                 # pin each repo to its latest tag
pre-commit run --all-files            # clean up existing files once

The first full run often changes many files, mostly whitespace and formatting. Commit that as a single "apply formatting" change so it does not mix with real work. You can list that commit in a .git-blame-ignore-revs file so git blame skips it.

What standards to enforce

StandardExample hooksStage
Formattingruff-format or black, prettier, terraform_fmt, gofmtpre-commit
Lintingruff or flake8, eslint, shellcheck, yamllint, hadolint for Dockerfilespre-commit
File hygienetrailing-whitespace, end-of-file-fixer, check-merge-conflict, check-added-large-filespre-commit
Secretsgitleaks, detect-secrets, detect-private-keypre-commit
Commit message formatcommitlint or a Conventional Commits checkercommit-msg
Infrastructure policyterraform_validate, tflint, checkov or trivy config scanspre-commit or pre-push
Unit testsA local hook running a fast test subsetpre-push

If your team uses a commit message convention, the patterns in best practices for Git commit messages map directly onto a commit-msg hook.

Writing a local hook for team-specific rules

When no published hook fits, define one with repo: local. This example blocks commits that add a TODO without a ticket reference:

  - repo: local
    hooks:
      - id: todo-needs-ticket
        name: TODO comments must reference a ticket
        language: pygrep
        entry: 'TODO(?!\(\w+-\d+\))'
        types: [text]

The pygrep language fails the hook when the regular expression matches any line in the staged files. For more complex rules use language: script or language: python.

Enforcing in CI so hooks cannot be skipped

git commit --no-verify skips pre-commit and commit-msg hooks, and a developer who never ran pre-commit install has no hooks at all. Run the same configuration in CI and make the job a required check on protected branches.

GitHub Actions

name: pre-commit
on: [pull_request]
permissions:
  contents: read
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
      - run: pre-commit run --all-files --show-diff-on-failure

GitLab CI/CD

pre-commit:
  image: python:3.12
  stage: test
  variables:
    PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit
  cache:
    paths:
      - .cache/pre-commit
  script:
    - pip install pre-commit
    - pre-commit run --all-files --show-diff-on-failure
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

Caching the pre-commit home directory avoids reinstalling hook environments on every run. Then require the job to pass before merge: branch protection rules or rulesets on GitHub, and "Pipelines must succeed" on GitLab merge requests.

There is also a hosted option, pre-commit.ci, which runs the configuration on pull requests and can push autofix commits. It is free for open-source repositories; check its site for current terms.

Keeping hooks fast and accepted

  • Run on staged files only. The framework does this by default. Avoid hooks that scan the whole repository on every commit.
  • Prefer auto-fixing hooks. A formatter that fixes the file is less annoying than one that only complains. The commit fails once, the developer stages the fix and commits again.
  • Move slow work later. Use stages: [pre-push] for tests and heavy scans, or leave them to CI.
  • Allow targeted skips. SKIP=terraform_validate git commit skips one hook by ID while keeping the rest, which is better than --no-verify when one tool is temporarily broken.
  • Update on a schedule. Run pre-commit autoupdate monthly, or let Dependabot or Renovate open pull requests for hook versions.
  • Document it. Put the two setup commands in the README and in any dev container or bootstrap script so new team members get hooks automatically.

Secret scanning deserves special attention

Once a secret is pushed, it can be copied by anyone with read access, cached in forks and CI logs, and kept in history even after you delete the file. A commit-time scanner such as gitleaks or detect-secrets catches most accidental leaks before they leave the laptop. Pair it with server-side protection: GitHub secret scanning and push protection, or GitLab secret detection. If a secret does leak, rotate it first, then clean history. More detail is in best practices for storing secrets in Git repositories.

Where pre-commit hooks fit in the bigger picture

Hooks are the first and cheapest layer of a quality pipeline. Branch protection, code review and CI scans are the layers that enforce. Branching rules that pair well with hooks are covered in best practices for Git branching strategies, and the wider repository checklist is in best practices for Git repository management. For Jenkins users, the same checks can run as a pipeline stage, which is one of the items in our Jenkins best practices.

Git workflows, hooks and CI quality gates are part of the hands-on labs in our DevOps course, taught in our Kharadi, Pune classroom and live online.

Frequently asked questions

What is a pre-commit hook in Git?

It is a script Git runs before creating a commit. If the script exits with a non-zero status, Git aborts the commit, which lets you block commits that fail formatting, linting or secret checks.

How do I share Git hooks with my team?

The .git/hooks directory is not cloned, so use the pre-commit framework with a committed .pre-commit-config.yaml, or set core.hooksPath to a tracked directory. Each developer still runs one setup command.

Can developers bypass pre-commit hooks?

Yes, with git commit --no-verify or by never installing them. Run the same checks in CI and make that job a required status check on protected branches.

What is the difference between pre-commit and pre-push hooks?

pre-commit runs before each commit and should be fast. pre-push runs before git push sends commits to the remote, so it suits slower checks such as unit tests.

How do I run pre-commit hooks on all files?

Run pre-commit run --all-files. This is useful when you first add the configuration and in CI pipelines.

How do I keep hook versions up to date?

Run pre-commit autoupdate to move each hook repository to its latest tag, or let Renovate or Dependabot open update pull requests.

Which hooks should every DevOps repository have?

A good baseline is whitespace and end-of-file fixes, YAML and JSON syntax checks, merge conflict detection, a large file check, a secret scanner and the formatter and linter for each language or IaC tool in the repo.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.