242 lines
11 KiB
Python
242 lines
11 KiB
Python
"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format.
|
|
|
|
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <seats file> | record-scoring <seats file>
|
|
|
|
Run it inside a project checkout or one of its worktrees. ruling-base, round-count and
|
|
needs-scoring-run first fetch origin, when the checkout has that remote, and take origin's default
|
|
branch, or else the local main or master, as the default branch. When the fetch fails, round-count
|
|
reads origin as last fetched and says so on stderr; the other two exit 1. The history is
|
|
docs/comprehension-history.md in the checkout.
|
|
|
|
ruling-base prints the commit a paired ruling reads against, then which of these found it. The last
|
|
measured commit is the default branch's newest merged change that adds a scoring run to the
|
|
history, or whose last added paired ruling, by heading time, is better; a merge commit counts as
|
|
one change against its first parent. With none, the base is the one the history's first paired
|
|
ruling names; with no ruling either, it is the merge base of HEAD and the default branch.
|
|
|
|
round-count prints each pass's count: the highest <n> among the titles opening
|
|
`Answer <pass> round <n>:` of commits the default branch does not hold. It marks each pass at the
|
|
cap of {cap} rounds, and each name in such a title that is not a pass.
|
|
|
|
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
|
|
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
|
|
an item whose tagline names the comprehension floor, or when it leaves a release with no item in
|
|
the checkout's todo.md, less the shipped items, and work has landed towards that release. Work has
|
|
landed when the chunk ships one of the release's items, or when the release is the earliest the
|
|
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
|
|
no v* tag.
|
|
|
|
record-ruling and record-scoring read a seats file: a first line naming what the seats read,
|
|
`<PR or branch> at <commit>`, ending `, against <base>` for a paired ruling, then each seat's
|
|
line, each followed by its places, one `- ` bullet each, as the history writes them. A seat's line
|
|
opens with its label, written exactly: `Junior A:`, `Mid A:`, `Maintainability senior:` or
|
|
`Inherited architect:`.
|
|
|
|
PR #231 at abc1234, against def5678
|
|
|
|
Mid A: worse
|
|
|
|
- `bin/x.py:12` `run`: three branches to hold at once
|
|
|
|
Inherited architect: worse
|
|
|
|
- `bin/x.py:12` `run`: ...
|
|
|
|
record-ruling takes Mid A's and the inherited architect's votes, better, same or worse; a better or
|
|
worse vote naming no place in backticks, `path:line`, counts as same, and the printed votes say so.
|
|
When the two counted votes differ, it appends nothing and prints `Split:`, saying to add the
|
|
maintainability senior's and Junior A's lines. Otherwise the ruling is the vote that leads each
|
|
other vote by two or more, else same; it prints `Ruling:` and appends the ruling.
|
|
|
|
record-scoring takes Junior A's, Mid A's, the maintainability senior's and the inherited
|
|
architect's lines in that order, or a `Mean:` line alone for a run moved from a decision entry.
|
|
Each line is `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency <n>, Overall <n>`, each
|
|
score from 1 to 10 and the overall at most 1 above the line's lowest dimension. Its first line
|
|
names no `, against`. It appends the seats' scores and their means, rounded half up to two
|
|
decimals, and prints the means and each one under the floor of {floor}.
|
|
|
|
Each record is appended to the history, created when missing, under a heading of the current UTC
|
|
time and the seats file's first line. A file holding a `Mean:` line alone opens with the date or
|
|
time its decision entry gives, and that line alone is the heading. Each commit the line names
|
|
must be in the checkout. Each run appends, so record a ruling or a run once.
|
|
|
|
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
|
|
breaks the shape above, or when git cannot start, finds no checkout or no default branch, cannot
|
|
fetch origin for ruling-base or needs-scoring-run, or cannot read or write the history or todo.md.
|
|
"""
|
|
import pathlib
|
|
import re
|
|
import sys
|
|
import time
|
|
import typing
|
|
|
|
from larv_review.history import appended, heading, ruling_entry, scoring_entry, vote_text
|
|
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, MEAN, Report, report, score_line, 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 [<item ID>...] | record-ruling <seats file> | record-scoring <seats file>"
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
if argv in (["-h"], ["--help"]):
|
|
print(__doc__.strip().format(cap=CAP, floor=FLOOR))
|
|
return 0
|
|
command, *given = argv or [""]
|
|
if command == "ruling-base" and not given:
|
|
done = with_default_branch(ruling_base, stale_ok=False)
|
|
elif command == "round-count" and not given:
|
|
done = with_default_branch(round_count, stale_ok=True)
|
|
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
|
|
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
|
|
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]))
|
|
elif command == "needs-scoring-run":
|
|
print(f"needs-scoring-run takes item IDs, the numbers in todo.md's ID column: {' '.join(given)}", file=sys.stderr)
|
|
return 1
|
|
elif not argv:
|
|
print(USAGE, file=sys.stderr)
|
|
return 1
|
|
else:
|
|
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
|
|
return 1
|
|
if isinstance(done, Failure):
|
|
print(done.reason, file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
def with_default_branch(command: typing.Callable[[str], Failure | None], stale_ok: bool) -> Failure | None:
|
|
default = default_branch(stale_ok)
|
|
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:
|
|
changes = history_changes(default)
|
|
if isinstance(changes, Failure):
|
|
return changes
|
|
history = file_at(default, HISTORY)
|
|
if isinstance(history, Failure):
|
|
return history
|
|
if found := base(changes, history):
|
|
print("\n".join(found))
|
|
return None
|
|
merge_base = git("merge-base", "HEAD", default)
|
|
if isinstance(merge_base, Failure):
|
|
return merge_base
|
|
print(f"{merge_base.strip()}\nthe merge base of HEAD and {default}")
|
|
return None
|
|
|
|
|
|
def round_count(default: str) -> Failure | None:
|
|
titles = git("log", "--format=%s", f"{default}..HEAD")
|
|
if isinstance(titles, Failure):
|
|
return titles
|
|
for name, count in round_counts(titles.splitlines()).items():
|
|
print(f"{name}: {count}{', at the cap' if count >= CAP else ''}{'' if name in PASSES else ', not a pass: check the commit title'}")
|
|
return None
|
|
|
|
|
|
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
|
|
checkout = top()
|
|
if isinstance(checkout, Failure):
|
|
return checkout
|
|
before = file_at(default, "todo.md")
|
|
if isinstance(before, Failure):
|
|
return before
|
|
try:
|
|
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}")
|
|
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
|
|
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)
|
|
if isinstance(chunk, Failure):
|
|
return Failure(f"the checkout's todo.md: {chunk.reason}")
|
|
landed = landed_since_release(default)
|
|
if isinstance(landed, Failure):
|
|
return landed
|
|
reasons = scoring_run_due(planned, chunk, ids, landed)
|
|
if isinstance(reasons, Failure):
|
|
return reasons
|
|
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
|
|
return None
|
|
|
|
|
|
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.name} {vote_text(seat, counted[seat.name])}" for seat in given.seats)
|
|
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 given.moved_mean is None else {}
|
|
if isinstance(found, Failure):
|
|
return found
|
|
moved = [] if given.moved_mean is None else score_line(MEAN, given.moved_mean)
|
|
if isinstance(moved, Failure):
|
|
return moved
|
|
mean = means(list(found.values()) or [moved])
|
|
under = under_floor(mean)
|
|
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {f'Under the floor of {FLOOR}: ' + ', '.join(under) if under else f'None under the floor of {FLOOR}'}.")
|
|
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, given.moved_mean is not None)
|
|
if isinstance(named, Failure):
|
|
return named
|
|
if unknown := [commit for commit in (named.commit, named.against) 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.title, given
|
|
|
|
|
|
def append(entry: str) -> Failure | None:
|
|
checkout = top()
|
|
if isinstance(checkout, Failure):
|
|
return checkout
|
|
history = pathlib.Path(checkout, HISTORY)
|
|
try:
|
|
text = history.read_text(encoding="utf-8") if history.exists() else ""
|
|
history.parent.mkdir(parents=True, exist_ok=True)
|
|
except (OSError, UnicodeDecodeError) as failure:
|
|
return Failure(f"could not read {history}: {failure}")
|
|
if unwritten := replace_file(history, appended(text, entry).encode()):
|
|
return Failure(f"could not write {history}: {unwritten.reason}")
|
|
print(f"Appended to {history}.")
|
|
return None
|