Parse each comprehension history entry once into votes, scores and listings
This commit is contained in:
@@ -21,8 +21,8 @@ MID = "Mid A"
|
||||
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
|
||||
RESTRUCTURE_FIRST = "would restructure first"
|
||||
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
|
||||
RULED_PLACES = re.compile(rf"^.+, {DECIDED_BY}:$")
|
||||
SCORED_PLACES = re.compile(rf"^.+, ({HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
||||
# A seat's label over its bullets: its name, then what the bullets are.
|
||||
LABEL = re.compile(rf"^(.+), ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
||||
SENIOR = "Maintainability senior"
|
||||
TITLE = "# Comprehension history\n"
|
||||
|
||||
@@ -40,22 +40,52 @@ class Place:
|
||||
name: str | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The bullets a seat lists under one label of an entry, each with its indented continuation lines. `kind` is what the label ends in: DECIDED_BY, HARDEST_FIRST or RESTRUCTURE_FIRST."""
|
||||
label: str
|
||||
seat: str
|
||||
kind: str
|
||||
bullets: list[str]
|
||||
|
||||
@property
|
||||
def places(self) -> list[Place]:
|
||||
"""The places on the first line of each bullet."""
|
||||
return [place for bullet in self.bullets for place in bullet_places(bullet.splitlines()[0])]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Entry:
|
||||
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither. The places under a scoring seat's label are scored_places; a ruling recorded before PR #255 may hold them too."""
|
||||
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither.
|
||||
|
||||
`votes` and `scores` hold table rows, each the cells after the first, by the first, with the header left out. `scores` is the table with a Mean row, `votes` any other: a ruling's votes, whose one cell in a ruling before PR #232 is the overall vote. A ruling before PR #255 holds both tables, and scoring seats' listings too."""
|
||||
heading: str
|
||||
time: str
|
||||
commit: str
|
||||
against: str | None
|
||||
ruling: str | None
|
||||
ruled_places: list[Place]
|
||||
scored_places: list[Place]
|
||||
body: str
|
||||
votes: dict[str, list[str]]
|
||||
scores: dict[str, list[str]]
|
||||
decided: list[Listing]
|
||||
hardest: list[Listing]
|
||||
|
||||
@property
|
||||
def paired(self) -> bool:
|
||||
return self.against is not None
|
||||
|
||||
@property
|
||||
def scored(self) -> bool:
|
||||
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return not self.paired or bool(self.scored_places)
|
||||
|
||||
@property
|
||||
def ruled_places(self) -> list[Place]:
|
||||
return [place for listing in self.decided for place in listing.places]
|
||||
|
||||
@property
|
||||
def scored_places(self) -> list[Place]:
|
||||
return [place for listing in self.hardest for place in listing.places]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HistoryChange:
|
||||
@@ -101,7 +131,15 @@ def entries(history: str) -> list[Entry]:
|
||||
if named := HEADING.match(heading):
|
||||
body = "\n".join(bodies)
|
||||
ruling = RULING.search(body)
|
||||
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body, RULED_PLACES), seat_places(body, SCORED_PLACES), body))
|
||||
tables = table_rows(body)
|
||||
listed = listings(body)
|
||||
found.append(Entry(
|
||||
heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None,
|
||||
votes={name: cells for table in tables if MEAN not in table for name, cells in table.items()},
|
||||
scores={name: cells for table in tables if MEAN in table for name, cells in table.items()},
|
||||
decided=[listing for listing in listed if listing.kind == DECIDED_BY],
|
||||
hardest=[listing for listing in listed if listing.kind != DECIDED_BY],
|
||||
))
|
||||
return found
|
||||
|
||||
|
||||
@@ -112,7 +150,7 @@ def latest_places(history: str) -> str | None:
|
||||
found = by_time(entries(history))
|
||||
newest = newest_scored(found)
|
||||
start = found.index(newest[0]) if newest else 0
|
||||
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]]
|
||||
parts = [placed(entry, worse_places(entry) + entry.hardest) for entry in found[start:]]
|
||||
return "\n".join(part for part in parts if part) or None
|
||||
|
||||
|
||||
@@ -129,26 +167,26 @@ def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
||||
|
||||
def newest_scored(found: list[Entry]) -> list[Entry]:
|
||||
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
|
||||
scoring = [entry for entry in found if scored(entry)]
|
||||
scoring = [entry for entry in found if entry.scored]
|
||||
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
|
||||
|
||||
|
||||
def run_overall(run: Entry) -> decimal.Decimal | Failure:
|
||||
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
|
||||
try:
|
||||
overall = decimal.Decimal(overall_cells(run).get(MEAN, ""))
|
||||
overall = decimal.Decimal(last_cells(run.scores).get(MEAN, ""))
|
||||
except decimal.InvalidOperation:
|
||||
overall = None
|
||||
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
|
||||
|
||||
|
||||
def overall_cells(entry: Entry) -> dict[str, str]:
|
||||
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score, or the Mean row's, in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
def last_cells(rows: dict[str, list[str]]) -> dict[str, str]:
|
||||
"""Each row's last non-empty cell, by its first cell: a seat's overall vote in an entry's `votes`, or its overall score, or the Mean row's, in its `scores`."""
|
||||
return {name: cells[-1] for name, cells in rows.items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def scoring_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""The scoring runs among the entries, oldest first. Unlike scored, it leaves out a ruling from before PR #255 that holds scoring seats' places: there overall_cells reads each voting seat's vote, not its score."""
|
||||
"""The scoring runs among the entries, oldest first. Unlike Entry.scored, it leaves out a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return [entry for entry in by_time(found) if not entry.paired]
|
||||
|
||||
|
||||
@@ -156,36 +194,38 @@ def by_time(found: list[Entry]) -> list[Entry]:
|
||||
return sorted(found, key=lambda entry: entry.time)
|
||||
|
||||
|
||||
def scored(entry: Entry) -> bool:
|
||||
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return not entry.paired or bool(entry.scored_places)
|
||||
def worse_places(entry: Entry) -> list[Listing]:
|
||||
"""Each of a ruling's decided-by listings, cut to the bullets that open with a dimension its seat's vote counted as worse; Overall counts as one."""
|
||||
cut = []
|
||||
for listing in entry.decided:
|
||||
worse = worse_dimensions(entry.votes.get(listing.seat, []))
|
||||
cut.append(dataclasses.replace(listing, bullets=[bullet for bullet in listing.bullets if worse.intersection(place_dimensions(bullet.removeprefix("- ")))]))
|
||||
return cut
|
||||
|
||||
|
||||
def worse_places(entry: Entry) -> list[tuple[str, list[str]]]:
|
||||
"""Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one."""
|
||||
worse = worse_votes(entry.body)
|
||||
return [(label, [bullet for bullet in bullets if worse.get(label.split(",")[0], set()) & set(place_dimensions(bullet.removeprefix("- ")))]) for label, bullets in labelled_bullets(entry.body, RULED_PLACES)]
|
||||
|
||||
|
||||
def placed(entry: Entry, labelled: list[tuple[str, list[str]]]) -> str:
|
||||
"""The entry's heading, then each label with bullets and its bullets; empty when no label has any."""
|
||||
text = "".join(f"\n{label}\n\n" + "".join(f"{bullet}\n" for bullet in bullets) for label, bullets in labelled if bullets)
|
||||
def placed(entry: Entry, listed: list[Listing]) -> str:
|
||||
"""The entry's heading, then each listing with bullets, its label and its bullets; empty when no listing has any."""
|
||||
text = "".join(f"\n{listing.label}\n\n" + "".join(f"{bullet}\n" for bullet in listing.bullets) for listing in listed if listing.bullets)
|
||||
return f"## {entry.heading}\n{text}" if text else ""
|
||||
|
||||
|
||||
def worse_votes(body: str) -> dict[str, set[str]]:
|
||||
"""Each seat's dimensions, Overall included, whose vote in the ruling's table counted as worse; `same (voted worse, …)` counted as same. The votes table comes first, so a seat's row in a later scores table is not its vote."""
|
||||
return {name: {dimension for dimension, vote in zip(DIMENSIONS, cells) if vote == "worse"} for name, cells in table_rows(body).items() if len(cells) == len(DIMENSIONS)}
|
||||
def worse_dimensions(votes: list[str]) -> set[str]:
|
||||
"""The dimensions, Overall included, whose vote in a seat's row of the ruling's votes counted as worse; `same (voted worse, …)` counted as same. A row without one vote per dimension, as in the older table with a single `Vote`, has none."""
|
||||
return {dimension for dimension, vote in zip(DIMENSIONS, votes) if vote == "worse"} if len(votes) == len(DIMENSIONS) else set()
|
||||
|
||||
|
||||
def table_rows(body: str) -> dict[str, list[str]]:
|
||||
"""Each table row's cells after its first, keyed by that first cell; where rows share a first cell, the first row wins. Header and Mean rows are included."""
|
||||
found: dict[str, list[str]] = {}
|
||||
for line in body.splitlines():
|
||||
if line.startswith("| "):
|
||||
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
found.setdefault(name, cells)
|
||||
return found
|
||||
def table_rows(body: str) -> list[dict[str, list[str]]]:
|
||||
"""Each table's rows after its header and separator, the cells after the first keyed by the first cell. A table starts at the row above a separator; `sections` has dropped the blank lines between tables."""
|
||||
lines = [line for line in body.splitlines() if line.startswith("|")]
|
||||
separators = [index for index, line in enumerate(lines) if line.startswith("|-")]
|
||||
ends = [*(index - 1 for index in separators[1:]), len(lines)]
|
||||
return [dict(row_cells(line) for line in lines[separator + 1:end]) for separator, end in zip(separators, ends)]
|
||||
|
||||
|
||||
def row_cells(line: str) -> tuple[str, list[str]]:
|
||||
"""A table row's first cell, then the cells after it."""
|
||||
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
return name, cells
|
||||
|
||||
|
||||
def place_dimensions(place: str) -> list[str]:
|
||||
@@ -199,25 +239,20 @@ def recorded(history: str, read: str) -> bool:
|
||||
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
|
||||
|
||||
|
||||
def seat_places(body: str, labels: re.Pattern[str]) -> list[Place]:
|
||||
"""The places on the first line of each bullet under a seat label the pattern `labels` matches."""
|
||||
return [place for _, bullets in labelled_bullets(body, labels) for bullet in bullets for place in bullet_places(bullet.splitlines()[0])]
|
||||
|
||||
|
||||
def labelled_bullets(body: str, labels: re.Pattern[str]) -> list[tuple[str, list[str]]]:
|
||||
"""Each seat label the pattern `labels` matches, with its bullets, each with its indented continuation lines."""
|
||||
found: list[tuple[str, list[str]]] = []
|
||||
listing = False
|
||||
def listings(body: str) -> list[Listing]:
|
||||
"""Each seat label in the body, with its bullets, each with its indented continuation lines."""
|
||||
found: list[Listing] = []
|
||||
under_label = False
|
||||
for line in body.splitlines():
|
||||
if labels.match(line):
|
||||
found.append((line, []))
|
||||
listing = True
|
||||
elif listing and line.startswith("- "):
|
||||
found[-1][1].append(line)
|
||||
elif listing and line.startswith(" ") and found[-1][1]:
|
||||
found[-1][1][-1] += f"\n{line}"
|
||||
if label := LABEL.match(line):
|
||||
found.append(Listing(line, label.group(1), label.group(2), []))
|
||||
under_label = True
|
||||
elif under_label and line.startswith("- "):
|
||||
found[-1].bullets.append(line)
|
||||
elif under_label and line.startswith(" ") and found[-1].bullets:
|
||||
found[-1].bullets[-1] += f"\n{line}"
|
||||
elif not line.startswith(" "):
|
||||
listing = False
|
||||
under_label = False
|
||||
return found
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
|
||||
from comprehension_history import counted_vote, entries, Entry, last_cells, scoring_runs
|
||||
from larv_review.seats import FIRST_SEATS
|
||||
|
||||
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
|
||||
@@ -10,7 +10,7 @@ MIN_PAIRS = 10
|
||||
def ruling_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
|
||||
first, second = FIRST_SEATS
|
||||
cells = [overall_cells(entry) for entry in found if entry.paired]
|
||||
cells = [last_cells(entry.votes) for entry in found if entry.paired]
|
||||
return [counted_vote(each[first]) == counted_vote(each[second]) for each in cells if first in each and second in each]
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ def run_agreement(found: list[Entry]) -> list[bool]:
|
||||
first, second = FIRST_SEATS
|
||||
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
|
||||
for entry in scoring_runs(found):
|
||||
cells = overall_cells(entry)
|
||||
cells = last_cells(entry.scores)
|
||||
if first in cells and second in cells:
|
||||
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
|
||||
pairs = [(each[0], each[1]) for each in runs.values() if len(each) >= 2]
|
||||
|
||||
@@ -162,6 +162,14 @@ class History(unittest.TestCase):
|
||||
fell = ruled.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 6 | 7 | 7 | 7 |\n| Mean | 7 | 6 | 7 | 7 | 7 |\n\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n"
|
||||
self.assertEqual(latest_places(appended(appended("", scored), fell)), hard_since.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n")
|
||||
|
||||
def test_takes_a_seats_vote_from_the_votes_table_whichever_table_comes_first(self):
|
||||
votes = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | same | same | same |\n"
|
||||
scores = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 7 | 7 | 7 | 7 |\n| Mean | 7 | 7 | 7 | 7 | 7 |\n"
|
||||
places = "Mid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n- Shape: `bin/f.py:2` `o`: dropped\n"
|
||||
kept = "## 2026-10-07T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n"
|
||||
for tables in (votes + scores, scores + votes):
|
||||
self.assertEqual(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + tables + places)), kept)
|
||||
|
||||
def test_names_the_places_of_every_run_on_the_newest_scored_commit(self):
|
||||
run = "## {time}, {pr} at {commit}\n\nJunior A, hardest first:\n\n- `bin/b.py:{line}` `h`: long\n"
|
||||
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
|
||||
|
||||
Reference in New Issue
Block a user