Metadata-Version: 2.4
Name: pyrigor
Version: 0.14.1
Summary: A Python coding discipline guideline collection and linter.
Author: Jarl Hoyem (@jarl-hoyem)
License-Expression: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: setuptools>=68; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Requires-Dist: pip; extra == "dev"
Requires-Dist: bandit[toml]>=1.9.4; extra == "dev"
Requires-Dist: codespell>=2.4.3; extra == "dev"
Requires-Dist: commitizen>=4.19.2; extra == "dev"
Requires-Dist: complexipy>=7.0.1; extra == "dev"
Requires-Dist: jsonschema>=4.23.0; extra == "dev"
Requires-Dist: mutmut>=3.8.0; extra == "dev"
Requires-Dist: mypy>=2.4.0; extra == "dev"
Requires-Dist: pip-audit>=2.10.1; extra == "dev"
Requires-Dist: pre-commit-hooks>=6.0.0; extra == "dev"
Requires-Dist: pylint>=4.1.2; extra == "dev"
Requires-Dist: pyright>=1.1.411; extra == "dev"
Requires-Dist: pytest>=9.1.1; extra == "dev"
Requires-Dist: pytest-cov>=6.3.0; extra == "dev"
Requires-Dist: radon>=6.0.1; extra == "dev"
Requires-Dist: ruff>=0.16.10; extra == "dev"
Requires-Dist: tach>=0.35.3; extra == "dev"
Requires-Dist: ty>=0.0.85; extra == "dev"
Requires-Dist: types-jsonschema>=4.26.0.20261006; extra == "dev"
Requires-Dist: vulture>=2.16; extra == "dev"
Requires-Dist: xenon>=0.9.3; extra == "dev"
Requires-Dist: zizmor>=1.30.1; extra == "dev"
Dynamic: license-file

# pyrigor

