Skip to main content

How to set up pre-commit hooks for a repository

Use the pre-commit framework to run linters and formatters automatically before each commit, sharing one config across the team and enforcing it in CI.

Difficulty
Beginner
Duration
30 minutes
Steps
6

What and why

Pre-commit hooks run checks before a commit is created, catching formatting and lint issues at the earliest point. The pre-commit framework manages hooks declaratively so every contributor runs the same checks. This tutorial wires up automatic linting and formatting.

Prerequisites

  • A Git repository.
  • Python available to install the pre-commit tool.
  • Linters or formatters you want to enforce.

Steps

1. Install the pre-commit tool

pip install pre-commit
pre-commit --version

The tool is language-agnostic even though it is installed via pip.

2. Create the config file

Create .pre-commit-config.yaml at the repo root. This file is committed so the whole team shares it.

3. Add hooks

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.6.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.5.0
    hooks:
      - id: ruff

Each repo provides hooks pinned to a rev for reproducibility.

4. Install the Git hook

pre-commit install

This writes a .git/hooks/pre-commit script that runs the configured checks on staged files.

5. Run on all files once

pre-commit run --all-files

The first run normalizes the whole repo so future commits only deal with new changes.

Verification

Introduce trailing whitespace and try to commit. The hook should fail and fix the file, blocking the commit until you re-stage. A clean commit should pass with all hooks reporting Passed.

Next Steps

Add pre-commit run --all-files to CI so checks are enforced even if a contributor skips local hooks. Use pre-commit autoupdate to bump hook versions. Add language-specific hooks as the codebase grows.

Prerequisites

  • A Git repository
  • Python installed for the pre commit tool
  • Linters or formatters to run

Steps

  • 1
    Install the pre-commit tool
  • 2
    Create the config file
  • 3
    Add hooks
  • 4
    Install the Git hook
  • 5
    Run on all files once
  • 6
    Enforce in CI