|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Verify that the mypy hook's additional_dependencies in .pre-commit-config.yaml |
| 3 | +includes all runtime dependencies declared in pyproject.toml. |
| 4 | +
|
| 5 | +Run directly or via pre-commit (check-mypy-deps hook). |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import sys |
| 11 | + |
| 12 | +try: |
| 13 | + import tomllib |
| 14 | +except ImportError: |
| 15 | + import tomli as tomllib # type: ignore[no-reuse-def] |
| 16 | + |
| 17 | +import yaml |
| 18 | +from packaging.requirements import Requirement |
| 19 | + |
| 20 | + |
| 21 | +def normalize(name: str) -> str: |
| 22 | + return name.lower().replace("-", "_").replace(".", "_") |
| 23 | + |
| 24 | + |
| 25 | +def main() -> int: |
| 26 | + with open("pyproject.toml", "rb") as f: |
| 27 | + pyproject = tomllib.load(f) |
| 28 | + |
| 29 | + with open(".pre-commit-config.yaml") as f: |
| 30 | + pre_commit = yaml.safe_load(f) |
| 31 | + |
| 32 | + project_deps: list[str] = pyproject["project"]["dependencies"] |
| 33 | + project_packages = {normalize(Requirement(dep).name) for dep in project_deps} |
| 34 | + |
| 35 | + mypy_additional: list[str] | None = None |
| 36 | + for repo in pre_commit["repos"]: |
| 37 | + for hook in repo.get("hooks", []): |
| 38 | + if hook["id"] == "mypy": |
| 39 | + mypy_additional = hook.get("additional_dependencies", []) |
| 40 | + break |
| 41 | + if mypy_additional is not None: |
| 42 | + break |
| 43 | + |
| 44 | + if mypy_additional is None: |
| 45 | + print("ERROR: mypy hook not found in .pre-commit-config.yaml") |
| 46 | + return 1 |
| 47 | + |
| 48 | + mypy_packages = {normalize(Requirement(dep).name) for dep in mypy_additional} |
| 49 | + |
| 50 | + missing = project_packages - mypy_packages |
| 51 | + if missing: |
| 52 | + print( |
| 53 | + "ERROR: The following project dependencies are missing from the mypy\n" |
| 54 | + "hook's additional_dependencies in .pre-commit-config.yaml:\n" |
| 55 | + ) |
| 56 | + for pkg in sorted(missing): |
| 57 | + print(f" {pkg}") |
| 58 | + print("\nAdd them to the `additional_dependencies` list of the mypy hook.") |
| 59 | + return 1 |
| 60 | + |
| 61 | + print("OK: mypy additional_dependencies covers all project runtime dependencies.") |
| 62 | + return 0 |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + sys.exit(main()) |
0 commit comments