Sub topic 13
Running Ruff in pre-commit and CI
What this chapter covers
Earlier chapters showed how to run ruff check and ruff format by hand. This chapter automates both so that no unchecked code reaches your main branch. Two layers do the work:
- A pre-commit hook runs Ruff on your machine before each commit, which gives fast feedback.
- A CI job runs Ruff on the server for every push or pull request. It is the layer nobody can skip.
You need these prerequisites:
- A project with Ruff configured in
pyproject.toml. - A Git repository.
- Basic familiarity with GitHub Actions, or with another CI system's YAML files.
Why use both layers
Hooks live in each developer's clone and can be bypassed with git commit --no-verify. They can also be missing if someone never installed them. CI runs in a clean environment on every change, so it is the final gate. The hook is a convenience that catches problems early, and CI enforces the rule.
Exit codes drive automation
Both hooks and CI decide pass or fail from a command's exit code. Know these before you wire anything up.
| Command | Exit code 0 | Exit code 1 | Exit code 2 |
|---|---|---|---|
| `ruff check` | No violations remain | Violations found | Ruff itself failed, for example on a bad config |
| `ruff check --fix` | No violations remain after fixing | Some violations remain unfixed | Ruff itself failed |
| `ruff format --check` | All files already formatted | At least one file would change | Ruff itself failed |
| `ruff format` | Files formatted (or unchanged) | Not used for formatting changes | Ruff itself failed |
Plain ruff format rewrites files and exits 0, so it never fails a CI job on its own. In CI, use --check so that unformatted code fails the build instead of being silently rewritten on a throwaway runner.
Two flags are useful in automation:
ruff check --exit-non-zero-on-fixreturns a non-zero code if any fix was applied, even if every violation was fixed. This is useful when you want a run to signal "the files changed".ruff format --diffprints what would change without writing it. It also exits 1 if changes are needed, so it works well in CI logs because the reader sees exactly what to fix.
Setting up the pre-commit hook
The [pre-commit](https://pre-commit.com) framework reads a .pre-commit-config.yaml file at the repository root. Astral publishes the hooks in the ruff-pre-commit repository.
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.0
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-formatEach part does the following:
revpins the Ruff version the hook uses. Pre-commit downloads that exact release into its own cache, so it does not use the Ruff in your virtual environment.ruff-checkis the linter hook. Older releases of the repository call itruff, and that name still works.args: [--fix]applies safe fixes automatically. Unsafe fixes stay off, as they do on the command line, unless you add--unsafe-fixes. Leave that flag out of hooks, because an unattended unsafe change is hard to review.ruff-formatis the formatter hook.
Order matters. Put ruff-check before ruff-format. A lint fix, such as removing an unused import or sorting imports, can leave code that is not formatted. If the formatter runs last, it cleans up after the fixer in the same commit. In the reverse order, the fixer can undo the formatter's work, and the commit fails on the next attempt.
Install and test the hooks like this:
pip install pre-commit
pre-commit install
pre-commit run --all-filespre-commit install registers the hook in .git/hooks. pre-commit run --all-files runs every hook against the whole repository, which is how you check a new setup without making a commit.
What happens when a hook changes files
When --fix or ruff-format modifies a file, pre-commit treats the hook as failed and aborts the commit. This is intentional. The commit you staged is not the content that now sits on disk. The workflow is:
- Run
git commit. The hooks run and rewrite some files, so the commit stops. - Review the changes with
git diff. - Stage the changes with
git addand commit again. The hooks now find nothing to change, so the commit succeeds.
Keep the hook and your project on the same Ruff version
The most common source of "passes locally, fails in CI" is version drift. Ruff adds rules and changes formatter behavior between releases. If the hook uses one version and CI installs another, they can disagree about the same file.
Pick one source of truth. A simple approach is to pin Ruff in your development dependencies and copy that version into rev:
[project.optional-dependencies]
dev = ["ruff==0.14.0", "pre-commit"]The rev tag has a v prefix (v0.14.0), and the pip pin does not (0.14.0). Update both together. The command pre-commit autoupdate bumps rev to the latest release. After running it, update your ruff== pin to match.
Hooks and excluded files
Pre-commit passes the list of changed files to Ruff explicitly, for example ruff check src/a.py src/b.py. By default, Ruff does not apply exclude to files named directly on the command line. A file you excluded in pyproject.toml can therefore be checked by the hook anyway.
Set force-exclude to make Ruff respect exclude even for explicitly passed paths:
[tool.ruff]
extend-exclude = ["migrations", "vendor"]
force-exclude = trueextend-exclude adds to Ruff's default exclusions (such as .git and .venv) without replacing them. The force-exclude setting applies to both ruff check and ruff format.
A CI job with GitHub Actions
The workflow below installs the pinned version and runs both checks. It runs on every push to main and on every pull request.
name: Ruff
on:
push:
branches: [main]
pull_request:
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Ruff
run: pip install ruff==0.14.0
- name: Lint
run: ruff check --output-format=github .
- name: Check formatting
run: ruff format --check --diff .Points to note:
--output-format=githubprints violations as workflow annotations, so they appear on the changed lines in the pull request.- The two checks are separate steps. If lint fails, the format step does not run (GitHub stops at the first failed step by default), so a developer may need two rounds to see everything. To report both in one run, add
if: always()to the second step. - There is no
--fixin CI. A CI job should report problems and fail, not edit files that nobody will commit. - Ruff does not need your dependencies installed, because it reads source files without importing them. The job is fast because it skips
pip install -e ..
Astral also publishes astral-sh/ruff-action. It installs Ruff and runs ruff check by default. It can read the version from your project, which helps avoid drift. Pass args: "format --check" in a second step to check formatting.
Pre-commit in CI as an alternative
Some teams run pre-commit run --all-files in CI instead of calling Ruff directly. This keeps one definition of the checks, and it also runs your other hooks, such as trailing-whitespace fixers. The cost is slower jobs, because pre-commit builds its environments first. Caching ~/.cache/pre-commit reduces that cost. If you use the hosted service pre-commit.ci, it runs the hooks on pull requests and can push fix commits to the branch for you.
Common problems
- The hook changes files and the commit fails every time. This is expected once. If it fails repeatedly, the formatter and a fixer are disagreeing. Check the hook order and the formatter-conflict rules from the previous chapter.
- CI reports violations the hook did not. Check the versions first. Then check whether the hook ran at all: someone may have used
--no-verify. - Excluded files are still linted by the hook. Set
force-exclude = true. - The format check fails on code that looks fine. Run
ruff format --diff .locally to see the difference. Line endings and trailing newlines are common causes.
Exercise
A teammate's pull request fails the CI step ruff format --check ., but the pre-commit hook passed on their machine. Name two likely causes and one command that shows what CI objects to.
Show answer
Likely causes are a version mismatch between the rev in .pre-commit-config.yaml and the Ruff version CI installs, and a commit made with git commit --no-verify (or without ever running pre-commit install). Running ruff format --diff . with the CI-pinned version prints the changes the formatter would make, which shows exactly what CI objects to.
Exercise
Why should ruff-check come before ruff-format in .pre-commit-config.yaml, and why is --fix left out of the CI job?
Show answer
Lint fixes such as removing imports or sorting them can leave code unformatted, so the formatter should run after them and tidy the result in the same commit. CI should only report problems, because edits made on a temporary runner are never committed and would hide the violations instead of failing the build.