[![PyPI version](https://img.shields.io/pypi/v/pyrigor.svg)](https://pypi.org/project/pyrigor/)
[![Downloads](https://static.pepy.tech/badge/pyrigor)](https://pepy.tech/project/pyrigor)
[![CI](https://github.com/jarl-hoyem/pyrigor/actions/workflows/ci.yaml/badge.svg)](https://github.com/jarl-hoyem/pyrigor/actions/workflows/ci.yaml)
[![Publish](https://github.com/jarl-hoyem/pyrigor/actions/workflows/publish.yaml/badge.svg)](https://github.com/jarl-hoyem/pyrigor/actions/workflows/publish.yaml)
[![Python 3.11-3.15](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue.svg)](https://www.python.org/downloads/)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://docs.astral.sh/ruff/)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://pre-commit.com/)
[![Type hints: Pyright](https://img.shields.io/badge/type%20hints-Pyright-brightgreen.svg)](https://github.com/microsoft/pyright)
[![Type hints: mypy](https://img.shields.io/badge/type%20hints-mypy-brightgreen.svg)](http://mypy-lang.org/)
[![Type hints: ty](https://img.shields.io/badge/type%20hints-ty-brightgreen.svg)](https://github.com/astral-sh/ty)
[![Pylint](https://img.shields.io/badge/pylint-checked-brightgreen)](https://pylint.pycqa.org/)
[![pydocstyle](https://img.shields.io/badge/docstrings-pydocstyle-brightgreen)](http://www.pydocstyle.org/)
[![Complexity: xenon](https://img.shields.io/badge/complexity-xenon-brightgreen)](https://xenon.readthedocs.io/)
[![Code complexity: radon](https://img.shields.io/badge/code%20complexity-radon-brightgreen)](https://radon.readthedocs.io/)
[![Cognitive complexity: complexipy](https://img.shields.io/badge/cognitive%20complexity-complexipy-brightgreen)](https://github.com/rohaquinlop/complexipy)
[![pytest: 100% coverage](https://img.shields.io/badge/pytest-100%25%20coverage-brightgreen)](https://pytest.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![actionlint](https://img.shields.io/badge/GitHub%20Actions-actionlint-brightgreen)](https://github.com/rhysd/actionlint)
[![Security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)
[![Dead code: vulture](https://img.shields.io/badge/dead%20code-vulture-brightgreen)](https://github.com/jendrikseipp/vulture)
[![codespell](https://img.shields.io/badge/spelling-codespell-brightgreen)](https://github.com/codespell-project/codespell)
[![Checked with pyrigor](https://img.shields.io/badge/checked%20with-pyrigor-blue)](https://github.com/jarl-hoyem/pyrigor)

Catches the class of bug type checkers structurally cannot: a NamedTuple/keyword-only-argument/return-value-usage rule
set for Python, inspired by safety-critical coding guidelines from other languages.

- Finds risky patterns in code that passes strict type checking
- Validated against real, public codebases: CPython's stdlib, Home Assistant, mypy, requests, hypothesis, abseil-py
- Drop-in pre-commit integration, or run standalone

> **The tool pyrigor complements Python's tooling ecosystem. It does not try to replace it.** If an established tool
> such as Pylint, Ruff, or a type checker already provides an adequate check, pyrigor will not duplicate that rule.
> Instead, pyrigor focuses on gaps where it can add distinct value.

## Table of Contents

- [The problem, in one example](#the-problem-in-one-example)
- [Usage](#usage)
- [Adding pyrigor to your own project](#adding-pyrigor-to-your-own-project)
- [What this is](#what-this-is)
- [Status](#status)
- [Guidelines](#guidelines)
- [Engineering and CI](#engineering-and-ci)
- [Philosophy](#philosophy)
- [Contributing](#contributing)
- [How this is built](#how-this-is-built)
- [Acknowledgements](#acknowledgements)
- [Contact](#contact)
- [License](#license)

## The problem, in one example

The [Mars Climate Orbiter](https://www.jpl.nasa.gov/missions/mars-climate-orbiter/) was lost after a unit mismatch
between ground software and navigation calculations. The values were numeric, but their meanings differed.

The same risk of confusing numeric values appears in a simplified spacecraft burn-time calculation. Here the error is
argument order. Correct units still need separate checks. Save this as `bad.py`:

```python
def compute_burn_time(fuel_mass: float, fuel_flow: float) -> float:
    return fuel_mass / fuel_flow


fuel_mass = 100.0  # kg
fuel_flow = 2.0  # kg/s
burn_time = compute_burn_time(fuel_flow, fuel_mass)  # Swapped: 0.02 s instead of 50 s.
```

This passes `mypy --strict bad.py`. The implemented PYR402 rule flags the function's positional parameters. Running
`pyrigor bad.py` reports this diagnostic and exits 1:

```text
bad.py:1:1: PYR402 Function 'compute_burn_time' has positional parameters; all parameters should be keyword-only (keyword-only-arguments)
```

Save this replacement as `good.py`:

```python
def compute_burn_time(*, fuel_mass: float, fuel_flow: float) -> float:
    return fuel_mass / fuel_flow


fuel_mass = 100.0  # kg
fuel_flow = 2.0  # kg/s
burn_time = compute_burn_time(fuel_mass=fuel_mass, fuel_flow=fuel_flow)  # 50 s.
```

Both `mypy --strict good.py` and `pyrigor good.py` pass. The linter exits 0 with no findings. A positional call such as
`compute_burn_time(fuel_flow, fuel_mass)` now fails type checking and raises `TypeError` at runtime. PYR402 flags the
definition, not a particular swapped call. Explicit names make intent visible, but values can still be assigned to the
wrong keyword.

Distinct types provide another layer of protection. A spacecraft interface can distinguish thrust and fuel mass with
`NewType`. The calculation is omitted here; the signature is enough to demonstrate the type check:

```python
from typing import NewType

Thrust = NewType("Thrust", float)
FuelMass = NewType("FuelMass", float)


def compute_burn_time(*, thrust: Thrust, fuel_mass: FuelMass) -> float:
    raise NotImplementedError("Calculation omitted")


thrust = Thrust(120.0)
fuel_mass = FuelMass(60.0)
burn_time = compute_burn_time(thrust=fuel_mass, fuel_mass=thrust)
```

The tool mypy rejects both swapped arguments: `FuelMass` is not `Thrust`, and `Thrust` is not `FuelMass`. PYR201
recommends `NewType` for same-typed values at risk of being confused. It is documented but not yet enforced.

## Usage

```bash
pip install pyrigor
pyrigor path/to/file.py [path/to/another.py ...]
```

Every rule marked enforced in [`guidelines/RULES.md`](./guidelines/RULES.md) runs automatically. A finding exits
non-zero and prints `path:line:col: PYRxxx message (symbolic-name)`.

Run `pyrigor --version` to check the installed version. Use `--select=CODE,CODE` to restrict checking to specific rules,
for example `pyrigor --select=PYR401,keyword-only-arguments path/`. Use `--ignore=CODE,CODE` to exclude specific rules
instead, running every other one. Both may be combined — `--ignore` removes codes from `--select`'s set (or from every
rule, if `--select` is omitted). The codes may be given as the full code, the bare number, or the symbolic name, the
same as suppression comments. An unrecognised code exits immediately with an error naming it, as does a
`--select`/`--ignore` combination that leaves no rules to check. Use `--exclude PATH` to omit a file or directory and
everything below it. Repeat the option to exclude multiple paths. This exclusion is applied by pyrigor itself,
independently of any pre-commit file filter.

PYR402 can be fixed explicitly after reviewing the planned change:

```bash
pyrigor --fix --select PYR402 path/
pyrigor --diff --select=PYR402 path/
```

`--fix` writes only the selected safe fixes and reports changed files. The `--diff` flag previews the same changes
without writing. Fixer modes require explicit PYR402 selection; ordinary linting remains read-only. Both
`--select PYR402` and `--select=PYR402` are accepted.

In diagnostic mode, exit code 1 means findings were reported. In fix mode, it means at least one source-file write
failed. Each writing error names the file and operating system error on stderr. Other files are still processed, and
only successful writes print `Fixed`. Successful fix runs exit 0. Usage errors exit 2. That includes a file name that
the v2 diagnostics schema cannot represent, which stops the run before any file is read.

For the machine-readable editor or tooling integration, use `--output-format=json`. It emits one JSON document
containing kept and suppressed findings, selected-rule metadata, tool identity, operational errors and a file count.
Both JSON and human locations use 1-based Unicode code-point columns. See
[`guidelines/JSON_DIAGNOSTICS.md`](./guidelines/JSON_DIAGNOSTICS.md) for the contract and schema.

To suppress a specific finding, add a same-line comment with a reason:

```python
def f(weight, bias):  # pyrigor PYR402 # matches a fixed external API
    ...
```

Codes may be given as the full code (`PYR402`), the bare number (`402`) or the rule's symbolic name
(`keyword-only-arguments`). Multiple codes: `# pyrigor 402,403 # reason`. A suppression comment without a reason is
ignored, and a warning is printed. Suppressed findings are counted per rule in the summary (`PYR402: 1 suppressed`), not
silently discarded.

When stacking with another tool's own suppression comment on the same line (`# nosec`, `# complexipy: ignore`, ...), put
pyrigor's own comment last — `# nosec  # pyrigor PYR402 # reason`. The pyrigor comment must come after any other tool's
comment, since its reason captures to the end of the line.

A suppression comment may also go on the line directly above the finding, or on any line in its primary span. For
functions, that span runs from `def` or `async def` through the signature colon. A comment elsewhere in the function
body does not suppress a signature finding. Assignment and call findings span the whole statement. The line above is
useful when the mandatory reason would not fit on the starting line:

```python
# pyrigor PYR402 # long test names plus a mandatory reason need more room
def apply_correction_for_the_pytest_fixture_injection_case(weight, bias): ...
```

Same-line comments continue to work. On wrapped statements, comments on any primary-span line work too.

## Adding pyrigor to your own project

Add pyrigor to your own `.pre-commit-config.yaml` as a pinned, remote hook, the same way you would add `ruff` or
`black`:

```yaml
- repo: https://github.com/jarl-hoyem/pyrigor
  rev: v0.14.0
  hooks:
    - id: pyrigor
      args: [--exclude, generated]
```

Pin `rev:` to a real, released tag, not `main`. Check the [release page](https://github.com/jarl-hoyem/pyrigor/releases)
for the latest version.

Show it in your own README:

```markdown
[![Checked with pyrigor](https://img.shields.io/badge/checked%20with-pyrigor-blue)](https://github.com/jarl-hoyem/pyrigor)
```

### Seeing findings in your editor

The tool pyrigor writes `file:line:column: message`, which most editors parse without needing a plugin. Configuring your
existing tools beats installing another one.

In PyCharm, add a File Watcher under `Settings, Tools, File Watchers`:

| Setting           | Value                                        |
| ----------------- | -------------------------------------------- |
| File type         | Python                                       |
| Scope             | Project Files                                |
| Program           | `$ProjectFileDir$/.venv/Scripts/pyrigor.exe` |
| Arguments         | `$FilePath$`                                 |
| Working directory | `$ProjectFileDir$`                           |
| Show console      | Never                                        |
| Output filters    | `$FILE_PATH$:$LINE$:$COLUMN$: $MESSAGE$`     |

On macOS and Linux the program path is `$ProjectFileDir$/.venv/bin/pyrigor`.

Two settings are not straightforward. The `Show console: Never` matters because pyrigor exits 1 whenever it finds
anything, so any other value opens a console on every save. And `Output filters` is not a plain text field, it needs the
browse button next to it, otherwise the value is silently discarded.

Findings then appear in the Problems view, clickable, as you save.

Other editors read the same lines. In Vim or Neovim, `makeprg=pyrigor\ %` with `errorformat=%f:%l:%c:\ %m` fills the
quickfix list from `:make`. In Emacs, `M-x compile` running `pyrigor .` needs no configuration at all, because
compilation mode already recognises this format. In Visual Studio Code, a task in `.vscode/tasks.json` whose
`problemMatcher` pattern is `^(.+):(\d+):(\d+): (.+)$` fills the Problems panel, and that file is normally committed, so
it reaches everyone on the project. Sublime Text takes the same expression as a build system's `file_regex`.

The text line is the lowest common denominator. Where an editor can consume structured output, `--output-format=json`
carries more: severity, raw byte ranges, code-point ranges, enclosing symbols and selected-rule metadata. An integration
can show ranges and colour them by severity. Findings currently carry an empty `fixes` list.

## What this is

Python's failure modes are often silent: implicit type coercion, positional-argument swaps between same-typed
parameters, mutable default arguments, float equality checks and tuple-unpacking that "type-checks" while being
semantically wrong are all real, tool-catchable classes of bugs that slip past mypy, pylint and ruff's default rule
sets.

`pyrigor` is a set of guidelines, with real, working tooling enforcing them today, growing as more rules are built out.

## Status

Early stage.

See [`guidelines/RULES.md`](./guidelines/RULES.md) for the full, generated list of every rule and whether it is enforced
yet.

- [x] Guideline documentation
- [x] Standalone AST-based checkers (pre-commit local hooks)
- [ ] Editor integration (deferred until real demand exists, see #152)

## Guidelines

See [`guidelines/`](./guidelines) for the full list. Each guideline has a rule ID, rationale, example and — once
implemented — a link to its enforcing check.

[`guidelines/RULES.md`](./guidelines/RULES.md) has a generated table of every rule and whether it is enforced yet —
generated from the real guideline docs and `CHECKERS`, never hand-maintained, so it cannot drift the way this table once
did.

## Engineering and CI

CI runs the exact same [`pre-commit`](https://pre-commit.com/) configuration used locally (`just check` runs
`pre-commit run --all-files`), so local and CI checks cannot silently drift apart. Every push and pull request against
`main` builds across Ubuntu, macOS and Windows, and Python 3.11 through 3.15, after `uv lock --check` confirms the
lockfile is current.

The gate includes strict typing across three checkers (mypy, pyright and ty), 100% branch-coverage enforcement and the
security and quality checks listed in the badges above. Every run also builds the wheel and source distribution and
smoke-tests them directly: it installs and runs the packaged artefact, not only the editable source checkout, and runs
pyrigor against the Python standard library to confirm it does not crash on real code.

Mutation testing runs in its own Docker container, as a non-root user matching the calling user's ID so it can write to
the bind-mounted checkout. It gates on a maximum number of surviving mutants rather than a bare score percentage, since
a percentage can hide new survivors while the total mutant count also grows.

On release, the build is smoke-tested against a large, real external codebase (Home Assistant's `core`) before
publishing to PyPI through [trusted publishing](https://docs.pypi.org/trusted-publishers/), with no long-lived API token
involved. Every workflow's action references are pinned to a commit SHA rather than a mutable tag, checkout steps do not
persist credentials unless the job needs to push, and jobs run under least-privilege token permissions.

The [GitLab pipeline](.gitlab-ci.yaml) reuses the core gates on Linux with Python 3.14. Quality checks, tests and
package builds run in parallel. Package verification waits for all three and tests the built wheel and source
distribution without rebuilding them. Test reports and distributions use job artefacts. Dependency caches live under
ignored, excluded `venv/.cache/`, separate from the project's `.venv`. GitHub Actions remain authoritative. Its
operating-system and Python-version matrix, standard-library smoke tests, Docker mutation testing and release
publication stay there to keep GitLab focused on portability of the core gates. GitLab requires no publishing secrets or
privileged Docker runner.

Set the GitLab project's CI/CD configuration file to `.gitlab-ci.yaml` under Settings > CI/CD > General pipelines.

The public [GitLab project](https://gitlab.com/jarl-hoyem/pyrigor) includes the
[successful main pipeline](https://gitlab.com/jarl-hoyem/pyrigor/-/pipelines/2935959298). The separate
[consumer demo](https://gitlab.com/jarl-hoyem/pyrigor-gitlab-demo) shows a pinned PyPI installation, findings,
operational errors and retained JSON diagnostics in a
[passing pipeline](https://gitlab.com/jarl-hoyem/pyrigor-gitlab-demo/-/pipelines/2936176106).

## Philosophy

Prefer explicit over implicit. Make illegal states unrepresentable. Do not rely on convention or code review where a
tool can enforce correctness instead.

The tool pyrigor is prescriptive by design: each guideline does not just flag a risky pattern, it commits to one
specific, verified fix. This is a deliberate choice, not an oversight — a codebase where every developer independently
improvises their own fix for the same problem is exactly the inconsistency pyrigor exists to close.

## Contributing

Participation is governed by the [Code of Conduct](./CODE_OF_CONDUCT.md).

1. Every change starts with an issue. Check
   [open issues labeled `ready`](https://github.com/jarl-hoyem/pyrigor/issues?q=is%3Aissue+is%3Aopen+label%3Aready) for
   a well-scoped starting point, or open a new one.
2. Adding a new rule? Follow [`guidelines/ADDING_A_RULE.md`](./guidelines/ADDING_A_RULE.md) step by step.
3. Run `just check` before pushing.
4. Open a Pull Request.

See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for full setup and workflow details.

## How this is built

Pyrigor's architecture, requirements and review decisions are the maintainer's. Implementation is largely done by LLM
coding assistants, working under the project's Definition of Ready, Definition of Done and independent issue review. The
maintainer is accountable for everything released. The verification behind that responsibility includes 100% branch
coverage, mutation testing and the quality gates described above.

## Feedback

Evaluating pyrigor for your own project? Open an [issue](https://github.com/jarl-hoyem/pyrigor/issues) and tell the
maintainer about your use case — real adoption signals drive priorities.

## Acknowledgements

The tool pyrigor's own rules draw directly on real, external sources, not invented in isolation: Steve McConnell's _Code
Complete_, the OSSF Secure Coding Guide for Python, and Google's Python Style Guide. Built on the shoulders of the real,
open source tooling, it runs alongside every day: ruff, pylint, mypy, pyright, and pytest, among others credited
throughout this project's own guideline docs.

## Contact

Created and maintained by [jarl-hoyem](https://github.com/jarl-hoyem). For questions or ideas, open an issue.

## License

MIT
