How to Add Sourcery to CI and Enforce Refactor Rules

September 19, 2026

You put Sourcery in CI by running the CLI on each pull request, generating a report, and failing the check only on rules your team agreed to enforce. The editor extension is per-developer; CI is where it becomes a team standard.

If your team already uses Sourcery locally but pull requests still come in with the same issues, this is the missing half.

How do you run Sourcery in GitHub Actions?

Add a workflow that installs the CLI and runs a review against the base branch. The core steps:

- uses: actions/setup-python@v5
  with: { python-version: '3.12' }
- run: pip install sourcery-cli
- run: sourcery review --diff "origin/${{ github.base_ref }}...HEAD"

The --diff flag matters. Reviewing the whole repo on every PR is slow and drowns the real changes in legacy noise. Restrict it to the lines the PR actually touches.

Which rules should you enforce versus warn?

Split rules into two buckets and treat them differently:

Bucket Rules CI behavior
Enforce Unused imports, dead code, shadowed names Fail the check
Warn Comprehension rewrites, control-flow changes Comment only

Dead code and unused imports are safe to block — they are unambiguous. Comprehension rewrites are a style call that varies by file, so never fail a build over them.

How do you keep refactor PRs reviewable?

Sourcery in CI should be a reporter, not a committer. If you also auto-apply its fixes, you get pull requests mixing feature work with dozens of unrelated refactors, and reviewers cannot tell which lines are functional.

Keep them separate. Merge the feature PR first, then run a standalone cleanup PR generated purely by Sourcery. A cleanup PR that changes only refactors is trivial to approve. Mixed PRs are not.

What about the paid tier in CI?

The CLI runs locally for free, but team features — shared rule config, PR comments, dashboards — sit in the paid plan. For a small team, the free CLI plus a GitHub Actions step reproduces most of the value at zero cost. The paid tier is worth it when you want per-repo rule profiles without maintaining YAML yourself.

Does Sourcery work outside Python?

No. It is Python-only, and that is a hard boundary. On a polyglot repo, keep it scoped to your .py paths and use a different tool for the rest. Trying to force it across languages just produces false silence on the non-Python code.

Quick Summary

  • Run sourcery review --diff in GitHub Actions against the base branch.
  • Fail CI only on unambiguous rules: unused imports, dead code, shadowed names.
  • Never auto-commit refactors into a feature PR — keep cleanup PRs separate.
  • The free CLI covers CI basics; team dashboards and shared configs are paid.
  • Sourcery is Python-only; scope it to .py paths on polyglot repos.