Files
claude-config/bin/touch_predictions/prediction.py
T

102 lines
4.2 KiB
Python

"""An item's prediction of the files and parts it will touch, as its detail spells it, and where two predictions overlap.
The spelling, which three readers seated as the project's audience picked from four candidates:
Touches:
- `bin/a.py`: `main`, `Plan.branch` (small)
- `bin/run.sh`: lines 10-20
- `docs/new.md`
A path alone is the whole file, and (small) marks a part the item changes only a little. file_parts says how a part is named."""
import dataclasses
import re
from failure import Failure
LABEL = "Touches:"
RANGE = re.compile(r"lines (\d+)-(\d+)")
PART = re.compile(r"(`[^`]+`|lines \d+-\d+)( \(small\))?")
BULLET = re.compile(rf"- `([^`\s]+)`(?:: ({PART.pattern}(?:, {PART.pattern})*))?")
@dataclasses.dataclass(frozen=True)
class Part:
"""A part of a file, by the name file_parts gives it or as `lines <first>-<last>`; small where the item changes it only a little."""
name: str
small: bool = False
# Each file's parts by its path; no parts where the whole file is touched.
Touches = dict[str, tuple[Part, ...]]
def predicted(detail: str) -> Touches | None | Failure:
"""The prediction in an item's detail: the bullets under its `Touches:` line, up to the first other text. None where the detail has no such line."""
lines = detail.splitlines()
if LABEL not in lines:
return None
touches: Touches = {}
for line in lines[lines.index(LABEL) + 1:]:
if not line.strip():
continue
if not line.startswith("- "):
break
bullet = BULLET.fullmatch(line)
parts = tuple(Part(name.strip("`"), bool(small)) for name, small in PART.findall(bullet.group(2) or "")) if bullet else ()
if bullet is None or any(span and span[0] > span[1] for span in map(line_range, parts)):
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>`, and optionally ` (small)`")
touches = together([touches, {bullet.group(1): parts}])
return touches or Failure(f"no bullet follows `{LABEL}`")
def rendered(touches: Touches) -> str:
"""touches as the bullets predicted reads."""
return "\n".join(f"- `{path}`" + (": " + ", ".join(shown(part) + " (small)" * part.small for part in parts) if parts else "") for path, parts in touches.items())
def shown(part: Part) -> str:
return part.name if line_range(part) else f"`{part.name}`"
def line_range(part: Part) -> tuple[int, int] | None:
found = RANGE.fullmatch(part.name)
return (int(found.group(1)), int(found.group(2))) if found else None
def together(several: list[Touches]) -> Touches:
"""What several predictions touch between them. A file one of them touches whole is touched whole, and a part is small only where each that names it says so."""
joined: dict[str, dict[str, bool] | None] = {}
for touches in several:
for path, parts in touches.items():
held = joined.setdefault(path, {})
if held is None or not parts:
joined[path] = None
continue
for part in parts:
held[part.name] = held.get(part.name, True) and part.small
return {path: tuple(Part(name, small) for name, small in held.items()) if held else () for path, held in joined.items()}
def overlaps(ours: Touches, theirs: Touches) -> list[str]:
"""Each place both touch: a file either touches whole, by its path alone, and else each part as ours names it. A part either side marks small is left out: a conflict there is cheap to settle, and a chunk that waits costs hours."""
found = []
for path, parts in ours.items():
if path not in theirs:
continue
if not parts or not theirs[path]:
found.append(f"`{path}`")
continue
found.extend(f"`{path}` {shown(part)}" for part in parts if any(same_part(part, other) and not (part.small or other.small) for other in theirs[path]))
return found
def same_part(one: Part, other: Part) -> bool:
"""Whether two parts of one file share lines, as far as their names tell: line ranges that share a line, a line range beside a name, equal names, or a class and what it holds."""
spans = line_range(one), line_range(other)
if spans[0] and spans[1]:
return spans[0][0] <= spans[1][1] and spans[1][0] <= spans[0][1]
if spans[0] or spans[1]:
return True
return one.name == other.name or one.name.startswith(f"{other.name}.") or other.name.startswith(f"{one.name}.")