diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 841bf793..93783a1c 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,6 +1,5 @@ import re import subprocess -import sys from failure import Failure from larv_review.history import HistoryChange @@ -21,19 +20,22 @@ def top() -> str | Failure: return found if isinstance(found, Failure) else found.strip() -def default_branch() -> str | Failure: - """The default branch's ref: `origin/` after a fetch, with that remote, else the local main or master.""" +def default_branch(fetched: bool) -> tuple[str, str | None] | Failure: + """The default branch's ref, `origin/` after a fetch with that remote, else the local main or master, and a note for stderr. Unless fetched, a failed fetch reads origin as last fetched, and the note says so.""" remotes = git("remote") if isinstance(remotes, Failure): return remotes if "origin" in remotes.split(): - if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure): - print(f"reading origin as last fetched: {fetched.reason}", file=sys.stderr) + fetch = git("fetch", "--quiet", "origin") + if isinstance(fetch, Failure) and fetched: + return fetch + note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") - return default.strip() if not isinstance(default, Failure) else origin_head() + named = default.strip() if not isinstance(default, Failure) else origin_head() + return named if isinstance(named, Failure) else (named, note) for branch in ("main", "master"): if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): - return branch + return branch, None return Failure("no origin remote, and no main or master branch to take as the default branch") @@ -44,7 +46,7 @@ def origin_head() -> str | Failure: return listed if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed): return f"origin/{named.group(1)}" - return Failure("origin names no default branch") + return Failure("origin names no default branch; set it with `git remote set-head origin --auto`") def commit_exists(commit: str) -> bool: diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index af9cdf8d..2695686a 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -7,7 +7,7 @@ from larv_review.seats import ARCHITECT, DIMENSIONS, MEAN, Seat from failure import Failure from markdown_sections import sections -DATED = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}[^,]*, ") +DATED = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}(?:T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)?, ") DECIDED_BY = "decided by" HARDEST_FIRST = "hardest first" HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$") @@ -108,9 +108,11 @@ def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list return found, dropped -def heading(at: float, read: str, paired: bool) -> re.Match[str] | Failure: - """An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read; a read that opens with its own date, as a run moved from a decision entry does, keeps it.""" - title = read if DATED.match(read) else f"{time.strftime(STAMP, time.gmtime(at))}, {read}" +def heading(at: float, read: str, paired: bool, moved: bool) -> re.Match[str] | Failure: + """An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read. A run moved from a decision entry opens instead with the date or time that entry gives.""" + if moved != bool(DATED.match(read)): + return Failure(f"only a seats file holding a {MEAN} line alone opens with a date or UTC time, then `, `: {read}") + title = read if moved else f"{time.strftime(STAMP, time.gmtime(at))}, {read}" if (named := HEADING.match(title)) and bool(named.group(4)) == paired: return named return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {read}") diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 29a13446..1b441050 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -64,8 +64,9 @@ import typing from larv_review.history import appended, heading, ruling_entry, scoring_entry from larv_review.rules import base, CAP, FLOOR, means, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes from larv_review.git import commit_exists, default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top -from larv_review.seats import DIMENSIONS, report, scores +from larv_review.seats import DIMENSIONS, MEAN, Report, report, scores from failure import Failure +from rank_todo import ITEMS_HEADER from file_writes import replace_file USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run ... | record-ruling | record-scoring " @@ -76,12 +77,16 @@ def main(argv: list[str]) -> int: print(__doc__.strip().format(cap=CAP, floor=FLOOR)) return 0 command, *given = argv or [""] - if command in ("ruling-base", "round-count") and not given: - done = with_default_branch(ruling_base if command == "ruling-base" else round_count) + if command == "ruling-base" and not given: + done = with_default_branch(ruling_base, fetched=True) + elif command == "round-count" and not given: + done = with_default_branch(round_count, fetched=False) elif command == "needs-scoring-run" and given and all(id_.isdigit() for id_ in given): - done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given])) - elif command in ("record-ruling", "record-scoring") and len(given) == 1: - done = record(pathlib.Path(given[0]), command == "record-ruling") + done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), fetched=True) + elif command == "record-ruling" and len(given) == 1: + done = record_ruling(pathlib.Path(given[0])) + elif command == "record-scoring" and len(given) == 1: + done = record_scoring(pathlib.Path(given[0])) else: print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) return 1 @@ -91,9 +96,15 @@ def main(argv: list[str]) -> int: return 0 -def with_default_branch(command: typing.Callable[[str], Failure | None]) -> Failure | None: - default = default_branch() - return default if isinstance(default, Failure) else command(default) +def with_default_branch(command: typing.Callable[[str], Failure | None], fetched: bool) -> Failure | None: + """fetched: whether the command needs origin as it is now, or may read it as last fetched.""" + default = default_branch(fetched) + if isinstance(default, Failure): + return default + branch, note = default + if note: + print(note, file=sys.stderr) + return command(branch) def ruling_base(default: str) -> Failure | None: @@ -103,10 +114,13 @@ def ruling_base(default: str) -> Failure | None: history = file_at(default, HISTORY) if isinstance(history, Failure): return history + if found := base(changes, history, default): + print("\n".join(found)) + return None merge_base = git("merge-base", "HEAD", default) if isinstance(merge_base, Failure): return merge_base - print("\n".join(base(changes, history, merge_base.strip(), default))) + print(f"{merge_base.strip()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.") return None @@ -130,7 +144,8 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read todo.md: {failure}") - planned = plan_items(before) + # A plan a chunk is reshaping into one table has none yet on the default branch. + planned = plan_items(before) if ITEMS_HEADER in before.splitlines() else [] if isinstance(planned, Failure): return Failure(f"{default}'s todo.md: {planned.reason}") chunk = plan_items(after) @@ -146,30 +161,28 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: return None -def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: - try: - given = report(seats_file.read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"could not read {seats_file}: {failure}") - if isinstance(given, Failure): - return given - named = heading(time.time(), given.read, paired) - if isinstance(named, Failure): - return named - title = named.group(0) - if unknown := [commit for commit in named.group(3, 4) if commit and not commit_exists(commit)]: - return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout") - if paired: - counted = votes(given.seats) - if isinstance(counted, Failure): - return counted - tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) - ruled = ruling(list(counted.values())) - if ruled is None: - print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") - return None - print(f"Ruling: {ruled}. Votes as counted: {tally}.") - return append(ruling_entry(title, given.seats, counted, ruled)) +def record_ruling(seats_file: pathlib.Path) -> Failure | None: + read = read_seats(seats_file, paired=True) + if isinstance(read, Failure): + return read + title, given = read + counted = votes(given.seats) + if isinstance(counted, Failure): + return counted + tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) + ruled = ruling(list(counted.values())) + if ruled is None: + print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") + return None + print(f"Ruling: {ruled}. Votes as counted: {tally}.") + return append(ruling_entry(title, given.seats, counted, ruled)) + + +def record_scoring(seats_file: pathlib.Path) -> Failure | None: + read = read_seats(seats_file, paired=False) + if isinstance(read, Failure): + return read + title, given = read found = scores(given.seats) if isinstance(found, Failure): return found @@ -179,6 +192,22 @@ def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: return append(scoring_entry(title, given.seats, found, [str(value) for value in mean])) +def read_seats(seats_file: pathlib.Path, paired: bool) -> tuple[str, Report] | Failure: + """The seats file, and the heading its record goes under, once each commit it names is in the checkout.""" + try: + given = report(seats_file.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {seats_file}: {failure}") + if isinstance(given, Failure): + return given + named = heading(time.time(), given.read, paired, [seat.name for seat in given.seats] == [MEAN]) + if isinstance(named, Failure): + return named + if unknown := [commit for commit in named.group(3, 4) if commit and not commit_exists(commit)]: + return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout") + return named.group(0), given + + def append(entry: str) -> Failure | None: checkout = top() if isinstance(checkout, Failure): diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index 04fd2bc9..bfdc6ea2 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -75,13 +75,13 @@ def first_ruling(history: str) -> Entry | None: return rulings[0] if rulings else None -def base(changes: list[HistoryChange], history: str, merge_base: str, default: str) -> tuple[str, str]: - """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names, else the merge base of HEAD and the default branch. history is the default branch's.""" +def base(changes: list[HistoryChange], history: str, default: str) -> tuple[str, str] | None: + """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names; None when neither exists, so the base is the merge base of HEAD and the default branch. history is the default branch's.""" if found := measured_commit(changes): return found, f"The newest merged change on {default} that adds a scoring run to the history, or whose last added paired ruling is better." if (first := first_ruling(history)) and first.against: return first.against, f"No merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names." - return merge_base, f"No merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}." + return None def plan_items(todo: str) -> list[Item] | Failure: diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index a1db8990..af8238a3 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -5,13 +5,17 @@ from failure import Failure ARCHITECT = "Inherited architect" DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") -FIRST_SEATS = ("Mid A", ARCHITECT) +JUNIOR = "Junior A" # A scoring run moved from a `comprehension floor:` decision entry kept only the seats' means. MEAN = "Mean" +MID = "Mid A" SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS)) -SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", ARCHITECT) +SENIOR = "Maintainability senior" + +FIRST_SEATS = (MID, ARCHITECT) +SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT) SEAT_LINE = re.compile(rf"^({'|'.join((*SCORING_SEATS, MEAN))}): (.+)$") -SPLIT_SEATS = ("Maintainability senior", "Junior A") +SPLIT_SEATS = (SENIOR, JUNIOR) @dataclasses.dataclass(frozen=True) diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 19d7c98d..fbb897b0 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -108,11 +108,11 @@ class Base(unittest.TestCase): self.assertEqual(measured_commit([worse_last, older]), "old") self.assertIsNone(measured_commit([same])) - def test_falls_back_to_the_first_rulings_base_then_to_the_merge_base(self): + def test_falls_back_to_the_first_rulings_base_then_to_none(self): ruled = paired("2026-10-08T13:00:00Z", "worse") - self.assertEqual(base([HistoryChange("c", "", ruled)], ruled, "m", "main")[0], "aaaaaaa") - self.assertEqual(base([], "", "m", "main")[0], "m") - self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "m", "main")[0], "c") + self.assertEqual(base([HistoryChange("c", "", ruled)], ruled, "main"), ("aaaaaaa", "No merged change on main adds a scoring run or a better ruling; the base its first paired ruling names.")) + self.assertIsNone(base([], "", "main")) + self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "main")[0], "c") def test_finds_the_earliest_ruling_by_its_time(self): ruled = first_ruling(paired("2026-10-08T14:00:00Z", "same", "ccccccc") + paired("2026-10-08T13:00:00Z", "worse")) @@ -269,6 +269,20 @@ class LarvReviewTool(unittest.TestCase): text = (self.checkout / "docs" / "comprehension-history.md").read_text() self.assertIn(f"## 2026-10-04, PR #1 merged at {self.start}\n\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mean | 7.38 | 6.63 | 7.00 | 6.88 | 6.88 |\n", text) + def test_states_its_rules_and_finds_origins_default_branch_where_the_clone_recorded_none(self): + helped = self.run_tool("--help") + self.assertEqual(helped.returncode, 0, helped.stderr) + self.assertIn("the cap of 3 rounds", helped.stdout) + self.git("remote", "set-head", "origin", "--delete") + self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n") + + def test_refuses_a_dated_first_line_except_for_a_mean_alone_and_a_mean_without_one(self): + mean = "Mean: Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7\n" + self.assertEqual(self.run_tool("record-scoring", self.seats_file(f"PR #1 at {self.start}\n\n{mean}")).returncode, 1) + ruled = self.run_tool("record-ruling", self.seats_file(f"2026-10-08, PR #2 at {self.start}, against {self.start}\n\nMid A: same\n\nInherited architect: same\n")) + self.assertEqual(ruled.returncode, 1) + self.assertIn("only a seats file holding a Mean line alone", ruled.stderr) + def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self): self.commit("Answer prose round 1: a") self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))