Dev tools and workflow · Intermediate · 18 min
Run linters and checks before every commit with pre-commit
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · uv 0.13 · pre-commit 4.7.0 · Git
You will have a repository where pre-commit 4.7 tidies files, lints Python with Ruff and blocks secrets on every commit, runs the project's tests before every push, and runs the same hooks in CI.
On this page
A Git hook is a script Git runs at a fixed moment, such as just before a commit is recorded. You can write one by hand, as in keep secrets out of Git, but hand-written hooks live in .git/hooks/, are not shared with your team, and turn into a pile of shell. pre-commit is a framework that fixes both problems. You list the checks you want in a committed file, .pre-commit-config.yaml, each pinned to a version. pre-commit downloads every tool into its own isolated environment, runs only on the files you changed, and gives every teammate and every CI run exactly the same checks.
In this tutorial you build a small Python project in ~/precommit-demo/, deliberately messy, and add hooks that trim whitespace, check YAML, catch merge markers and large files, lint and format with Ruff, and refuse commits that contain secrets. Then you add a hook that runs the project's own tests before every push, learn the one safe way to skip a hook, run everything in CI, and keep the pinned versions current. All pushes go to a local practice remote, so you need no hosting account.
Step 1 · Install pre-commit as a uv tool
pre-commit is a command-line program, not a project dependency, so install it once per machine as a uv tool. uv gives it a private environment and puts the pre-commit command in ~/.local/bin:
uv tool install pre-commit==4.7.0uv tool update-shelluv tool update-shell adds ~/.local/bin to your PATH in your shell's start-up file if it is missing. Open a new terminal afterwards so the change takes effect.
Check it worked
pre-commit --versionThe output is pre-commit 4.7.0. If the shell says command not found, you are still in the old terminal: open a new one, or run export PATH="$HOME/.local/bin:$PATH" for this session.
Step 2 · Make a messy practice project
Create a repository with a small Python package and a YAML settings file. Each file has a fault for a hook to find: trailing spaces, no newline at the end of the file, two unused imports, untidy spacing, and a YAML line indented one space too far.
mkdir -p ~/precommit-demo/shop/app
cd ~/precommit-demo/shop
git init -b main
touch app/__init__.py
printf 'import os\nimport json\n\n\ndef total( prices ): \n return sum( prices )' > app/prices.py
cat > config.yaml <<'YAML'
app:
name: shop
debug: true
YAML
git add .
git status --shortCheck it worked
git status --short lists three staged files, each with A in the left column: app/__init__.py, app/prices.py and config.yaml. No commit exists yet.
Step 3 · Write a pinned hook configuration
Create .pre-commit-config.yaml in the root of the repository. Each entry under repos names a Git repository that publishes hooks, a rev (the tag to use), and the hook ids you want from it:
cat > .pre-commit-config.yaml <<'YAML'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-merge-conflict
- id: check-added-large-files
args: [--maxkb=300]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.6
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-format
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
YAML
git add .pre-commit-config.yaml
pre-commit validate-configWhat each group does:
- pre-commit-hooks is maintained by the pre-commit project.
trailing-whitespaceandend-of-file-fixerrepair files.check-yamlreports YAML that does not parse.check-merge-conflictrefuses files that still contain<<<<<<<markers.check-added-large-filesrefuses new files over a size limit, 500 kB by default; here it is lowered to 300 kB. - ruff-pre-commit runs Ruff.
ruff-checkcomes first, with--fix, so it can remove problems such as unused imports beforeruff-formatlays out the code. To configure which Ruff rules apply, see lint and format a Python project with Ruff. - gitleaks scans the changes you are about to commit for text shaped like API keys and tokens.
Pinning rev to a tag means every machine runs the same version of every tool until someone changes the file on purpose. Hooks that change files and hooks that only report are both useful. The first kind saves you time; the second kind needs you to make the fix.
Check it worked
pre-commit validate-config prints nothing and returns to the prompt. A typo, such as hook: in place of hooks:, makes it print an error naming the bad key.
Step 4 · Install the hooks and run them on every file once
Tell Git to call pre-commit before each commit, and download the hook environments now rather than on your first commit:
pre-commit install --install-hooksThe first line says something like pre-commit installed at .git/hooks/pre-commit. The installs that follow can take a few minutes. The gitleaks hook is written in Go, and if Go is not on your machine, pre-commit downloads a Go toolchain and builds gitleaks from source. Everything is cached in ~/.cache/pre-commit, so later runs start in under a second. On metered or prepaid mobile data, run this first install on Wi-Fi; after that, pre-commit needs the network again only when you change a rev.
Normally hooks only look at the files staged for a commit. When you add pre-commit to an existing project, run every hook across every file once, so you start from a clean base:
pre-commit run --all-filespre-commit prints one line per hook, ending in Passed, Failed or Skipped. This run fails, and that is the point. Under each failed hook you see its id and either files were modified by this hook or an error. The whitespace, end-of-file and Ruff hooks have already fixed app/prices.py for you. check-yaml cannot guess what you meant, so it reports an error such as mapping values are not allowed here and points at line 3 of config.yaml.
Fix the YAML by hand. Here, debug belongs at the same depth as name:
cat > config.yaml <<'YAML'
app:
name: shop
debug: true
YAML
cat app/prices.py
pre-commit run --all-filesWhen the run is clean, commit. The commit runs the hooks again, this time on the staged files only:
git add .
git commit -m "Add pre-commit checks"Check it worked
The second pre-commit run --all-files ends every line with Passed. app/prices.py now holds only the def total(prices): function, with the imports gone and normal spacing. The commit prints the same list of Passed lines, then a line with the commit hash and Add pre-commit checks.
Step 5 · Watch a commit with a secret get blocked
Now make the mistake the gitleaks hook exists for. This command writes a settings file holding a random string shaped like a GitHub personal access token. It is generated on the spot, so it is not a real token and this page does not contain one:
fake=$(python3 -c 'import secrets, string; print("ghp_" + "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(36)))')
printf 'GITHUB_TOKEN = "%s"\n' "$fake" > app/settings.py
git add app/settings.pyTry to commit it:
git commit -m "Add settings"The gitleaks line says Failed. Below it, gitleaks prints the finding with the rule id github-pat, the file and line, and REDACTED where the secret would be, because the hook runs with --redact so your terminal history and CI logs never show it. Git records no commit.
Take the file out of the staging area and delete it. In a real project, the token goes in an environment variable or a git-ignored .env file, as shown in keep secrets out of Git:
git restore --staged app/settings.py
rm app/settings.pyCheck it worked
git status --short
git log --onelinegit status --short prints nothing, and git log --oneline still shows a single commit, Add pre-commit checks. A scanner catches known token formats, not every secret, so it is a safety net, not a reason to stop keeping secrets out of the code.
Step 6 · Run the project's tests before every push
Formatting and secret checks are quick enough for every commit. A test suite usually is not, so run it at the moment you push instead. Add a test, then a local hook: a hook defined in your own repository that runs a command you already use. Note: the command below replaces your .pre-commit-config.yaml with a longer version of the same file.
mkdir -p tests
cat > tests/test_prices.py <<'PY'
import unittest
from app.prices import total
class TotalTests(unittest.TestCase):
def test_adds_all_prices(self):
self.assertEqual(total([100, 250, 50]), 400)
if __name__ == "__main__":
unittest.main()
PY
cat > .pre-commit-config.yaml <<'YAML'
default_install_hook_types: [pre-commit, pre-push]
default_stages: [pre-commit]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-merge-conflict
- id: check-added-large-files
args: [--maxkb=300]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.6
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-format
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
- id: gitleaks
name: gitleaks over the whole history
alias: gitleaks-history
entry: gitleaks git --redact --verbose
stages: [manual]
- repo: local
hooks:
- id: unit-tests
name: unit tests
entry: python3 -m unittest discover -s tests
language: unsupported
pass_filenames: false
always_run: true
stages: [pre-push]
YAML
pre-commit installThe new keys:
default_install_hook_typestellspre-commit installto set up both Git'spre-commitandpre-pushhooks, so teammates get both with one command.default_stages: [pre-commit]means a hook that does not choose its own stages runs only at commit time. A few of the pre-commit-hooks fixers declare their own stages, so you will also see them, quickly, at push time.- The
unit-testshook useslanguage: unsupported, which runs the command with whatever is on your machine and builds no environment for it. This name arrived in pre-commit 4.4; older configs call itlanguage: system.pass_filenames: falseandalways_run: truemake it run the whole suite once, whatever changed. - The second
gitleaksentry reuses the same hook with a different command. Itsaliasgives it its own name, andstages: [manual]means it runs only when you ask for it. You will use it in CI.
pre-commit install prints two lines, one for .git/hooks/pre-commit and one for .git/hooks/pre-push.
Commit, create a practice remote on your own disk, and push:
git add .
git commit -m "Add tests and a pre-push test hook"
git init --bare ~/precommit-demo/remote.git
git remote add origin ~/precommit-demo/remote.git
git push -u origin mainThe commit output does not mention unit tests. The push output shows something like unit tests....Passed before Git reports the new branch.
Now break the code in a way the linters cannot see, commit it, and push:
cat > app/prices.py <<'PY'
def total(prices):
return sum(prices[1:])
PY
git commit -am "Skip the first price"git pushThe commit goes through, because the code is tidy. The push stops: unit tests says Failed, unittest prints an assertion error along the lines of AssertionError: 300 != 400, then FAILED (failures=1), and Git prints error: failed to push some refs. Fix the function and push again:
cat > app/prices.py <<'PY'
def total(prices):
return sum(prices)
PY
git commit -am "Count every price"
git pushCheck it worked
git --git-dir ~/precommit-demo/remote.git log --oneline -1The remote's newest commit is Count every price. Both later commits reached it with the fix; the broken state was never pushed on its own.
Step 7 · Skip one hook when you really must
Sometimes a hook stands between you and an urgent fix: the test suite needs a service that is down, or a scanner reports a false positive you cannot resolve right now. Git's --no-verify flag skips every hook at once, including the secret scanner. Prefer pre-commit's SKIP variable, which takes a comma-separated list of hook ids and skips only those:
cat >> config.yaml <<'YAML'
currency: NGN
YAML
git commit -am "Set the currency"SKIP=unit-tests git pushTreat a skip as a debt. Say why in the commit message or the pull request, and run the skipped check as soon as you can, for example with pre-commit run unit-tests --hook-stage pre-push. The next step makes sure a skipped hook still runs somewhere nobody can switch it off.
Check it worked
The push output shows unit tests followed by dots and Skipped, while the other hooks still say Passed. The remote's newest commit is Set the currency.
Step 8 · Run the same hooks in CI
Local hooks are a convenience: anyone can skip them, and a new teammate may never run pre-commit install. Running the same config in CI on every push and pull request is what makes the checks binding. Add a GitHub Actions workflow:
mkdir -p .github/workflows
cat > .github/workflows/pre-commit.yml <<'YAML'
name: pre-commit
on:
push:
branches: [main]
pull_request:
jobs:
hooks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: astral-sh/setup-uv@v10
- run: uv tool install pre-commit==4.7.0
- uses: actions/cache@v6
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }}
- run: pre-commit run --all-files --show-diff-on-failure
- run: pre-commit run --all-files --hook-stage pre-push
- run: pre-commit run gitleaks-history --hook-stage manual --all-files
YAML
git add .github
git commit -m "Run pre-commit in CI"
git pushThe three run lines are the whole check:
- The first runs every commit-stage hook on every file.
--show-diff-on-failureprints what a fixing hook changed, so whoever reads the log can see the fix without running anything. - The second runs the pre-push stage, so the tests run even when someone pushed with
SKIP. - The third runs the history scan. The normal gitleaks hook only reads staged changes, and nothing is staged on a CI runner, so on its own it would check nothing there.
fetch-depth: 0gives the runner the full history to scan.
The cache key includes a hash of the config file, so CI downloads hook environments again only when a rev changes. On GitHub, make this job a required status check in the branch protection settings so a failing run blocks merging.
Check it worked
Run the same three commands locally:
pre-commit run --all-files --show-diff-on-failure
pre-commit run --all-files --hook-stage pre-push
pre-commit run gitleaks-history --hook-stage manual --all-filesEvery hook says Passed, and the last command shows something like gitleaks over the whole history....Passed. The commit that added the workflow also passed check-yaml, so the workflow file parses. When you push this repository to GitHub, the Actions tab shows the same results.
Step 9 · Update the pinned versions, then clean up
Pinned revs do not update themselves. pre-commit autoupdate checks each repository for its newest tag and rewrites rev for you. It needs the network, so run it on purpose, for example once a month:
pre-commit autoupdate
git diff
pre-commit run --all-files
git diff --quiet .pre-commit-config.yaml || git commit -am "Update pre-commit hook versions"Each repository gets a line saying it is already up to date, or updating from the old tag to the new one. Read the diff and the release notes of anything that changed before you commit: a new Ruff release can add rules or format code differently, and the full run shows you that straight away. The last line commits only when the config changed. A tag can be moved by whoever controls the repository; pre-commit autoupdate --freeze writes the commit hash in its place, with the tag kept as a comment, if you want versions that cannot change underneath you.
When you are finished, delete the practice project and the cached hook environments:
cd ~
rm -rf ~/precommit-demo
pre-commit cleanIf you do not want to keep pre-commit itself, remove the tool too:
uv tool uninstall pre-commitCheck it worked
ls ~/precommit-demo reports that the folder does not exist, and pre-commit clean printed something like Cleaned followed by the cache folder. If you removed the tool, uv tool list no longer shows pre-commit.
Next steps
- Choose and configure the Ruff rules your hooks enforce: lint and format a Python project with Ruff.
- Speed up the CI job by caching more than the hook environments: cache dependencies and build outputs in GitHub Actions.
- Learn what to do when a secret does reach a commit: keep secrets out of Git.
- Undo a commit a hook should have stopped: undo mistakes in Git.
Related tutorials
- Work on two branches at once with git worktreeYou will fix an urgent bug in a second working tree without stashing your half-finished feature, merge the fix, and clean up every extra tree afterwards.
- Version releases with semantic versioning, Git tags and a changelogYou will take a small shell library from 1.0.0 to 1.1.0 with written version rules, Conventional Commits, a Keep a Changelog file, annotated Git tags, a build stamped by git describe and release notes drafted from the commits since the last tag.
- Search files and shell history interactively with fzfYou will have fzf 0.75 wired into your shell for history search, file insertion and directory jumps, fed by fd with a preview pane, plus two small pickers that switch Git branches and stop processes.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials