320 lines
14 KiB
Python
320 lines
14 KiB
Python
import dataclasses
|
|
import decimal
|
|
import re
|
|
|
|
from failure import Failure
|
|
from markdown_text import sections
|
|
from utc_stamp import utc
|
|
|
|
ARCHITECT = "Inherited architect"
|
|
DECIDED_BY = "decided by"
|
|
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
|
|
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
|
|
FLOOR = decimal.Decimal("7.0")
|
|
HARDEST_FIRST = "hardest first"
|
|
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
|
|
HISTORY = "docs/comprehension-history.md"
|
|
JUNIOR = "Junior A"
|
|
MEAN = "Mean"
|
|
MID = "Mid A"
|
|
# `path:line` or `:line`, then the unit's name where one follows.
|
|
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
|
|
RESTRUCTURE_FIRST = "would restructure first"
|
|
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
|
|
# A seat's label over its bullets: its name, then the listing's kind.
|
|
LABEL = re.compile(rf"^(.+), ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
|
SENIOR = "Maintainability senior"
|
|
TITLE = "# Comprehension history\n"
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Seat:
|
|
name: str
|
|
said: str
|
|
places: list[str]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Place:
|
|
path: str
|
|
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.
|
|
|
|
`score_rows` holds the rows of the table with a Mean row, and `vote_rows` those of any other table: each row's cells after the first, keyed by the first, without the header. `ruled_listings` holds the decided-by listings, and `scored_listings` the hardest-first and would-restructure-first ones."""
|
|
heading: str
|
|
time: str
|
|
commit: str
|
|
against: str | None
|
|
ruling: str | None
|
|
vote_rows: dict[str, list[str]]
|
|
score_rows: dict[str, list[str]]
|
|
ruled_listings: list[Listing]
|
|
scored_listings: list[Listing]
|
|
|
|
@property
|
|
def paired(self) -> bool:
|
|
return self.against is not None
|
|
|
|
@property
|
|
def scored(self) -> bool:
|
|
"""Whether the entry scores the project: a scoring run, or a ruling that lists scoring seats' places, as a ruling from before PR #255 may, beside their table."""
|
|
return not self.paired or bool(self.scored_places)
|
|
|
|
@property
|
|
def ruled_places(self) -> list[Place]:
|
|
return [place for listing in self.ruled_listings for place in listing.places]
|
|
|
|
@property
|
|
def scored_places(self) -> list[Place]:
|
|
return [place for listing in self.scored_listings for place in listing.places]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class HistoryChange:
|
|
"""A merged change on the default branch that touched the history, and the history before and after it."""
|
|
commit: str
|
|
before: str
|
|
after: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Heading:
|
|
title: str
|
|
label: str
|
|
commit: str
|
|
against: str | None
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class ScoringRun:
|
|
"""The four scoring seats' lines, their scores as written and the means, in DIMENSIONS' order."""
|
|
seats: list[Seat]
|
|
scores: dict[str, list[str]]
|
|
means: list[decimal.Decimal]
|
|
|
|
|
|
# A paired ruling as entry_text writes it. A scoring run's heading has no `, against`; it has no Ruling line, ends its table with a Mean row, and labels each seat's places `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`. A ruling recorded before PR #232 has a `| Seat | Vote |` table, whose one cell is the overall vote.
|
|
#
|
|
# ## 2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75
|
|
#
|
|
# Ruling: same
|
|
#
|
|
# | Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
|
# |---|---|---|---|---|---|
|
|
# | Mid A | better | worse | same | same | better |
|
|
#
|
|
# Mid A, decided by:
|
|
#
|
|
# - Locality: `bin/x.py:12` `run`: three branches to hold at once
|
|
def entries(history: str) -> list[Entry]:
|
|
"""Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out."""
|
|
found = []
|
|
for heading, bodies in sections(history).items():
|
|
if named := HEADING.match(heading):
|
|
body = "\n".join(bodies)
|
|
ruling = RULING.search(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,
|
|
vote_rows={name: cells for table in tables if MEAN not in table for name, cells in table.items()},
|
|
score_rows={name: cells for table in tables if MEAN in table for name, cells in table.items()},
|
|
ruled_listings=[listing for listing in listed if listing.kind == DECIDED_BY],
|
|
scored_listings=[listing for listing in listed if listing.kind != DECIDED_BY],
|
|
))
|
|
return found
|
|
|
|
|
|
def latest_places(history: str) -> str | None:
|
|
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
|
|
|
|
They start at the first entry that scores that commit, so a rerun of one head adds to the run before it. Where no entry scores the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
|
|
found = by_time(entries(history))
|
|
newest = newest_commit_runs(found)
|
|
start = found.index(newest[0]) if newest else 0
|
|
parts = [placed(entry, worse_places(entry) + entry.scored_listings) for entry in found[start:]]
|
|
return "\n".join(part for part in parts if part) or None
|
|
|
|
|
|
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
|
"""The mean of the overall means of the entries that score the newest scored commit, since a rerun of one head measures it again; None where no entry scores the project."""
|
|
overalls = []
|
|
for entry in newest_commit_runs(by_time(entries(history))):
|
|
overall = run_overall(entry)
|
|
if isinstance(overall, Failure):
|
|
return overall
|
|
overalls.append(overall)
|
|
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
|
|
|
|
|
|
def newest_commit_runs(found: list[Entry]) -> list[Entry]:
|
|
"""The entries that score the commit of the last entry that scores the project, in found's order; empty where none does. Commits match by prefix, since a heading may write one at any length from 7 characters."""
|
|
scored = [entry for entry in found if entry.scored]
|
|
if not scored:
|
|
return []
|
|
newest = scored[-1].commit
|
|
return [entry for entry in scored if entry.commit.startswith(newest) or newest.startswith(entry.commit)]
|
|
|
|
|
|
def run_overall(run: Entry) -> decimal.Decimal | Failure:
|
|
"""The overall cell of the Mean row of an entry that scores the project."""
|
|
try:
|
|
overall = decimal.Decimal(last_cells(run.score_rows).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 last_cells(rows: dict[str, list[str]]) -> dict[str, str]:
|
|
"""Each row's last cell, by its first cell, leaving out a row whose last cell is empty: a seat's overall vote in an entry's `vote_rows`, or its overall score, or the Mean row's, in its `score_rows`."""
|
|
return {name: cells[-1] for name, cells in rows.items() if cells and cells[-1]}
|
|
|
|
|
|
def by_time(found: list[Entry]) -> list[Entry]:
|
|
return sorted(found, key=lambda entry: entry.time)
|
|
|
|
|
|
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."""
|
|
cut = []
|
|
for listing in entry.ruled_listings:
|
|
worse = worse_dimensions(entry.vote_rows.get(listing.seat, []))
|
|
kept = [bullet for bullet in listing.bullets if worse.intersection(place_dimensions(bullet.removeprefix("- ")))]
|
|
cut.append(dataclasses.replace(listing, bullets=kept))
|
|
return cut
|
|
|
|
|
|
def placed(entry: Entry, listed: list[Listing]) -> str:
|
|
"""The entry's heading, then the label and bullets of each listing that has bullets; empty when none has."""
|
|
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_dimensions(votes: list[str]) -> set[str]:
|
|
"""The dimensions, Overall included, that a seat's row of votes counted as worse; `same (voted worse, …)` counts as same. A row without one vote per dimension, such as the older single `Vote` table's, gives an empty set."""
|
|
return {dimension for dimension, vote in zip(DIMENSIONS, votes) if vote == "worse"} if len(votes) == len(DIMENSIONS) else set()
|
|
|
|
|
|
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. Tables may touch, so a table starts at the row above a separator."""
|
|
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]]:
|
|
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
|
return name, cells
|
|
|
|
|
|
def place_dimensions(place: str) -> list[str]:
|
|
"""The dimensions a place opens with, as in `Locality, Shape: `path:line` ...`; empty when any name before the first `: ` is no dimension."""
|
|
named = place.partition(": ")[0].split(", ")
|
|
return named if all(name in DIMENSIONS for name in named) else []
|
|
|
|
|
|
def recorded(history: str, read: str) -> bool:
|
|
"""Whether the history holds an entry on what a seats file's first line says the seats read."""
|
|
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
|
|
|
|
|
|
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 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(" "):
|
|
under_label = False
|
|
return found
|
|
|
|
|
|
def bullet_places(bullet: str) -> list[Place]:
|
|
"""A `:line` with no path is in the file named before it in the bullet."""
|
|
places = []
|
|
path = ""
|
|
for match in PLACE.finditer(bullet):
|
|
path = match.group(1) or path
|
|
if path:
|
|
places.append(Place(path, match.group(2)))
|
|
return places
|
|
|
|
|
|
def heading(at: float, read: str, paired: bool) -> Heading | Failure:
|
|
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read."""
|
|
title = f"{utc(at)}, {read}"
|
|
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
|
|
return Heading(title, named.group(2), named.group(3), named.group(4))
|
|
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
|
|
|
|
|
|
def appended(history: str, entry: str) -> str:
|
|
"""The history with entry added last; an empty history gets the file's title first."""
|
|
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
|
|
return f"{text}\n{entry}"
|
|
|
|
|
|
def ruling_entry(title: str, seats: list[Seat], said: dict[str, list[str]], counted: dict[str, list[str]], ruled: str) -> str:
|
|
"""A paired ruling's entry; a seat's vote that counted as same for want of a place says so."""
|
|
votes = [[seat.name, *map(vote_text, DIMENSIONS, said[seat.name], counted[seat.name])] for seat in seats]
|
|
return entry_text(title, [f"Ruling: {ruled}"], [[["Seat", *DIMENSIONS], *votes]], [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats])
|
|
|
|
|
|
def vote_text(dimension: str, said: str, counted: str) -> str:
|
|
if counted == said:
|
|
return counted
|
|
return f"same (voted {said}, naming no place)" if dimension == DIMENSIONS[-1] else f"same (voted {said}, no place naming {dimension})"
|
|
|
|
|
|
def counted_vote(cell: str) -> str:
|
|
"""The vote a ruling's table cell counted as, which is its first word, as vote_text writes it."""
|
|
return cell.split()[0]
|
|
|
|
|
|
def scoring_entry(title: str, scoring: ScoringRun) -> str:
|
|
return entry_text(title, [], [scores_table(scoring)], scoring_labels(scoring.seats))
|
|
|
|
|
|
def scores_table(scoring: ScoringRun) -> list[list[str]]:
|
|
return [["Seat", *DIMENSIONS], *([seat, *values] for seat, values in scoring.scores.items()), [MEAN, *map(str, scoring.means)]]
|
|
|
|
|
|
def scoring_labels(seats: list[Seat]) -> list[tuple[str, list[str]]]:
|
|
return [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
|
|
|
|
|
|
def entry_text(title: str, lines: list[str], tables: list[list[list[str]]], seats: list[tuple[str, list[str]]]) -> str:
|
|
"""The heading, any lines such as `Ruling: same`, each table, whose first row is its header, and under each seat's label its places, one bullet each."""
|
|
parts = [f"## {title}", *lines, *("\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)]) for header, *rows in tables)]
|
|
parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places]
|
|
return "\n\n".join(parts) + "\n"
|
|
|
|
|
|
def row_text(cells: list[str]) -> str:
|
|
return "| " + " | ".join(cells) + " |"
|