Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/prose-gate/prose-gate.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"sentence-split": { "default": false, "summary": "a sentence wrapping across lines" },
"sentence-length": { "default": true, "summary": "a sentence over the word cap" },
"spelling": { "default": true, "summary": "a British spelling where the repo convention is US English" },
"home-path": { "default": true, "summary": "an absolute home path naming a real account" },
"home-path": { "default": true, "summary": "an absolute home path naming a real account", "file_exemption": "home_path_exempt" },
"dead-path": { "default": true, "summary": "a mention of a path git once tracked and the tree no longer holds" },
"issue-ref": { "default": true, "summary": "an issue or pull request reference in a leading comment, a Python docstring, or instruction text" }
},
Expand Down
103 changes: 90 additions & 13 deletions .github/actions/prose-gate/prose_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@
OVERRIDE_NAME = ".prose-gate.json"
RULES: dict[str, str] = {name: rule["summary"] for name, rule in BASE["rules"].items()}
DEFAULT_RULES = frozenset(name for name, rule in BASE["rules"].items() if rule["default"])
FILE_EXEMPTION: dict[str, str] = {
name: rule["file_exemption"] for name, rule in BASE["rules"].items() if "file_exemption" in rule
}
MESSAGES: dict[str, str] = BASE["messages"]
SENTENCE_WORD_CAP: int = BASE["sentence_word_cap"]
# The data file names each character as `U+XXXX`, which keeps the file itself ASCII.
Expand Down Expand Up @@ -275,20 +278,32 @@ def undiffable_paths(base: str, root: Path) -> set[str] | None:


def changed_lines(
base: str, root: Path, excludes: tuple[str, ...] = ()
base: str,
root: Path,
excludes: tuple[str, ...] = (),
paths: list[str] | None = None,
whole: dict[str, frozenset[str]] | None = None,
) -> dict[str, set[int]] | None:
"""Map path -> lines this tree adds vs `base`, an untracked or undiffable text file in full.

A file moved out of a generated tree or an excluded path is read in full too, since no run read
it there. A move between read paths adds only what it changed.
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.
"""
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
trees = config_for(str(root)).exempt["generated_trees"]
config = config_for(str(root))
trees = config.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] = {}
cur = None
source = ""
# A header is honored only in the block a `diff --git` line opens, which content cannot forge.
Expand All @@ -299,8 +314,15 @@ def changed_lines(
elif in_header and line.startswith("rename from "):
source = unquoted(line.removeprefix("rename from "))
elif in_header and line.startswith("rename to "):
if not trees.isdisjoint(Path(source).parts) or any(x in source for x in excludes):
unread.append(unquoted(line.removeprefix("rename to ")))
dest = unquoted(line.removeprefix("rename to "))
if (
not trees.isdisjoint(Path(source).parts)
or any(x in source for x in excludes)
or (asked is not None and not asked_about(source, asked))
):
unread.append(dest)
else:
moved[dest] = source
elif in_header and line.startswith("+++ "):
in_header = False
cur = diff_header_path(line[4:])
Expand All @@ -314,12 +336,46 @@ def changed_lines(
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):
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
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 exempt_rules(path: Path, root: Path, config: Config) -> frozenset[str]:
"""The rules that never read `path`, each because the list its `file_exemption` names holds it."""
return frozenset(
rule
for rule, key in FILE_EXEMPTION.items()
if path.resolve() in {(root / p).resolve() for p in config.exempt[key]}
)


def asked_about(key: str, paths: list[str]) -> bool:
"""Whether a repository-relative diff key falls under one of the requested paths."""
for raw in paths:
Expand Down Expand Up @@ -1252,21 +1308,32 @@ def rule_sentence_split(unit: Unit, ctx: Context) -> list[Finding]:
r"""^\s*-\s+["']?(?:[A-Za-z]:(?=[\\/]))?(?:\$\{[^}]*\}|[^:\s"'{}])+:(?P<target>/[^:\s"']*)"""
)
LONG_MOUNT = re.compile(r"""^\s*(?:-\s+)?target:\s+["']?(?P<target>/[^\s"']*)""")
BLOCK_SCALAR = re.compile(
r"^(?P<lead>\s*(?:-\s+)*)(?P<key>[^\s#][^#]*?:\s+)?(?:[!&]\S*\s+)*[|>]"
r"(?:[-+][1-9]?|[1-9][-+]?)?\s*(?:#.*)?$"
)


