diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fbfb9a4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +## 0.5.0 + +- Add opt-in, path-scoped import boundaries to turn architectural constraints into + deterministic `imports/boundary` errors with project-specific remediation guidance. +- Support absolute and relative static imports, aliases, nested imports, and + type-checking blocks in conventional flat and `src/` layouts. +- Integrate boundaries with JSON, SARIF, CI failure thresholds, rule ignores, + per-file suppression, and the lint toggle. +- Reject malformed boundary configuration with a readable CLI error. +- Enforce separation between PyCodeGate's analysis rules, shared data types, and + presentation using the same boundary configuration available to users. + +No import restrictions are enabled for projects without boundary configuration. +Dynamic imports, re-export tracing, and custom import roots are outside the scope +of this check. See the README for configuration and matching semantics. + +This release also includes the precision, scoring, and output fixes already on +main after the published 0.3.0 release. diff --git a/README.md b/README.md index c8e952f..5d86e3b 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,48 @@ files = ["tests/fixtures/**"] If both files exist, `pycodegate.toml` takes precedence. CLI flags always override config values. +## Import boundaries + +Turn architectural review feedback into a deterministic check. Import boundaries +are opt-in: forbid a module (and its submodules) in selected files and provide +actionable guidance for the developer or agent. + +In `pycodegate.toml`: + +```toml +[[import-boundaries]] +files = ["src/app/domain/*.py"] +forbidden = ["app.infrastructure", "requests", "fastapi"] +message = "Keep the domain independent of infrastructure; use a domain port." + +[[import-boundaries]] +files = ["src/app/*.py"] +forbidden = ["app.legacy_client"] +message = "Use app.clients instead of adding new legacy dependencies." +``` + +For `pyproject.toml`, use `[[tool.pycodegate.import-boundaries]]` with the same +fields. `files` uses case-sensitive project-relative POSIX path globs; `*` can +span directories. `forbidden` contains literal dotted module prefixes, so +`requests` matches `requests.sessions` but not `requests_extra`. Both arrays +must contain at least one nonempty string. The optional `message` supplies the +diagnostic's remediation guidance. + +Checks cover static `import` and `from ... import ...` statements, including +aliases, nested functions, and type-checking blocks. Relative imports are resolved +using the path under the project root, stripping a leading `src/` for conventional +src layouts. Custom import roots, runtime imports via `importlib` or `__import__`, +and re-export tracing are not supported. Importing a name from a package is +treated as importing that dotted name, so avoid forbidden prefixes that collide +with allowed attributes on the same package. + +Violations emit `imports/boundary` errors with the source location and your +message in terminal, JSON, and SARIF output. Use +`pycodegate . --fail-on error` to enforce the boundary in CI. Existing rule and +per-file ignores apply; `--no-lint` disables boundary checks. Without configured +boundaries, scan behavior is unchanged. Static checks supplement tests and +runtime verification; a high score alone does not prove behavior is correct. + ## Profiles PyCodeGate auto-detects a project profile and adjusts rule weights accordingly. You can also set a profile explicitly in config (`profile = "library"`). diff --git a/benchmarks/README.md b/benchmarks/README.md index b0adf6d..efca594 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -23,3 +23,9 @@ removed. Genuine issues (a 100-branch function, `verify=False`) should remain. The precision fixes derived from this benchmark are locked in by `tests/test_precision.py` and the per-rule unit tests under `tests/rules/`. + +## Release validation + +[0.5.0 validation](results/0.5.0.md) records the Python test matrix, packaging +checks, configured boundary checks, and an exact baseline comparison across the +29-package corpus. Machine-readable results are saved alongside the report. diff --git a/benchmarks/results/0.5.0.json b/benchmarks/results/0.5.0.json new file mode 100644 index 0000000..2634336 --- /dev/null +++ b/benchmarks/results/0.5.0.json @@ -0,0 +1,227 @@ +{ + "release": "0.5.0", + "date": "2026-11-15", + "baseline_commit": "2a294b180daefe0511e253905b685de68d761175", + "candidate_code_commit": "8960979", + "packages": { + "requests": { + "files": 35, + "score": 68, + "findings": 169, + "matches_baseline": true, + "source_distribution": "requests-2.34.2" + }, + "flask": { + "files": 65, + "score": 74, + "findings": 61, + "matches_baseline": true, + "source_distribution": "flask-3.1.3" + }, + "click": { + "files": 76, + "score": 72, + "findings": 102, + "matches_baseline": true, + "source_distribution": "click-8.5.1" + }, + "rich": { + "files": 100, + "score": 58, + "findings": 273, + "matches_baseline": true, + "source_distribution": "rich-15.0.0" + }, + "httpx": { + "files": 60, + "score": 74, + "findings": 110, + "matches_baseline": true, + "source_distribution": "httpx-0.28.1" + }, + "sqlalchemy": { + "files": 603, + "score": 22, + "findings": 2256, + "matches_baseline": true, + "source_distribution": "sqlalchemy-2.1.8" + }, + "fastapi": { + "files": 738, + "score": 53, + "findings": 2383, + "matches_baseline": true, + "source_distribution": "fastapi-0.163.1" + }, + "starlette": { + "files": 84, + "score": 71, + "findings": 162, + "matches_baseline": true, + "source_distribution": "starlette-1.10.0" + }, + "pydantic": { + "files": 324, + "score": 35, + "findings": 720, + "matches_baseline": true, + "source_distribution": "pydantic-2.14.3" + }, + "jinja2": { + "files": 49, + "score": 64, + "findings": 104, + "matches_baseline": true, + "source_distribution": "jinja2-3.1.6" + }, + "werkzeug": { + "files": 84, + "score": 59, + "findings": 156, + "matches_baseline": true, + "source_distribution": "werkzeug-3.1.9" + }, + "urllib3": { + "files": 80, + "score": 71, + "findings": 144, + "matches_baseline": true, + "source_distribution": "urllib3-2.8.0" + }, + "django": { + "files": 2592, + "score": 33, + "findings": 969, + "matches_baseline": true, + "source_distribution": "django-6.1.3" + }, + "celery": { + "files": 406, + "score": 37, + "findings": 472, + "matches_baseline": true, + "source_distribution": "celery-5.7.0" + }, + "black": { + "files": 366, + "score": 35, + "findings": 392, + "matches_baseline": true, + "source_distribution": "black-26.10.1" + }, + "isort": { + "files": 110, + "score": 70, + "findings": 144, + "matches_baseline": true, + "source_distribution": "isort-9.0.2" + }, + "pytest": { + "files": 253, + "score": 35, + "findings": 1168, + "matches_baseline": true, + "source_distribution": "pytest-9.2.0" + }, + "attrs": { + "files": 53, + "score": 77, + "findings": 54, + "matches_baseline": true, + "source_distribution": "attrs-26.1.0" + }, + "typer": { + "files": 339, + "score": 66, + "findings": 155, + "matches_baseline": true, + "source_distribution": "typer-0.29.1" + }, + "pyyaml": { + "files": 44, + "score": 58, + "findings": 127, + "matches_baseline": true, + "source_distribution": "pyyaml-6.0.3" + }, + "redis": { + "files": 267, + "score": 43, + "findings": 1143, + "matches_baseline": true, + "source_distribution": "redis-8.1.0" + }, + "scrapy": { + "files": 538, + "score": 45, + "findings": 417, + "matches_baseline": true, + "source_distribution": "scrapy-2.20.0" + }, + "beautifulsoup4": { + "files": 38, + "score": 72, + "findings": 90, + "matches_baseline": true, + "source_distribution": "beautifulsoup4-4.15.0" + }, + "loguru": { + "files": 19, + "score": 67, + "findings": 60, + "matches_baseline": true, + "source_distribution": "loguru-0.8.0" + }, + "pandas": { + "files": 1448, + "score": 20, + "findings": 3210, + "matches_baseline": true, + "source_distribution": "pandas-3.1.1" + }, + "numpy": { + "files": 1046, + "score": 22, + "findings": 2930, + "matches_baseline": true, + "source_distribution": "numpy-2.5.4" + }, + "pillow": { + "files": 292, + "score": 45, + "findings": 666, + "matches_baseline": true, + "source_distribution": "pillow-13.0.0" + }, + "tornado": { + "files": 77, + "score": 41, + "findings": 309, + "matches_baseline": true, + "source_distribution": "tornado-6.6.1" + }, + "aiohttp": { + "files": 144, + "score": 44, + "findings": 430, + "matches_baseline": true, + "source_distribution": "aiohttp-3.14.5" + } + }, + "files": 10330, + "diagnostic_regressions": 0, + "configured_boundary_checks": { + "requests": { + "forbidden_dependency": "urllib3", + "expected_violations": 28 + }, + "flask": { + "forbidden_dependency": "werkzeug", + "expected_violations": 79 + }, + "fastapi": { + "forbidden_dependency": "starlette", + "expected_violations": 115 + } + } +} diff --git a/benchmarks/results/0.5.0.md b/benchmarks/results/0.5.0.md new file mode 100644 index 0000000..e8852a8 --- /dev/null +++ b/benchmarks/results/0.5.0.md @@ -0,0 +1,84 @@ +# 0.5.0 release validation + +Validated on 2026-11-15. Baseline: `2a294b180daefe0511e253905b685de68d761175` +(main, version 0.4.1). Candidate code: `8960979`, version 0.5.0. +Later documentation-only commits do not change the tested implementation. + +## Tests and packaging + +- 287 tests passed on each CI target: Python 3.10.22, 3.11.18, 3.12.14, and 3.13.5. +- Ruff lint and format checks passed. +- Coverage: 91% overall, 100% for the import-boundary rule. +- The installed wheel passed all 287 tests with current PyPI dependencies. +- Wheel and source distribution passed Twine validation and isolated functional + checks for version metadata, opt-in behavior, remediation guidance, and the + CLI failure gate. The wheel was built from the source distribution by `uv build`. +- Configured policy checks found 28 expected urllib3 imports in Requests, 79 + Werkzeug imports in Flask, and 115 Starlette imports in FastAPI. A nonexistent + forbidden module produced no boundary diagnostics in those projects. +- JSON and SARIF, both configuration formats, relative imports, src layouts, + type-checking blocks, nested imports, negative fixtures, suppression, invalid + configuration, and disabling lint are covered by automated tests. + +## Public-source corpus comparison + +All 29 default packages from `uv run --frozen python benchmarks/run_corpus.py` +were scanned, totaling **10,330 Python files**. Sources are cached PyPI +source distributions, not arbitrary working copies. These checks exercise +PyCodeGate against those projects; they do not run the projects' own test suites. + +Each source tree was scanned separately with baseline and candidate code using +`--json --no-dead-code`. Scores, discovered project metadata, and all diagnostic +fields were compared after sorting diagnostics. Only version and elapsed time +were excluded. **Every comparison was identical.** No new default restrictions +are introduced for projects without import-boundary configuration. + +The corpus emits 19,376 existing diagnostics with a mean score of 52.8. These +findings were not individually adjudicated as true or false positives. Identical +output demonstrates lack of regression for this release, not that those projects +are broken or that existing rule precision has been fully established. + +| Package | Source distribution | Files | Score | Findings | Baseline comparison | +| --- | --- | ---: | ---: | ---: | --- | +| requests | requests-2.34.2 | 35 | 68 | 169 | Identical | +| flask | flask-3.1.3 | 65 | 74 | 61 | Identical | +| click | click-8.5.1 | 76 | 72 | 102 | Identical | +| rich | rich-15.0.0 | 100 | 58 | 273 | Identical | +| httpx | httpx-0.28.1 | 60 | 74 | 110 | Identical | +| sqlalchemy | sqlalchemy-2.1.8 | 603 | 22 | 2256 | Identical | +| fastapi | fastapi-0.163.1 | 738 | 53 | 2383 | Identical | +| starlette | starlette-1.10.0 | 84 | 71 | 162 | Identical | +| pydantic | pydantic-2.14.3 | 324 | 35 | 720 | Identical | +| jinja2 | jinja2-3.1.6 | 49 | 64 | 104 | Identical | +| werkzeug | werkzeug-3.1.9 | 84 | 59 | 156 | Identical | +| urllib3 | urllib3-2.8.0 | 80 | 71 | 144 | Identical | +| django | django-6.1.3 | 2592 | 33 | 969 | Identical | +| celery | celery-5.7.0 | 406 | 37 | 472 | Identical | +| black | black-26.10.1 | 366 | 35 | 392 | Identical | +| isort | isort-9.0.2 | 110 | 70 | 144 | Identical | +| pytest | pytest-9.2.0 | 253 | 35 | 1168 | Identical | +| attrs | attrs-26.1.0 | 53 | 77 | 54 | Identical | +| typer | typer-0.29.1 | 339 | 66 | 155 | Identical | +| pyyaml | pyyaml-6.0.3 | 44 | 58 | 127 | Identical | +| redis | redis-8.1.0 | 267 | 43 | 1143 | Identical | +| scrapy | scrapy-2.20.0 | 538 | 45 | 417 | Identical | +| beautifulsoup4 | beautifulsoup4-4.15.0 | 38 | 72 | 90 | Identical | +| loguru | loguru-0.8.0 | 19 | 67 | 60 | Identical | +| pandas | pandas-3.1.1 | 1448 | 20 | 3210 | Identical | +| numpy | numpy-2.5.4 | 1046 | 22 | 2930 | Identical | +| pillow | pillow-13.0.0 | 292 | 45 | 666 | Identical | +| tornado | tornado-6.6.1 | 77 | 41 | 309 | Identical | +| aiohttp | aiohttp-3.14.5 | 144 | 44 | 430 | Identical | + +Machine-readable evidence is in [0.5.0.json](0.5.0.json). + +## Version and publication + +PyPI and remote Git tags were checked: the latest published version was 0.3.0; +0.5.0 was unused. The minor version reflects the new opt-in capability on top of +the unreleased 0.4.1 checkout. `pyproject.toml`, `uv.lock`, installed metadata, +CLI JSON, and distribution names agree on 0.5.0. + +The existing release workflow publishes to PyPI through trusted publishing when +a GitHub release is published. Local validation does not establish a merged PR, +passing hosted CI, a published GitHub release, or successful PyPI publication. diff --git a/pyproject.toml b/pyproject.toml index 4e47266..134ad6a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pycodegate" -version = "0.4.1" +version = "0.5.0" description = "Trust, but verify. The quality gate for AI-generated Python code." readme = "README.md" requires-python = ">=3.10" @@ -77,3 +77,13 @@ files = ["tests/fixtures/**", "tests/**"] [tool.pycodegate.per-file-suppress] # Click CLI entry-points must declare all options as individual parameters "src/pycodegate/cli.py" = ["too-many-arguments"] + +[[tool.pycodegate.import-boundaries]] +files = ["src/pycodegate/rules/*.py"] +forbidden = ["pycodegate.cli", "pycodegate.output"] +message = "Keep analysis independent of presentation; return diagnostics to the caller." + +[[tool.pycodegate.import-boundaries]] +files = ["src/pycodegate/types.py"] +forbidden = ["pycodegate.rules", "pycodegate.scan", "pycodegate.cli", "pycodegate.output"] +message = "Keep shared data types independent of scanning and presentation." diff --git a/src/pycodegate/cli.py b/src/pycodegate/cli.py index cf8e635..74b77f2 100644 --- a/src/pycodegate/cli.py +++ b/src/pycodegate/cli.py @@ -67,7 +67,10 @@ def _maybe_run_fix(opts: CliOptions) -> None: def _build_config(opts: CliOptions): """Load config and apply CLI overrides.""" - config = load_config(opts.directory) + try: + config = load_config(opts.directory) + except ValueError as error: + raise click.ClickException(str(error)) from error config.lint = opts.lint config.dead_code = opts.dead_code config.verbose = opts.verbose diff --git a/src/pycodegate/config.py b/src/pycodegate/config.py index 7845233..a396ea8 100644 --- a/src/pycodegate/config.py +++ b/src/pycodegate/config.py @@ -6,6 +6,7 @@ from pathlib import Path from pycodegate._compat import tomllib +from pycodegate.types import ImportBoundary @dataclass @@ -19,6 +20,7 @@ class Config: profile: str | None = None per_file_suppress: dict[str, list[str]] = field(default_factory=dict) max_deduction: dict[str, int] = field(default_factory=dict) + import_boundaries: list[ImportBoundary] = field(default_factory=list) def load_config(project_path: str) -> Config: @@ -55,6 +57,7 @@ def _parse_doctor_toml(path: Path) -> Config: profile=options.get("profile", None), per_file_suppress=_read_per_file_suppress(data), max_deduction=_read_max_deduction(data), + import_boundaries=_read_import_boundaries(data), ) @@ -78,6 +81,7 @@ def _parse_pyproject_toml(path: Path) -> Config: profile=section.get("profile", None), per_file_suppress=_read_per_file_suppress(section), max_deduction=_read_max_deduction(section), + import_boundaries=_read_import_boundaries(section), ) @@ -86,6 +90,34 @@ def _read_per_file_suppress(table: dict) -> dict: return table.get("per-file-suppress") or table.get("per-file-ignores") or {} +def _read_import_boundaries(table: dict) -> list[ImportBoundary]: + boundaries = table.get("import-boundaries", []) + if not isinstance(boundaries, list): + raise ValueError("import-boundaries must be an array of tables") + result = [] + for boundary in boundaries: + if not isinstance(boundary, dict): + raise ValueError("Each import boundary must be a table") + for key in ("files", "forbidden"): + values = boundary.get(key) + if not isinstance(values, list) or not values: + raise ValueError(f"Import boundary {key} must be a nonempty array of strings") + if any(not isinstance(value, str) or not value.strip() for value in values): + raise ValueError(f"Import boundary {key} must contain nonempty strings") + message = boundary.get("message", "Move shared code behind the allowed layer's API") + if any( + not all(part.isidentifier() for part in module.split(".")) + for module in boundary["forbidden"] + ): + raise ValueError("Import boundary forbidden entries must be dotted module names") + if not isinstance(message, str) or not message.strip(): + raise ValueError("Import boundary message must be a nonempty string") + result.append( + ImportBoundary(tuple(boundary["files"]), tuple(boundary["forbidden"]), message) + ) + return result + + def _read_max_deduction(table: dict) -> dict: """Read scoring max-deduction overrides. diff --git a/src/pycodegate/rules/__init__.py b/src/pycodegate/rules/__init__.py index 73acda4..b6e9d8d 100644 --- a/src/pycodegate/rules/__init__.py +++ b/src/pycodegate/rules/__init__.py @@ -11,6 +11,7 @@ from pycodegate.rules.django import DjangoRules from pycodegate.rules.fastapi import FastAPIRules from pycodegate.rules.flask import FlaskRules +from pycodegate.rules.import_boundaries import ImportBoundaryRules as ImportBoundaryRules from pycodegate.rules.imports import ImportsRules as ImportsRules from pycodegate.rules.logging_rules import LoggingRules from pycodegate.rules.numpy_rules import NumpyRules diff --git a/src/pycodegate/rules/import_boundaries.py b/src/pycodegate/rules/import_boundaries.py new file mode 100644 index 0000000..319a7c3 --- /dev/null +++ b/src/pycodegate/rules/import_boundaries.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +import ast +import fnmatch +from pathlib import Path + +from pycodegate.rules.base import BaseRules +from pycodegate.types import Category, Diagnostic, ImportBoundary, Severity + + +class ImportBoundaryRules(BaseRules): + def __init__(self, project_path: str, boundaries: list[ImportBoundary]) -> None: + self.root = Path(project_path).resolve() + self.boundaries = boundaries + + def check(self, source: str, filename: str) -> list[Diagnostic]: + tree = self._parse(source) + if tree is None: + return [] + try: + relative = Path(filename).resolve().relative_to(self.root) + except ValueError: + return [] + boundaries = [ + boundary + for boundary in self.boundaries + if any(fnmatch.fnmatchcase(relative.as_posix(), pattern) for pattern in boundary.files) + ] + diagnostics = [] + for node in ast.walk(tree): + modules = self._imported_names(node, relative) + for boundary in boundaries: + forbidden = next( + (name for name in modules if self._forbidden(name, boundary.forbidden)), None + ) + if forbidden is not None: + diagnostics.append( + Diagnostic( + file_path=filename, + rule="imports/boundary", + severity=Severity.ERROR, + category=Category.IMPORTS, + message=f"Import '{forbidden}' violates an import boundary", + help=boundary.message, + line=node.lineno, + column=node.col_offset, + ) + ) + return diagnostics + + @staticmethod + def _forbidden(module: str, forbidden: tuple[str, ...]) -> bool: + return any(module == prefix or module.startswith(f"{prefix}.") for prefix in forbidden) + + @staticmethod + def _imported_names(node: ast.AST, relative: Path) -> list[str]: + if isinstance(node, ast.Import): + return [alias.name for alias in node.names] + if not isinstance(node, ast.ImportFrom): + return [] + module = node.module or "" + if node.level: + package = list(relative.parent.parts) + if package and package[0] == "src": + package = package[1:] + if node.level > len(package): + return [] + parent = package[: len(package) - node.level + 1] + module = ".".join([*parent, *([module] if module else [])]) + return [module, *(f"{module}.{alias.name}" for alias in node.names)] diff --git a/src/pycodegate/scan.py b/src/pycodegate/scan.py index b5d025f..c592f82 100644 --- a/src/pycodegate/scan.py +++ b/src/pycodegate/scan.py @@ -12,7 +12,7 @@ from pycodegate.constants import RULES_SUPPRESSED_IN_TESTS from pycodegate.discover import discover_project from pycodegate.profile import PROFILES, detect_profile -from pycodegate.rules import get_all_rule_sets, get_import_gated_rules +from pycodegate.rules import ImportBoundaryRules, get_all_rule_sets, get_import_gated_rules from pycodegate.rules.dead_code import DeadCodeRules from pycodegate.rules.dependencies import DependencyRules from pycodegate.rules.imports import ImportsRules @@ -81,7 +81,9 @@ def _run_checks( """Run lint + dead code + imports + structure + dependency checks in parallel.""" str_files = [str(f) for f in files] with ThreadPoolExecutor(max_workers=5) as executor: - lint_future = executor.submit(_run_lint, files, config) if config.lint else None + lint_future = ( + executor.submit(_run_lint, files, config, project_path) if config.lint else None + ) dead_code_future = ( executor.submit(_run_dead_code, project_path, config) if config.dead_code else None ) @@ -190,9 +192,12 @@ def _matches_ignore(file_path: str, patterns: list[str], root: Path) -> bool: def _run_lint( files: list[Path], config: Config, + project_path: str = ".", ) -> list[Diagnostic]: """Run core rules on every file; library rules only on files importing the library.""" core_rules = get_all_rule_sets() + if config.import_boundaries: + core_rules.append(ImportBoundaryRules(project_path, config.import_boundaries)) gated_rules = get_import_gated_rules() diags: list[Diagnostic] = [] diff --git a/src/pycodegate/types.py b/src/pycodegate/types.py index a5cc9c8..5491d26 100644 --- a/src/pycodegate/types.py +++ b/src/pycodegate/types.py @@ -11,6 +11,13 @@ class Severity(str, Enum): WARNING = "warning" +@dataclass(frozen=True) +class ImportBoundary: + files: tuple[str, ...] + forbidden: tuple[str, ...] + message: str + + class Category(str, Enum): SECURITY = "Security" PERFORMANCE = "Performance" diff --git a/tests/rules/test_import_boundaries.py b/tests/rules/test_import_boundaries.py new file mode 100644 index 0000000..fa1ae65 --- /dev/null +++ b/tests/rules/test_import_boundaries.py @@ -0,0 +1,135 @@ +import pytest +from click.testing import CliRunner + +from pycodegate.cli import main +from pycodegate.config import Config, load_config +from pycodegate.rules.import_boundaries import ImportBoundaryRules +from pycodegate.scan import scan_project +from pycodegate.types import ImportBoundary, Severity + + +@pytest.mark.parametrize( + "source", + [ + "import app.infrastructure.database as database", + "from app.infrastructure import database", + "from app import infrastructure", + "from ..infrastructure import database", + "from .. import infrastructure", + "def load():\n import app.infrastructure.database", + "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import app.infrastructure", + ], +) +@pytest.mark.parametrize("source_root", ["", "src/"]) +def test_forbidden_imports(tmp_path, source, source_root): + filename = tmp_path / f"{source_root}app/domain/service.py" + rules = ImportBoundaryRules( + str(tmp_path), + [ImportBoundary(("**/domain/*.py",), ("app.infrastructure",), "Use a domain port")], + ) + diagnostics = rules.check(source, str(filename)) + assert len(diagnostics) == 1 + assert diagnostics[0].rule == "imports/boundary" + assert diagnostics[0].severity == Severity.ERROR + assert diagnostics[0].help == "Use a domain port" + + +@pytest.mark.parametrize( + "source,filename", + [ + ("import app.infrastructure_extra", "app/domain/service.py"), + ("from app import domain", "app/domain/service.py"), + ("from . import infrastructure", "app/domain/service.py"), + ("import app.infrastructure", "app/api/service.py"), + ("text = 'import app.infrastructure'", "app/domain/service.py"), + ("broken syntax!", "app/domain/service.py"), + ], +) +def test_allowed_code(tmp_path, source, filename): + rules = ImportBoundaryRules( + str(tmp_path), + [ImportBoundary(("app/domain/*.py",), ("app.infrastructure",), "Use a port")], + ) + assert rules.check(source, str(tmp_path / filename)) == [] + + +@pytest.mark.parametrize("config_file", ["pycodegate.toml", "pyproject.toml"]) +@pytest.mark.parametrize("output_flag", ["--json", "--sarif"]) +def test_configured_boundary_blocks_cli_and_can_be_suppressed(tmp_path, config_file, output_flag): + prefix = "tool.pycodegate." if config_file == "pyproject.toml" else "" + (tmp_path / config_file).write_text( + f'[[{prefix}import-boundaries]]\nfiles = ["*.py"]\n' + 'forbidden = ["requests"]\nmessage = "Use the shared HTTP client"\n' + ) + (tmp_path / "service.py").write_text("import requests\n") + config = load_config(str(tmp_path)) + assert config.import_boundaries == [ + ImportBoundary(("*.py",), ("requests",), "Use the shared HTTP client") + ] + result = CliRunner().invoke(main, [str(tmp_path), output_flag, "--fail-on", "error"]) + assert result.exit_code == 1 + assert "imports/boundary" in result.output + config.per_file_suppress = {"service.py": ["imports/boundary"]} + assert not any( + diagnostic.rule == "imports/boundary" + for diagnostic in scan_project(str(tmp_path), config).diagnostics + ) + + +def test_boundaries_are_opt_in_and_follow_lint_setting(tmp_path): + (tmp_path / "service.py").write_text("import requests\n") + for config in [ + Config(), + Config(lint=False, import_boundaries=[ImportBoundary(("*.py",), ("requests",), "No")]), + ]: + assert not any( + diagnostic.rule == "imports/boundary" + for diagnostic in scan_project(str(tmp_path), config).diagnostics + ) + + +@pytest.mark.parametrize( + "setting", + [ + 'files = "*.py"\nforbidden = ["requests"]', + 'files = ["*.py"]\nforbidden = []', + 'files = ["*.py"]\nforbidden = [42]', + 'files = ["*.py"]\nforbidden = ["requests.*"]', + 'files = ["*.py"]\nforbidden = ["requests"]\nmessage = ""', + ], +) +def test_invalid_boundary_is_rejected(tmp_path, setting): + (tmp_path / "pycodegate.toml").write_text(f"[[import-boundaries]]\n{setting}\n") + with pytest.raises(ValueError, match="Import boundary"): + load_config(str(tmp_path)) + result = CliRunner().invoke(main, [str(tmp_path)]) + assert result.exit_code == 1 + assert result.output.startswith("Error: Import boundary") + + +def test_nested_import_location_and_package_init(tmp_path): + rules = ImportBoundaryRules( + str(tmp_path), + [ImportBoundary(("src/app/domain/*.py",), ("app.infrastructure",), "Use a port")], + ) + diagnostics = rules.check( + "def load():\n from ..infrastructure import database\n", + str(tmp_path / "src/app/domain/__init__.py"), + ) + assert diagnostics[0].line == 2 + assert diagnostics[0].column == 4 + + +def test_outside_root_and_invalid_relative_import_are_ignored(tmp_path): + rules = ImportBoundaryRules( + str(tmp_path), [ImportBoundary(("*.py",), ("requests",), "Use a client")] + ) + assert rules.check("import requests", str(tmp_path.parent / "outside.py")) == [] + assert rules.check("from .. import requests", str(tmp_path / "module.py")) == [] + + +@pytest.mark.parametrize("contents", ['import-boundaries = "invalid"', "import-boundaries = [42]"]) +def test_invalid_boundary_table_is_rejected(tmp_path, contents): + (tmp_path / "pycodegate.toml").write_text(contents) + with pytest.raises(ValueError, match="[Ii]mport[- ]boundar"): + load_config(str(tmp_path)) diff --git a/uv.lock b/uv.lock index 18867b9..ae6de52 100644 --- a/uv.lock +++ b/uv.lock @@ -203,7 +203,7 @@ wheels = [ [[package]] name = "pycodegate" -version = "0.4.1" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "click" },