|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Fail when configured Ruff diagnostics touch lines added by a Git diff.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import json |
| 8 | +import os |
| 9 | +import re |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +HUNK_HEADER = re.compile( |
| 15 | + r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@" |
| 16 | +) |
| 17 | + |
| 18 | + |
| 19 | +def _git_output(*arguments: str, binary: bool = False) -> str | bytes: |
| 20 | + result = subprocess.run( |
| 21 | + ("git", *arguments), |
| 22 | + check=True, |
| 23 | + capture_output=True, |
| 24 | + text=not binary, |
| 25 | + ) |
| 26 | + return result.stdout |
| 27 | + |
| 28 | + |
| 29 | +def _changed_python_files(base: str, head: str | None) -> tuple[Path, ...]: |
| 30 | + revision_arguments = (base, head) if head is not None else (base,) |
| 31 | + output = _git_output( |
| 32 | + "diff", |
| 33 | + "--name-only", |
| 34 | + "--diff-filter=ACMR", |
| 35 | + "-z", |
| 36 | + *revision_arguments, |
| 37 | + "--", |
| 38 | + "*.py", |
| 39 | + binary=True, |
| 40 | + ) |
| 41 | + assert isinstance(output, bytes) |
| 42 | + return tuple( |
| 43 | + Path(os.fsdecode(path)) |
| 44 | + for path in output.split(b"\0") |
| 45 | + if path |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +def _added_lines( |
| 50 | + path: Path, |
| 51 | + base: str, |
| 52 | + head: str | None, |
| 53 | +) -> frozenset[int]: |
| 54 | + revision_arguments = (base, head) if head is not None else (base,) |
| 55 | + output = _git_output( |
| 56 | + "diff", |
| 57 | + "--unified=0", |
| 58 | + "--no-ext-diff", |
| 59 | + "--no-color", |
| 60 | + *revision_arguments, |
| 61 | + "--", |
| 62 | + os.fspath(path), |
| 63 | + ) |
| 64 | + assert isinstance(output, str) |
| 65 | + added: set[int] = set() |
| 66 | + for line in output.splitlines(): |
| 67 | + match = HUNK_HEADER.match(line) |
| 68 | + if match is None: |
| 69 | + continue |
| 70 | + first_line = int(match.group(1)) |
| 71 | + line_count = int(match.group(2) or "1") |
| 72 | + added.update(range(first_line, first_line + line_count)) |
| 73 | + return frozenset(added) |
| 74 | + |
| 75 | + |
| 76 | +def _ruff_diagnostics(paths: tuple[Path, ...]) -> list[dict[str, object]]: |
| 77 | + result = subprocess.run( |
| 78 | + ("ruff", "check", "--output-format=json", *(os.fspath(path) for path in paths)), |
| 79 | + check=False, |
| 80 | + capture_output=True, |
| 81 | + text=True, |
| 82 | + ) |
| 83 | + try: |
| 84 | + diagnostics = json.loads(result.stdout) |
| 85 | + except json.JSONDecodeError as error: |
| 86 | + raise RuntimeError( |
| 87 | + "Ruff did not return JSON diagnostics.\n" |
| 88 | + f"stdout:\n{result.stdout}\n" |
| 89 | + f"stderr:\n{result.stderr}" |
| 90 | + ) from error |
| 91 | + if result.returncode not in {0, 1}: |
| 92 | + raise RuntimeError( |
| 93 | + f"Ruff failed with exit code {result.returncode}:\n{result.stderr}" |
| 94 | + ) |
| 95 | + return diagnostics |
| 96 | + |
| 97 | + |
| 98 | +def _github_escape(value: object) -> str: |
| 99 | + return ( |
| 100 | + str(value) |
| 101 | + .replace("%", "%25") |
| 102 | + .replace("\r", "%0D") |
| 103 | + .replace("\n", "%0A") |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def _relative_diagnostic_path(filename: object) -> Path: |
| 108 | + path = Path(str(filename)) |
| 109 | + if path.is_absolute(): |
| 110 | + return path.relative_to(Path.cwd()) |
| 111 | + return path |
| 112 | + |
| 113 | + |
| 114 | +def main() -> int: |
| 115 | + parser = argparse.ArgumentParser(description=__doc__) |
| 116 | + parser.add_argument("--base", required=True, help="Git revision before the change") |
| 117 | + parser.add_argument( |
| 118 | + "--head", |
| 119 | + help="Git revision after the change; omit to inspect the current worktree", |
| 120 | + ) |
| 121 | + arguments = parser.parse_args() |
| 122 | + |
| 123 | + changed_paths = _changed_python_files(arguments.base, arguments.head) |
| 124 | + if not changed_paths: |
| 125 | + print("No changed Python files.") |
| 126 | + return 0 |
| 127 | + |
| 128 | + line_index = { |
| 129 | + path: _added_lines(path, arguments.base, arguments.head) |
| 130 | + for path in changed_paths |
| 131 | + } |
| 132 | + introduced = [] |
| 133 | + for diagnostic in _ruff_diagnostics(changed_paths): |
| 134 | + path = _relative_diagnostic_path(diagnostic["filename"]) |
| 135 | + location = diagnostic["location"] |
| 136 | + assert isinstance(location, dict) |
| 137 | + row = int(location["row"]) |
| 138 | + if row in line_index.get(path, frozenset()): |
| 139 | + introduced.append((path, row, location, diagnostic)) |
| 140 | + |
| 141 | + if not introduced: |
| 142 | + print( |
| 143 | + "Configured Ruff rules report no diagnostics on added Python lines " |
| 144 | + f"across {len(changed_paths)} changed files." |
| 145 | + ) |
| 146 | + return 0 |
| 147 | + |
| 148 | + for path, row, location, diagnostic in introduced: |
| 149 | + code = diagnostic["code"] |
| 150 | + message = diagnostic["message"] |
| 151 | + print( |
| 152 | + f"::error file={_github_escape(path)},line={row}," |
| 153 | + f"col={location['column']},title=Ruff {code}::" |
| 154 | + f"{_github_escape(message)}" |
| 155 | + ) |
| 156 | + print(f"{len(introduced)} Ruff diagnostics touch added Python lines.") |
| 157 | + return 1 |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + sys.exit(main()) |
0 commit comments