def container_paths(lines: tuple[Line, ...]) -> dict[int, range]:
"""Where a Compose volume entry names its container path, a path an image ships, not a host.

The host side keeps a `${...}` expansion and a drive letter whole, so neither colon splits it.
A sequence may sit at its key's own indent, so only a sibling key closes the block.
A sequence may sit at its key's own indent, so only a sibling key closes the block. A `|` or
`>` block scalar is text, so every line deeper than the node that opens one is skipped.
"""
out: dict[int, range] = {}
block: int | None = None
opaque: int | None = None
for line in lines:
body = line.text.lstrip()
if not body or body.startswith("#"):
continue
indent = len(line.text) - len(body)
if opaque is not None and indent > opaque:
continue
opaque = None
if scalar := BLOCK_SCALAR.match(line.text):
opaque = len(scalar["lead"]) if scalar["key"] else indent
if block is not None and (indent < block or (indent == block and body[0] != "-")):
block = None
if VOLUMES_KEY.match(line.text):
Expand All @@ -1281,9 +1348,7 @@ def container_paths(lines: tuple[Line, ...]) -> dict[int, range]:
def rule_home_path(unit: Unit, ctx: Context) -> list[Finding]:
"""An absolute home path naming a real account, on any line, a fenced transcript included."""
exempt = ctx.config.exempt
if ctx.root is not None and ctx.path.resolve() in {
(ctx.root / p).resolve() for p in exempt["home_path_exempt"]
}:
if ctx.root is not None and "home-path" in exempt_rules(ctx.path, ctx.root, ctx.config):
return []
inside = container_paths(unit.lines) if COMPOSE_FILE.fullmatch(ctx.path.name) else {}
return [
Expand Down Expand Up @@ -1955,7 +2020,12 @@ 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.
scope = changed_lines(a.diff, scan_root, tuple(a.exclude)) if a.diff is not None else None
whole: dict[str, frozenset[str]] = {}
scope = (
changed_lines(a.diff, scan_root, tuple(a.exclude), scan_paths, whole)
if a.diff is not None
else None
)
if a.diff is not None and scope is None:
return refuse("error-no-diff", base=a.diff)
if scope is not None:
Expand All @@ -1977,14 +2047,21 @@ def main(argv: list[str] | None = None) -> int:
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:
if allowed is not None and ln not in allowed and kind not in whole.get(keys[f], ()):
continue
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(scope[keys[f]]) for f in files) if scope is not None else None
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
)
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)
Expand Down
101 changes: 92 additions & 9 deletions tests/test_prose_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3612,6 +3612,31 @@ def test_a_compose_host_path_is_still_a_home(self) -> None:
["home-path"], self.kinds(self.compose(entry), {"home-path"}, name)
)

def test_a_compose_block_scalar_is_text_rather_than_a_volume(self) -> None:
"""A `volumes:` key or a mount inside a `|` or `>` scalar is text, so the rule reads it.

The real volume entry after each scalar still names a container path, so exactly one
finding means the scalar ended where its indentation returned.
"""
real = f" volumes:\n - ledger-cache:{NIX_HOME}/data\n"
for indicator in ("|", ">", "|-", ">+", "|2", "|-2", "&note |", "!!str >", "| # note"):
text = (
f"services:\n ledger:\n x-readme: {indicator}\n volumes:\n"
f" - ledger-cache:{NIX_HOME}/data\n{real}"
)
with self.subTest(indicator=indicator):
self.assertEqual(["home-path"], self.kinds(text, {"home-path"}, "compose.yml"))
target = f" target: {NIX_HOME}/media"
for entry in (
f" - type: bind\n x-note: |\n - ./old:{NIX_HOME}/media\n{target}",
f" - x-note: >-\n - ./old:{NIX_HOME}/media\n{target}",
f" - |\n - ./old:{NIX_HOME}/media\n - ./config:{NIX_HOME}/media",
):
with self.subTest(entry=entry):
self.assertEqual(
["home-path"], self.kinds(self.compose(entry), {"home-path"}, "compose.yml")
)


