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.
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-committool. - 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
- 1Install the pre-commit tool
- 2Create the config file
- 3Add hooks
- 4Install the Git hook
- 5Run on all files once
- 6Enforce in CI