import hashlib import json import os import subprocess import sys from collections import Counter from dataclasses import asdict, dataclass from datetime import datetime, timezone from pathlib import Path from tempfile import NamedTemporaryFile BASELINE_SCHEMA_VERSION = 1 class LintBaselineError(RuntimeError): """Raised when a baseline cannot safely be created, loaded, or compared.""" @dataclass(frozen=True) class LintBaseline: schema_version: int project_name: str project_path: str linter: str linter_version: str command: str captured_at: str git_head: str | None diagnostic_fingerprints: list[str] @property def diagnostic_count(self) -> int: return len(self.diagnostic_fingerprints) def to_json(self) -> dict: return asdict(self) @classmethod def from_json(cls, data: object) -> "LintBaseline": if not isinstance(data, dict): raise LintBaselineError("Lint baseline must contain a JSON object.") try: baseline = cls( schema_version=int(data["schema_version"]), project_name=str(data["project_name"]), project_path=str(data["project_path"]), linter=str(data["linter"]), linter_version=str(data["linter_version"]), command=str(data["command"]), captured_at=str(data["captured_at"]), git_head=str(data["git_head"]) if data.get("git_head") else None, diagnostic_fingerprints=[str(value) for value in data["diagnostic_fingerprints"]], ) except (KeyError, TypeError, ValueError) as exc: raise LintBaselineError(f"Lint baseline is malformed: {exc}") from exc if baseline.schema_version != BASELINE_SCHEMA_VERSION: raise LintBaselineError(f"Unsupported lint baseline schema: {baseline.schema_version}.") return baseline @dataclass(frozen=True) class RuffLintRun: version: str fingerprints: list[str] diagnostics: list[dict] @property def diagnostic_count(self) -> int: return len(self.fingerprints) def capture_ruff_baseline( project_dir: Path, project_name: str, *, python_executable: str | Path | None = None ) -> LintBaseline: project_dir = project_dir.resolve() python = str(python_executable or sys.executable) lint_run = run_ruff_json(project_dir, python_executable=python) return LintBaseline( schema_version=BASELINE_SCHEMA_VERSION, project_name=project_name, project_path=_canonical_path(project_dir), linter="ruff", linter_version=lint_run.version, command=f'"{python}" -m ruff check --output-format json .', captured_at=datetime.now(timezone.utc).isoformat(), git_head=_git_head(project_dir), diagnostic_fingerprints=lint_run.fingerprints, ) def save_baseline(path: Path, baseline: LintBaseline) -> None: path.parent.mkdir(parents=True, exist_ok=True) with NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as temp: json.dump(baseline.to_json(), temp, indent=2, sort_keys=True) temp.write("\n") temp_path = Path(temp.name) temp_path.replace(path) def load_baseline(path: Path) -> LintBaseline: if not path.is_file(): raise LintBaselineError(f"Lint baseline not found: {path}") try: return LintBaseline.from_json(json.loads(path.read_text(encoding="utf-8"))) except json.JSONDecodeError as exc: raise LintBaselineError(f"Lint baseline is not valid JSON: {path}") from exc def validate_ruff_baseline( baseline: LintBaseline, project_dir: Path, project_name: str, current_version: str, ) -> None: if baseline.project_name != project_name: raise LintBaselineError( f"Lint baseline project mismatch: expected {project_name}, found {baseline.project_name}." ) if _canonical_path(project_dir) != baseline.project_path: raise LintBaselineError("Lint baseline project path does not match the active project.") if baseline.linter != "ruff": raise LintBaselineError(f"Lint baseline is for {baseline.linter}, not ruff.") if baseline.linter_version != current_version: raise LintBaselineError( "Lint baseline Ruff version does not match the active Ruff version. " "Refresh the baseline explicitly." ) def run_ruff_json( project_dir: Path, *, python_executable: str | Path | None = None ) -> RuffLintRun: python = str(python_executable or sys.executable) command = [python, "-m", "ruff", "check", "--output-format", "json", "."] result = _run(command, project_dir, timeout=120) if result.returncode not in {0, 1}: output = (result.stderr or result.stdout or "").strip() raise LintBaselineError(f"Ruff baseline command failed: {output or result.returncode}") try: raw_diagnostics = json.loads(result.stdout or "[]") except json.JSONDecodeError as exc: raise LintBaselineError("Ruff did not return valid JSON diagnostics.") from exc if not isinstance(raw_diagnostics, list): raise LintBaselineError("Ruff JSON diagnostics must be a list.") return RuffLintRun( version=_ruff_version(project_dir, python_executable=python), diagnostics=raw_diagnostics, fingerprints=[_diagnostic_fingerprint(project_dir, item) for item in raw_diagnostics], ) def introduced_diagnostics( baseline: LintBaseline, lint_run: RuffLintRun, ) -> list[dict]: remaining = Counter(baseline.diagnostic_fingerprints) introduced: list[dict] = [] for diagnostic, fingerprint in zip(lint_run.diagnostics, lint_run.fingerprints, strict=True): if remaining[fingerprint]: remaining[fingerprint] -= 1 else: introduced.append(diagnostic) return introduced def format_diagnostic_summary(diagnostics: list[dict], limit: int = 10) -> str: if not diagnostics: return "" lines: list[str] = [] for diagnostic in diagnostics[:limit]: filename = str(diagnostic.get("filename", "")) location = diagnostic.get("location") or {} row = location.get("row", "?") if isinstance(location, dict) else "?" code = str(diagnostic.get("code", "RUFF")) message = str(diagnostic.get("message", "Lint diagnostic")) lines.append(f"{filename}:{row}: {code} {message}") if len(diagnostics) > limit: lines.append(f"... {len(diagnostics) - limit} more introduced diagnostics") return "\n".join(lines) def compare_ruff_baseline(baseline_path: Path, project_dir: Path, project_name: str) -> str: """Return a read-only current-vs-baseline Ruff comparison summary.""" try: baseline = load_baseline(baseline_path) lint_run = run_ruff_json(project_dir) validate_ruff_baseline(baseline, project_dir, project_name, lint_run.version) except LintBaselineError as exc: return f"Error: Cannot compare Ruff baseline: {exc}" introduced = introduced_diagnostics(baseline, lint_run) summary = ( f"Baseline diagnostics: {baseline.diagnostic_count}\n" f"Current diagnostics: {lint_run.diagnostic_count}\n" f"Introduced diagnostics: {len(introduced)}" ) details = format_diagnostic_summary(introduced) return f"{summary}\n{details}" if details else summary def _run(command: list[str], project_dir: Path, timeout: int) -> subprocess.CompletedProcess[str]: try: return subprocess.run( command, cwd=str(project_dir), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, ) except subprocess.TimeoutExpired as exc: raise LintBaselineError(f"Command timed out: {' '.join(command)}") from exc def _ruff_version(project_dir: Path, *, python_executable: str | Path | None = None) -> str: python = str(python_executable or sys.executable) result = _run([python, "-m", "ruff", "--version"], project_dir, timeout=30) if result.returncode != 0: output = (result.stderr or result.stdout or "").strip() raise LintBaselineError(f"Could not determine Ruff version: {output or result.returncode}") return (result.stdout or "").strip() def _git_head(project_dir: Path) -> str | None: try: result = _run(["git", "rev-parse", "HEAD"], project_dir, timeout=30) except LintBaselineError: return None if result.returncode != 0: return None return (result.stdout or "").strip() or None def _diagnostic_fingerprint(project_dir: Path, diagnostic: object) -> str: if not isinstance(diagnostic, dict): raise LintBaselineError("Ruff returned a malformed diagnostic.") relative_path = _relative_diagnostic_path(project_dir, str(diagnostic.get("filename", ""))) code = str(diagnostic.get("code", "")) message = str(diagnostic.get("message", "")) source_line = _source_line(project_dir / relative_path, diagnostic.get("location")) payload = "\0".join((relative_path, code, message, source_line)) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def _relative_diagnostic_path(project_dir: Path, filename: str) -> str: if not filename: raise LintBaselineError("Ruff diagnostic did not include a filename.") source_path = Path(filename) if not source_path.is_absolute(): source_path = project_dir / source_path try: return source_path.resolve().relative_to(project_dir.resolve()).as_posix() except ValueError as exc: raise LintBaselineError(f"Ruff diagnostic is outside the project: {filename}") from exc def _source_line(path: Path, location: object) -> str: row = location.get("row") if isinstance(location, dict) else None if not isinstance(row, int) or row < 1 or not path.is_file(): return "" lines = path.read_text(encoding="utf-8", errors="replace").splitlines() if row > len(lines): return "" return " ".join(lines[row - 1].strip().split()) def _canonical_path(path: Path) -> str: return os.path.normcase(str(path.resolve()))