class TestDeadPathRule(unittest.TestCase):
"""The `dead-path` rule on Markdown prose units."""
Expand Down Expand Up @@ -5629,11 +5654,15 @@ def moved(
edit: bool = False,
excludes: tuple[str, ...] = (),
keep: bool = False,
paths: tuple[str, ...] | None = None,
whole: dict[str, frozenset[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 `docs/ledger.md` gets.
"""The scope a move of a committed four-line file from `source` to `dest` gets.

With `keep`, the file is copied rather than moved, and the source gains a fifth line.
Copy detection looks for a source only among the files a change modifies.
Copy detection looks for a source only among the files a change modifies. Each of `paths`
is relative to the repository, as a run narrowed to it would ask.
"""
root = self.real_repo()
subprocess.run(["git", "-C", str(root), "config", "diff.renames", renames], check=True)
Expand All @@ -5643,17 +5672,16 @@ def moved(
subprocess.run(["git", "-C", str(root), "commit", "--quiet", "-m", "baseline"], check=True)
(root / "docs").mkdir(exist_ok=True)
if keep:
shutil.copyfile(root / source, root / "docs" / "ledger.md")
shutil.copyfile(root / source, root / dest)
with (root / source).open("a", encoding="utf-8") as fh:
fh.write("Five.\n")
subprocess.run(["git", "-C", str(root), "add", "docs/ledger.md", source], check=True)
subprocess.run(["git", "-C", str(root), "add", dest, source], check=True)
else:
subprocess.run(["git", "-C", str(root), "mv", source, "docs/ledger.md"], check=True)
subprocess.run(["git", "-C", str(root), "mv", source, dest], check=True)
if edit:
(root / "docs" / "ledger.md").write_text(
"One.\nTwo.\nEdited.\nFour.\n", encoding="utf-8"
)
got = prose_lint.changed_lines("HEAD", root, excludes)
(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)
assert got is not None, "git failed, so this case proved nothing about scoping"
return got

Expand All @@ -5678,6 +5706,61 @@ def test_a_rename_out_of_an_excluded_path_is_read_whole(self) -> None:
got = self.moved("drafts/ledger.md", excludes=("drafts/",))
self.assertEqual({"docs/ledger.md": {1, 2, 3, 4}}, got)

def test_a_rename_from_outside_the_asked_paths_is_read_whole(self) -> None:
"""A run narrowed to some paths never read a file outside them, so a move in is all new."""
got = self.moved("drafts/ledger.md", paths=("docs",))
self.assertEqual({"docs/ledger.md": {1, 2, 3, 4}}, got)
got = self.moved("docs/draft.md", paths=("docs",), edit=True)
self.assertEqual({"docs/ledger.md": {3}}, got)

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",)))

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.

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.
"""
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 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)

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."""
got = self.moved("docs/notes.txt")
self.assertEqual({"docs/ledger.md": {1, 2, 3, 4}}, got)

def test_a_moved_runbook_reports_its_home_path_and_no_older_finding(self) -> None:
"""The run end to end: the moved line reports for `home-path` and for no other rule."""
root = self.real_repo()
text = f"Deploy into {NIX_HOME}/stack here.\nOne; two.\n"
(root / "OPERATIONS.md").write_text(text, encoding="utf-8")
subprocess.run(["git", "-C", str(root), "add", "OPERATIONS.md"], check=True)
subprocess.run(["git", "-C", str(root), "commit", "--quiet", "-m", "baseline"], check=True)
(root / "docs").mkdir()
subprocess.run(["git", "-C", str(root), "mv", "OPERATIONS.md", "docs/ops.md"], check=True)
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = prose_lint.main(
["--check", "home-path", "--check", "semicolon", "--diff", "HEAD", str(root)]
)
self.assertEqual(1, code)
self.assertEqual(
["docs/ops.md:1: home-path"],
[ln.rsplit(":", 1)[0] for ln in out.getvalue().splitlines()],
)

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.

Expand Down
Loading