From e33494f6961fe88ff45a9d977d9c21f61596bb53 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 1 Nov 2026 10:53:12 -0800 Subject: [PATCH 1/2] Report What a Move or a Shebang Edit Adds in the Prose Gate's Diff Mode A moved file is now checked twice, at its old path and its new one, and reports only the findings the new path adds. That covers a move off a Compose name and a move into another directory, which the hand-kept path_readings table missed, and replaces that table. An edit that changes a file's lexer through its first line now reads the file whole, as a move changing its lexer already did. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose_lint.py | 114 +++++++++++--------- tests/test_prose_lint.py | 128 ++++++++++++++++++++--- 2 files changed, 175 insertions(+), 67 deletions(-) diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index 15844099f..6b296aa9c 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -41,6 +41,7 @@ import sys import unicodedata from bisect import bisect_right +from collections import Counter from collections.abc import Callable, Iterable from pathlib import Path from typing import Any, NamedTuple @@ -282,28 +283,28 @@ def changed_lines( root: Path, excludes: tuple[str, ...] = (), paths: list[str] | None = None, - whole: dict[str, frozenset[str]] | None = None, + moves: dict[str, str] | None = None, ) -> dict[str, set[int]] | None: """Map path -> lines this tree adds vs `base`, an untracked or undiffable text file in full. No run read a file in a generated tree, an excluded path, or a path outside `paths`. So a file - moved out of one is read in full too, as is one whose move changes the lexer it reads through. - Only directories narrow. A list naming a file is what a hook passes from a commit, which says - what this run reads rather than what every run does. A move changing what its path - decides for a rule is read in full for that rule alone, recorded in `whole`. Any other move - adds only what it changed. + moved out of one is read in full too. So is one whose lexer the change alters, by its path or + its first line. Only directories narrow. A list naming a file is what a hook passes from a + commit, which says what this run reads rather than what every run does. Any other move adds + what it changed, and `moves` records its source so a run reports what the new path adds. """ raw = git_bytes(root, DIFF_ARGS, base) undiffable = undiffable_paths(base, root) if raw is not None else None if raw is None or undiffable is None: return None - config = config_for(str(root)) - trees = config.exempt["generated_trees"] + trees = config_for(str(root)).exempt["generated_trees"] narrowed = paths is not None and all(Path(p).is_dir() for p in paths) asked = [repo_key(Path(p), root) for p in paths] if paths is not None and narrowed else None out: dict[str, set[int]] = {} unread: list[str] = [] moved: dict[str, str] = {} + # The first line a file held at `base`, where a hunk reaches it, or None until its `-` line. + firsts: dict[str, str | None] = {} cur = None source = "" # A header is honored only in the block a `diff --git` line opens, which content cannot forge. @@ -332,39 +333,46 @@ def changed_lines( out.setdefault(cur, set()) elif line.startswith("@@") and cur: in_header = False - m = re.search(r"\+(\d+)(?:,(\d+))?", line) + m = re.search(r"-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?", line) if m: - start = int(m.group(1)) - out[cur].update(range(start, start + int(m.group(2) or 1))) - for dest, source in moved.items(): - if not is_text(root / dest): + start, count = int(m.group(3)), int(m.group(4) or 1) + out[cur].update(range(start, start + count)) + if m.group(1) == "0": + # Lines inserted above the first, which now sits below them. + firsts[cur] = nth_line(root / cur, count + 1) + elif m.group(1) == "1" and m.group(2) != "0": + firsts[cur] = None + elif line.startswith("-") and cur and cur in firsts and firsts[cur] is None: + firsts[cur] = line[1:].rstrip("\r") + for name in sorted(out.keys() | moved.keys()): + if name not in firsts and name not in moved: + continue + if name in unread or not (root / name).is_file() or not is_text(root / name): continue - first = (root / dest).read_bytes().split(b"\n", 1)[0].decode("utf-8", "replace") - before = path_readings(root / source, root, config, first.rstrip("\r")) - after = path_readings(root / dest, root, config, first.rstrip("\r")) - if before["*"] != after["*"]: - unread.append(dest) - elif rules := frozenset(r for r in after if r != "*" and before[r] != after[r]): - out.setdefault(dest, set()) - if whole is not None: - whole[dest] = rules + first = nth_line(root / name, 1) + was = firsts.get(name, first) + # A `-` line the parse never reached leaves the old lexer unknown, read as changed. + if was is None or lexer_name(root / moved.get(name, name), was) != lexer_name( + root / name, first + ): + unread.append(name) + elif name in moved: + out.setdefault(name, set()) + if moves is not None: + moves[name] = moved[name] for name in [*undiffable, *untracked_paths(root), *unread]: if is_text(root / name): out[name] = set(range(1, len((root / name).read_bytes().splitlines()) + 1)) return out -def path_readings(path: Path, root: Path, config: Config, first: str) -> dict[str, object]: - """Whether a rule reads a file at all, or the lexer every rule reads it through, as `*`. - - Only these leave a path's every line unread by a rule, so a move changing one is new to it. - """ - exempt = exempt_rules(path, root, config) - return { - **{rule: rule in exempt for rule in FILE_EXEMPTION}, - "*": lexer_name(path, first), - "issue-ref": is_instruction_text(path, root), - } +def nth_line(path: Path, n: int) -> str: + """Line `n` of `path`, counted from 1, or empty where the file holds fewer lines or none.""" + try: + lines = path.read_bytes().split(b"\n", n) + except OSError: + return "" + return lines[n - 1].decode("utf-8", "replace").rstrip("\r") if len(lines) >= n else "" def exempt_rules(path: Path, root: Path, config: Config) -> frozenset[str]: @@ -1928,8 +1936,9 @@ def check_file( allowed: set[int] | None = None, plain: list[Path] | None = None, undecoded: list[Path] | None = None, + at: Path | None = None, ) -> list[Finding]: - """Every finding the rules in `rules` make on `path`. + """Every finding the rules in `rules` make on `path`, judged as sitting at `at` where given. `plain` collects a file with no lexer and `undecoded` one that is not UTF-8, since each is otherwise counted as read with nothing found. A byte order mark is judged on its own. @@ -1944,12 +1953,13 @@ def check_file( text = decoded.removeprefix(bom) out = [f for f in charset_findings(1, bom) if f[1] in rules] if text != decoded else [] lex = any(RULE_TABLE[r][1] - {"source", "prose", "code"} for r in rules) - units, fenced, read_plain = extract(path, text, lex) + judged = at or path + units, fenced, read_plain = extract(judged, text, lex) if read_plain and plain is not None: plain.append(path) - lexer = lexer_name(path, text.split("\n", 1)[0].rstrip("\r")) + lexer = lexer_name(judged, text.split("\n", 1)[0].rstrip("\r")) config = config_for(str(root) if root else None) - ctx = Context(path, root, fenced, language_of(lexer) or {}, config, allowed) + ctx = Context(judged, root, fenced, language_of(lexer) or {}, config, allowed) units = [without_metadata_blocks(unit, ctx) for unit in units] passes: dict[Rule, set[str]] = {} for name in RULE_TABLE: @@ -2034,9 +2044,9 @@ def main(argv: list[str] | None = None) -> int: return 0 discovered = len(files) # Presence rather than truthiness, since an empty value is a base that failed to compute. - whole: dict[str, frozenset[str]] = {} + moves: dict[str, str] = {} scope = ( - changed_lines(a.diff, scan_root, tuple(a.exclude), scan_paths, whole) + changed_lines(a.diff, scan_root, tuple(a.exclude), scan_paths, moves) if a.diff is not None else None ) @@ -2060,22 +2070,26 @@ def main(argv: list[str] | None = None) -> int: undecoded: list[Path] = [] for f in files: allowed = scope.get(keys[f]) if scope is not None else None - for ln, kind, msg in check_file(f, rules, scan_root, allowed, plain, undecoded): - if allowed is not None and ln not in allowed and kind not in whole.get(keys[f], ()): - continue + findings = check_file(f, rules, scan_root, allowed, plain, undecoded) + # A moved file reports what its new path finds beyond what the old one did, not the backlog. + added = ( + Counter(findings) + - Counter(check_file(f, rules, scan_root, allowed, at=scan_root / moves[keys[f]])) + if keys[f] in moves + else Counter() + ) + for found in findings: + ln, kind, msg = found + if allowed is not None and ln not in allowed: + if not added[found]: + continue + added[found] -= 1 total += 1 bykind[kind] = bykind.get(kind, 0) + 1 byfile[keys[f]] = byfile.get(keys[f], 0) + 1 if not a.summary: print(printable(f"{keys[f]}:{ln}: {kind}: {msg}")) - inscope = ( - sum( - len(f.read_bytes().splitlines()) if keys[f] in whole else len(scope[keys[f]]) - for f in files - ) - if scope is not None - else None - ) + inscope = sum(len(scope[keys[f]]) for f in files) if scope is not None else None provenance = gate_provenance(a.provenance) named = [[keys[f] for f in group] for group in (plain, undecoded)] note_line = scope_note(len(files), discovered, inscope, a.diff, provenance, *named) diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 7479f1e3f..ffe447778 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -5671,7 +5671,7 @@ def moved( excludes: tuple[str, ...] = (), keep: bool = False, paths: tuple[str, ...] | None = None, - whole: dict[str, frozenset[str]] | None = None, + moves: dict[str, str] | None = None, dest: str = "docs/ledger.md", ) -> dict[str, set[int]]: """The scope a move of a committed four-line file from `source` to `dest` gets. @@ -5697,7 +5697,7 @@ def moved( if edit: (root / dest).write_text("One.\nTwo.\nEdited.\nFour.\n", encoding="utf-8") asked = None if paths is None else [str(root / p) for p in paths] - got = prose_lint.changed_lines("HEAD", root, excludes, asked, whole) + got = prose_lint.changed_lines("HEAD", root, excludes, asked, moves) assert got is not None, "git failed, so this case proved nothing about scoping" return got @@ -5731,26 +5731,27 @@ def test_a_rename_from_outside_the_asked_paths_is_read_whole(self) -> None: def test_a_file_list_narrows_nothing(self) -> None: """A hook passes the files a commit stages, a move's destination alone, not a run's scope.""" - self.assertEqual({}, self.moved("docs/draft.md", paths=("docs/ledger.md",))) + got = self.moved("docs/draft.md", paths=("docs/ledger.md",)) + self.assertEqual({"docs/ledger.md": set()}, got) - def test_a_rename_changing_what_its_path_decides_is_read_whole_for_that_rule(self) -> None: - """A rule that read the file another way where it sat reads it in full, and no other rule. + def test_a_rename_between_read_paths_names_where_it_sat(self) -> None: + """A run reads a moved file at both paths to report what the new one adds, so needs both. - The root runbook is exempt from `home-path` and is instruction text, which only - `issue-ref` reads as prose. A move keeping both adds only what it changed. + The root runbook is exempt from `home-path` and is instruction text, which only `issue-ref` + reads as prose. A move into or out of either, or keeping both, records its source alike. """ - for source, dest, rules in ( - ("OPERATIONS.md", "docs/ledger.md", {"home-path", "issue-ref"}), - ("docs/guide.md", "docs/OPERATIONS.md", set()), - ("notes/guide.md", "AGENTS.md", {"issue-ref"}), - ("notes/draft.md", "docs/ledger.md", set()), + for source, dest in ( + ("OPERATIONS.md", "docs/ledger.md"), + ("docs/guide.md", "docs/OPERATIONS.md"), + ("notes/guide.md", "AGENTS.md"), + ("notes/draft.md", "docs/ledger.md"), ): for edit, lines in ((False, set()), (True, {3})): with self.subTest(source=source, dest=dest, edit=edit): - whole: dict[str, frozenset[str]] = {} - got = self.moved(source, edit=edit, whole=whole, dest=dest) - self.assertEqual({dest: lines} if rules or edit else {}, got) - self.assertEqual({dest: frozenset(rules)} if rules else {}, whole) + moves: dict[str, str] = {} + got = self.moved(source, edit=edit, moves=moves, dest=dest) + self.assertEqual({dest: lines}, got) + self.assertEqual({dest: source}, moves) def test_a_rename_changing_its_lexer_is_read_whole(self) -> None: """A file read as plain text where it sat had no comment or Markdown unit read at all.""" @@ -5777,6 +5778,19 @@ def test_a_moved_runbook_reports_its_home_path_and_no_older_finding(self) -> Non [ln.rsplit(":", 1)[0] for ln in out.getvalue().splitlines()], ) + def test_a_move_into_instruction_text_reports_its_issue_references(self) -> None: + """Only instruction text reads a bare reference as a finding, so a move into it adds one.""" + for source, dest, reported in ( + ("notes/guide.md", "AGENTS.md", ["AGENTS.md:1: issue-ref"]), + ("AGENTS.md", "notes/guide.md", []), + ): + with self.subTest(source=source, dest=dest): + root = self.real_repo() + self.commit(root, {source: "Fixed in #123 already.\n"}) + (root / dest).parent.mkdir(exist_ok=True) + subprocess.run(["git", "-C", str(root), "mv", source, dest], check=True) + self.assertEqual(reported, self.gate(root, "issue-ref")) + def test_a_rename_between_read_paths_adds_only_what_it_changed(self) -> None: """A run already read the file where it sat, so a move brings no line into scope unedited. @@ -5785,10 +5799,90 @@ def test_a_rename_between_read_paths_adds_only_what_it_changed(self) -> None: """ for renames in ("true", "false", "copies"): with self.subTest(renames=renames): - self.assertEqual({}, self.moved("notes/ledger.md", renames)) + self.assertEqual({"docs/ledger.md": set()}, self.moved("notes/ledger.md", renames)) got = self.moved("notes/ledger.md", renames, edit=True) self.assertEqual({"docs/ledger.md": {3}}, got) + def commit(self, root: Path, files: dict[str, str]) -> None: + """Write and commit `files`, each relative to `root`.""" + for name, text in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(text, encoding="utf-8") + subprocess.run(["git", "-C", str(root), "add", *files], check=True) + subprocess.run(["git", "-C", str(root), "commit", "--quiet", "-m", "baseline"], check=True) + + def gate(self, root: Path, *checks: str) -> list[str]: + """Each `path:line: rule` a run scoped to the diff against `HEAD` reports.""" + out = io.StringIO() + args = [arg for check in checks for arg in ("--check", check)] + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + code = prose_lint.main([*args, "--diff", "HEAD", str(root)]) + reported = [": ".join(ln.split(": ")[:2]) for ln in out.getvalue().splitlines()] + self.assertEqual(1 if reported else 0, code) + return reported + + def test_a_move_off_a_compose_name_reports_the_container_paths_it_exposes(self) -> None: + """Only a Compose file skips a volume's container side, so a move off the name adds it. + + The host side is a finding at either name, so it stays the older finding it already was. + """ + text = ( + f"services:\n app:\n volumes:\n - {NIX_HOME}/a:/data\n" + f" - cache:{NIX_HOME}/data\n" + ) + for dest, reported in ( + ("ledger.yml", ["ledger.yml:5: home-path"]), + ("app/compose.yml", []), + ): + with self.subTest(dest=dest): + root = self.real_repo() + self.commit(root, {"compose.yml": text}) + (root / dest).parent.mkdir(exist_ok=True) + subprocess.run(["git", "-C", str(root), "mv", "compose.yml", dest], check=True) + self.assertEqual(reported, self.gate(root, "home-path")) + + def test_a_move_to_another_directory_reports_the_mentions_it_turns_dead(self) -> None: + """A relative mention resolves against the file's own directory, which a move changes. + + The mention of a deleted root file is dead from either directory, so it is not reported. + """ + root = self.real_repo() + mentions = "See [b](b.md).\nSee [old](old.md).\n" + self.commit( + root, + {"notes/b.md": "B.\n", "docs/b.md": "B.\n", "old.md": "Old.\n", "notes/a.md": mentions}, + ) + subprocess.run(["git", "-C", str(root), "rm", "--quiet", "docs/b.md", "old.md"], check=True) + subprocess.run(["git", "-C", str(root), "commit", "--quiet", "-m", "delete"], check=True) + (root / "docs").mkdir() + subprocess.run(["git", "-C", str(root), "mv", "notes/a.md", "docs/a.md"], check=True) + self.assertEqual(["docs/a.md:1: dead-path"], self.gate(root, "dead-path")) + + def test_an_edited_shebang_changing_the_lexer_reads_the_script_whole(self) -> None: + """The shebang picks how every line is read, so a change to its lexer is new to every line. + + A sentence Python reads as a docstring is a shell string, read by no rule. + """ + doc = '"""' + " ".join(["word"] * 60) + '."""\n' + for before, after, scope in ( + ("#!/bin/sh\n" + doc, "#!/usr/bin/env python3\n" + doc, {1, 2}), + (doc, "#!/usr/bin/env python3\n" + doc, {1, 2}), + ("#!/usr/bin/env python3\n" + doc, doc, {1}), + ("#!/bin/sh\n" + doc, "#!/bin/bash\n" + doc, {1}), + ("#!/bin/sh\n" + doc, "#!/bin/sh\n" + doc + "echo\n", {3}), + ): + with self.subTest(before=before[:12], after=after[:12]): + root = self.real_repo() + self.commit(root, {"tools/run": before}) + (root / "tools" / "run").write_text(after, encoding="utf-8") + self.assertEqual({"tools/run": scope}, prose_lint.changed_lines("HEAD", root)) + root = self.real_repo() + self.commit(root, {"tools/run": "#!/bin/sh\n" + doc}) + (root / "bin").mkdir() + subprocess.run(["git", "-C", str(root), "mv", "tools/run", "bin/run"], check=True) + (root / "bin" / "run").write_text("#!/usr/bin/env python3\n" + doc, encoding="utf-8") + self.assertEqual(["bin/run:2: sentence-length"], self.gate(root, "sentence-length")) + def test_a_binary_change_contributes_no_scope_entry(self) -> None: """A genuinely binary path stays out of the map entirely, gaining no entry at all. From d88320cfa45b6bae4342095c1d7a79108d105238 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 1 Nov 2026 11:03:34 -0800 Subject: [PATCH 2/2] Judge a Moved File by the First Line It Had Where It Sat The run at the old path read the new first line, so a move onto a suffix that keeps the lexer, together with a shebang edit, judged the old path through the wrong lexer and could resurface an older finding. The first line the diff recorded is now passed along with the source. A byte order mark opening the first line is also dropped before the lexer comparison, as check_file already drops it. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose_lint.py | 44 ++++++++++++++---------- tests/test_prose_lint.py | 24 +++++++++++-- 2 files changed, 47 insertions(+), 21 deletions(-) diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index 6b296aa9c..657fb5bb6 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -84,6 +84,7 @@ TIER3 = frozenset(chr(int(k.removeprefix("U+"), 16)) for k in BASE["charset"]["tier3"]) TIER4 = frozenset(chr(int(k.removeprefix("U+"), 16)) for k in BASE["charset"]["tier4"]) VARIATION_SELECTOR_16 = chr(0xFE0F) +BOM = chr(0xFEFF) GENERATED_ROOTS = frozenset(BASE["generated_roots"]) INSTRUCTION_DOCS = frozenset(BASE["instruction_docs"]) DUP_ALLOW = frozenset(BASE["exemptions"]["dupword_allow"]) @@ -283,7 +284,7 @@ def changed_lines( root: Path, excludes: tuple[str, ...] = (), paths: list[str] | None = None, - moves: dict[str, str] | None = None, + moves: dict[str, tuple[str, str]] | None = None, ) -> dict[str, set[int]] | None: """Map path -> lines this tree adds vs `base`, an untracked or undiffable text file in full. @@ -291,7 +292,8 @@ def changed_lines( moved out of one is read in full too. So is one whose lexer the change alters, by its path or its first line. Only directories narrow. A list naming a file is what a hook passes from a commit, which says what this run reads rather than what every run does. Any other move adds - what it changed, and `moves` records its source so a run reports what the new path adds. + what it changed. `moves` records its source and first line, so a run reports what the new + path adds. """ raw = git_bytes(root, DIFF_ARGS, base) undiffable = undiffable_paths(base, root) if raw is not None else None @@ -343,7 +345,7 @@ def changed_lines( elif m.group(1) == "1" and m.group(2) != "0": firsts[cur] = None elif line.startswith("-") and cur and cur in firsts and firsts[cur] is None: - firsts[cur] = line[1:].rstrip("\r") + firsts[cur] = line[1:].rstrip("\r").removeprefix(BOM) for name in sorted(out.keys() | moved.keys()): if name not in firsts and name not in moved: continue @@ -359,7 +361,7 @@ def changed_lines( elif name in moved: out.setdefault(name, set()) if moves is not None: - moves[name] = moved[name] + moves[name] = (moved[name], was) for name in [*undiffable, *untracked_paths(root), *unread]: if is_text(root / name): out[name] = set(range(1, len((root / name).read_bytes().splitlines()) + 1)) @@ -367,12 +369,17 @@ def changed_lines( def nth_line(path: Path, n: int) -> str: - """Line `n` of `path`, counted from 1, or empty where the file holds fewer lines or none.""" + """Line `n` of `path` as a lexer reads a first line, or empty where the file holds fewer lines. + + Line `n` is counted from 1, and a byte order mark opening it is dropped as `check_file` drops it. + """ try: lines = path.read_bytes().split(b"\n", n) except OSError: return "" - return lines[n - 1].decode("utf-8", "replace").rstrip("\r") if len(lines) >= n else "" + if len(lines) < n: + return "" + return lines[n - 1].decode("utf-8", "replace").rstrip("\r").removeprefix(BOM) def exempt_rules(path: Path, root: Path, config: Config) -> frozenset[str]: @@ -1032,13 +1039,14 @@ def inline_comments(tok: Token, lines: list[str]) -> list[Line]: return out -def extract(path: Path, text: str, lex: bool = True) -> Extracted: +def extract(path: Path, text: str, lex: bool = True, first: str | None = None) -> Extracted: """The units the rules read in this file, and whether it was read as plain text. Without `lex`, a code file's comments and docstrings are left unread, no rule asking for them. + The lexer is chosen from `first` in place of the text's own first line where it is given. """ lines = [line.rstrip("\r") for line in text.split("\n")] - lexer = lexer_name(path, lines[0]) + lexer = lexer_name(path, lines[0] if first is None else first) if lexer == "markdown": return extract_markdown(lines) fenced = fenced_lines(lines) @@ -1936,9 +1944,9 @@ def check_file( allowed: set[int] | None = None, plain: list[Path] | None = None, undecoded: list[Path] | None = None, - at: Path | None = None, + at: tuple[Path, str] | None = None, ) -> list[Finding]: - """Every finding the rules in `rules` make on `path`, judged as sitting at `at` where given. + """Every finding the rules in `rules` make on `path`, or judged at `at`, a path and a first line. `plain` collects a file with no lexer and `undecoded` one that is not UTF-8, since each is otherwise counted as read with nothing found. A byte order mark is judged on its own. @@ -1949,15 +1957,14 @@ def check_file( if undecoded is not None: undecoded.append(path) return [] - bom = chr(0xFEFF) - text = decoded.removeprefix(bom) - out = [f for f in charset_findings(1, bom) if f[1] in rules] if text != decoded else [] + text = decoded.removeprefix(BOM) + out = [f for f in charset_findings(1, BOM) if f[1] in rules] if text != decoded else [] lex = any(RULE_TABLE[r][1] - {"source", "prose", "code"} for r in rules) - judged = at or path - units, fenced, read_plain = extract(judged, text, lex) + judged, first = at or (path, text.split("\n", 1)[0].rstrip("\r")) + units, fenced, read_plain = extract(judged, text, lex, first) if read_plain and plain is not None: plain.append(path) - lexer = lexer_name(judged, text.split("\n", 1)[0].rstrip("\r")) + lexer = lexer_name(judged, first) config = config_for(str(root) if root else None) ctx = Context(judged, root, fenced, language_of(lexer) or {}, config, allowed) units = [without_metadata_blocks(unit, ctx) for unit in units] @@ -2044,7 +2051,7 @@ def main(argv: list[str] | None = None) -> int: return 0 discovered = len(files) # Presence rather than truthiness, since an empty value is a base that failed to compute. - moves: dict[str, str] = {} + moves: dict[str, tuple[str, str]] = {} scope = ( changed_lines(a.diff, scan_root, tuple(a.exclude), scan_paths, moves) if a.diff is not None @@ -2072,9 +2079,10 @@ def main(argv: list[str] | None = None) -> int: allowed = scope.get(keys[f]) if scope is not None else None findings = check_file(f, rules, scan_root, allowed, plain, undecoded) # A moved file reports what its new path finds beyond what the old one did, not the backlog. + source, opener = moves.get(keys[f], ("", "")) added = ( Counter(findings) - - Counter(check_file(f, rules, scan_root, allowed, at=scan_root / moves[keys[f]])) + - Counter(check_file(f, rules, scan_root, allowed, at=(scan_root / source, opener))) if keys[f] in moves else Counter() ) diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index ffe447778..118fb4849 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -5671,7 +5671,7 @@ def moved( excludes: tuple[str, ...] = (), keep: bool = False, paths: tuple[str, ...] | None = None, - moves: dict[str, str] | None = None, + moves: dict[str, tuple[str, str]] | None = None, dest: str = "docs/ledger.md", ) -> dict[str, set[int]]: """The scope a move of a committed four-line file from `source` to `dest` gets. @@ -5748,10 +5748,10 @@ def test_a_rename_between_read_paths_names_where_it_sat(self) -> None: ): for edit, lines in ((False, set()), (True, {3})): with self.subTest(source=source, dest=dest, edit=edit): - moves: dict[str, str] = {} + moves: dict[str, tuple[str, str]] = {} got = self.moved(source, edit=edit, moves=moves, dest=dest) self.assertEqual({dest: lines}, got) - self.assertEqual({dest: source}, moves) + self.assertEqual({dest: (source, "One.")}, moves) def test_a_rename_changing_its_lexer_is_read_whole(self) -> None: """A file read as plain text where it sat had no comment or Markdown unit read at all.""" @@ -5870,6 +5870,7 @@ def test_an_edited_shebang_changing_the_lexer_reads_the_script_whole(self) -> No ("#!/usr/bin/env python3\n" + doc, doc, {1}), ("#!/bin/sh\n" + doc, "#!/bin/bash\n" + doc, {1}), ("#!/bin/sh\n" + doc, "#!/bin/sh\n" + doc + "echo\n", {3}), + ("\ufeff#!/bin/sh\n" + doc, "\ufeff#!/usr/bin/env python3\n" + doc, {1, 2}), ): with self.subTest(before=before[:12], after=after[:12]): root = self.real_repo() @@ -5883,6 +5884,23 @@ def test_an_edited_shebang_changing_the_lexer_reads_the_script_whole(self) -> No (root / "bin" / "run").write_text("#!/usr/bin/env python3\n" + doc, encoding="utf-8") self.assertEqual(["bin/run:2: sentence-length"], self.gate(root, "sentence-length")) + def test_a_moved_file_is_judged_where_it_sat_by_the_first_line_it_had_there(self) -> None: + """Read through its new shebang at its old path, the comment bash read there would report. + + The suffix the move adds keeps the lexer bash, so the file is not read whole. Python skips + an inline script metadata block, and bash reads it as comments. + """ + body = "# /// script\n# Read the the ledger.\n# ///\necho\n" + root = self.real_repo() + self.commit(root, {"tools/run": "#!/bin/sh\n" + body}) + subprocess.run(["git", "-C", str(root), "mv", "tools/run", "tools/run.sh"], check=True) + (root / "tools" / "run.sh").write_text("#!/usr/bin/env python3\n" + body, encoding="utf-8") + moves: dict[str, tuple[str, str]] = {} + got = prose_lint.changed_lines("HEAD", root, moves=moves) + self.assertEqual({"tools/run.sh": {1}}, got) + self.assertEqual({"tools/run.sh": ("tools/run", "#!/bin/sh")}, moves) + self.assertEqual([], self.gate(root, "dupword")) + def test_a_binary_change_contributes_no_scope_entry(self) -> None: """A genuinely binary path stays out of the map entirely, gaining no entry at all.