File size: 8,254 Bytes
3ccdcc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
"""Forward-looking ruff lint gate for hermes-webui.

The Python twin of the ESLint runtime guard (``npm run lint:runtime``). It runs the
curated ``[tool.ruff]`` ruleset from ``pyproject.toml`` (E9 + F + B) but enforces it
**only on new / changed code**, so it keeps incoming PRs clean without demanding a
big-bang reformat of the existing tree (which still carries a cosmetic
unused-import backlog — see issue #3273).

Two modes:

  --diff [BASE]   Line-scoped gate (default mode). Only report findings on lines
                  that this branch ADDED or MODIFIED relative to the merge-base
                  with BASE (default: origin/master). Editing a legacy file that
                  has pre-existing violations elsewhere is safe — only your own
                  new lines are gated. Exit 1 if any new finding, else 0.

  --all           Whole-tree report (informational). Runs the curated ruleset over
                  every tracked .py file and prints the backlog. Exit 0 always
                  unless --strict is also passed. Useful for tracking the cleanup
                  progress of #3273; NOT used as a release blocker.

Usage::

    python3 scripts/ruff_lint.py --diff origin/master     # the CI / pre-release gate
    python3 scripts/ruff_lint.py --all                    # backlog report
    python3 scripts/ruff_lint.py --all --strict           # fail on ANY tree finding

ruff is resolved from PATH, or run via ``uvx ruff`` / ``python -m ruff`` as a
fallback. If ruff cannot be found at all the gate prints a notice and exits 0 (a
dev without ruff is not blocked; CI installs ruff so enforcement still holds there —
same contract as the ESLint guard).
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from collections import defaultdict

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def _run(cmd: list[str], **kw) -> subprocess.CompletedProcess:
    return subprocess.run(
        cmd, cwd=REPO_ROOT, capture_output=True, text=True, **kw
    )


def _ruff_cmd() -> list[str] | None:
    """Return the argv prefix that invokes ruff, or None if unavailable."""
    if shutil.which("ruff"):
        return ["ruff"]
    # `python -m ruff` works when ruff is pip-installed in the active interpreter.
    probe = _run([sys.executable, "-m", "ruff", "--version"])
    if probe.returncode == 0:
        return [sys.executable, "-m", "ruff"]
    # uvx pulls a pinned ruff on demand (used in local dev boxes without a global ruff).
    if shutil.which("uvx"):
        probe = _run(["uvx", "ruff", "--version"])
        if probe.returncode == 0:
            return ["uvx", "ruff"]
    return None


def _changed_py_files(base: str) -> tuple[str, list[str]]:
    """Resolve the merge-base with `base` and return (merge_base, changed .py files)."""
    mb = _run(["git", "merge-base", base, "HEAD"])
    merge_base = mb.stdout.strip() if mb.returncode == 0 and mb.stdout.strip() else base
    diff = _run(
        ["git", "diff", "--name-only", "--diff-filter=ACMR", merge_base, "HEAD"]
    )
    files = [
        f
        for f in diff.stdout.splitlines()
        if f.endswith(".py") and os.path.exists(os.path.join(REPO_ROOT, f))
    ]
    return merge_base, files


_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")


def _added_lines(merge_base: str, path: str) -> set[int]:
    """Set of NEW-file line numbers added or modified in `path` since merge_base."""
    diff = _run(["git", "diff", "--unified=0", merge_base, "HEAD", "--", path])
    added: set[int] = set()
    new_ln = 0
    for line in diff.stdout.splitlines():
        m = _HUNK_RE.match(line)
        if m:
            new_ln = int(m.group(1))
            continue
        if line.startswith("+") and not line.startswith("+++"):
            added.add(new_ln)
            new_ln += 1
        elif line.startswith("-") and not line.startswith("---"):
            # deletion: new-file pointer does not advance
            continue
        elif not line.startswith(("@@", "diff ", "index ", "--- ", "+++ ")):
            new_ln += 1
    return added


def _ruff_check_json(ruff: list[str], files: list[str]) -> list[dict]:
    """Run ruff over `files` with the project config, return parsed JSON findings."""
    if not files:
        return []
    proc = _run(ruff + ["check", "--output-format", "json", "--no-cache", *files])
    out = proc.stdout.strip()
    if not out:
        return []
    try:
        return json.loads(out)
    except json.JSONDecodeError:
        sys.stderr.write(
            "ruff_lint: could not parse ruff JSON output:\n" + proc.stdout + proc.stderr
        )
        # Be conservative: surface as a failure so a broken invocation never
        # silently green-lights a PR.
        raise


def _print_findings(findings: list[dict]) -> None:
    by_file: dict[str, list[dict]] = defaultdict(list)
    for f in findings:
        by_file[f.get("filename", "?")].append(f)
    for fname in sorted(by_file):
        rel = os.path.relpath(fname, REPO_ROOT)
        for f in sorted(by_file[fname], key=lambda x: (x["location"]["row"], x["location"]["column"])):
            loc = f["location"]
            code = f.get("code") or "?"
            msg = f.get("message", "").strip()
            print(f"  {rel}:{loc['row']}:{loc['column']}  {code}  {msg}")


def run_diff(base: str) -> int:
    ruff = _ruff_cmd()
    if ruff is None:
        print("ruff_lint: ruff not found on PATH — skipping (CI installs ruff). OK.")
        return 0
    merge_base, files = _changed_py_files(base)
    if not files:
        print(f"ruff_lint: no changed .py files vs {base} ({merge_base[:12]}). OK.")
        return 0

    all_findings = _ruff_check_json(ruff, files)
    # Build the added-line map once per file, intersect.
    added_map = {f: _added_lines(merge_base, f) for f in files}
    new_findings = []
    for finding in all_findings:
        rel = os.path.relpath(finding.get("filename", ""), REPO_ROOT)
        row = finding.get("location", {}).get("row")
        if rel in added_map and row in added_map[rel]:
            new_findings.append(finding)

    print(
        f"ruff_lint (diff vs {base}): {len(files)} changed .py file(s), "
        f"{len(all_findings)} total finding(s) in them, "
        f"{len(new_findings)} on added/modified lines."
    )
    if new_findings:
        print("\nNew ruff violations introduced by this change:\n")
        _print_findings(new_findings)
        print(
            "\nThe curated ruff gate (E9+F+B) flags NEW code only. Fix the lines above, "
            "or — if a finding is a genuine false positive — add a scoped "
            "`# noqa: <CODE>` with a one-line reason. Config: pyproject.toml [tool.ruff]."
        )
        return 1
    print("ruff_lint: no new violations on added/modified lines. OK.")
    return 0


def run_all(strict: bool) -> int:
    ruff = _ruff_cmd()
    if ruff is None:
        print("ruff_lint: ruff not found on PATH — skipping. OK.")
        return 0
    proc = _run(ruff + ["check", "--statistics", "--no-cache", "."])
    sys.stdout.write(proc.stdout)
    sys.stderr.write(proc.stderr)
    if strict and proc.returncode != 0:
        return proc.returncode
    print(
        "\nruff_lint --all is informational (existing-tree backlog tracked in #3273). "
        "Pass --strict to fail on any finding."
    )
    return 0


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    g = p.add_mutually_exclusive_group()
    g.add_argument(
        "--diff",
        nargs="?",
        const="origin/master",
        metavar="BASE",
        help="Line-scoped gate vs merge-base with BASE (default origin/master).",
    )
    g.add_argument("--all", action="store_true", help="Whole-tree backlog report.")
    p.add_argument("--strict", action="store_true", help="With --all: fail on any finding.")
    args = p.parse_args(argv)

    if args.all:
        return run_all(args.strict)
    base = args.diff or "origin/master"
    return run_diff(base)


if __name__ == "__main__":
    raise SystemExit(main())