Answer the architecture and stability reviews' first round: exempt rows, restored item 6, retired decisions

This commit is contained in:
2026-10-02 20:04:19 +02:00
parent c12a4109f9
commit c0dba6625c
7 changed files with 115 additions and 77 deletions
+46 -18
View File
@@ -4,20 +4,24 @@
usage: rank_todo.py [--check] [todo.md]
Reads todo.md (default: ./todo.md) and the README.md beside it. Rewrites each item's Score from
`Score = <formula>` under ## Scoring, sorts the ## Items table by release, then score from highest,
then ID, and orders ## Details to match, each heading `### <ID>. <tagline>`. --check writes nothing
and fails when the file is not ranked as it would be.
`Score = <formula>` under ## Scoring, sorts the ## Items table by release, then exempt items first,
then score from highest, then ID, and orders ## Details to match, each heading `### <ID>. <tagline>`.
An item's Exempt cell is empty, or names why the bar does not apply to it: security, question or
decision. --check writes nothing and fails when the file is not ranked as it would be.
Exit 1, saying why, when todo.md breaks the format, its goal weights do not list README.md's goals,
an item scores under the `Bar = <number>` it states, or --check finds it unranked.
an item that is not exempt scores under the `Bar = <number>` it states, judged on the Score as
shown, or --check finds it unranked.
"""
import ast
import dataclasses
import math
import pathlib
import re
import sys
ITEMS_HEADER = "| ID | Release | Item | R | S | A | G | Goals | Score |"
EXEMPTIONS = ("", "decision", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
WEIGHTS_HEADER = "| Goal | W |"
VARIABLES = ("A", "G", "R", "S", "W")
@@ -26,6 +30,7 @@ VARIABLES = ("A", "G", "R", "S", "W")
class Item:
id: int
release: tuple[int, int, int]
exempt: str
tagline: str
scores: dict[str, int]
goals: tuple[str, ...]
@@ -49,8 +54,8 @@ def main(argv: list[str]) -> int:
text = todo.read_text(encoding="utf-8")
readme = (todo.parent / "README.md").read_text(encoding="utf-8")
ranked, under_bar = rank(text, readme_goals(readme))
except (OSError, Malformed) as failure:
print(f"{todo}: {getattr(failure, 'strerror', None) or failure}", file=sys.stderr)
except (OSError, UnicodeDecodeError, Malformed) as failure:
print(failure if isinstance(failure, OSError) else f"{todo}: {failure}", file=sys.stderr)
return 1
if check and ranked != text:
print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr)
@@ -70,13 +75,15 @@ def rank(text: str, goals: list[str]) -> tuple[str, list[str]]:
weights = parse_weights(lines, goals)
start, end = table_rows(lines, ITEMS_HEADER)
items = [parse_item(row, weights) for row in lines[start:end]]
if any(line.startswith("|") for line in section_lines(lines, end)):
raise Malformed("## Items holds a row outside its table; keep the rows together under the header")
if len({item.id for item in items}) < len(items):
raise Malformed("two items share an ID")
scored = sorted(((item, score(formula, item, weights)) for item in items), key=lambda pair: (pair[0].release, -pair[1], pair[0].id))
scored = sorted(((item, score(formula, item, weights)) for item in items), key=lambda pair: (pair[0].release, not pair[0].exempt, -pair[1], pair[0].id))
lines[start:end] = [render_item(item, value) for item, value in scored]
text = "\n".join(lines)
text = rank_details(text, [item for item, _ in scored])
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; rescore it or delete it" for item, value in scored if round(value, 1) < bar]
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; rescore it or delete it" for item, value in scored if not item.exempt and round(value, 1) < bar]
return text, under_bar
@@ -87,13 +94,15 @@ def readme_goals(readme: str) -> list[str]:
raise Malformed("README.md has no ## Goals")
goals: list[str] = []
path: list[tuple[int, str]] = []
for indent, number in re.findall(r"^( *)(\d+)\. ", section.group(1), re.M):
for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", section.group(1).expandtabs(4), re.M):
while path and path[-1][0] >= len(indent):
path.pop()
path.append((len(indent), number))
goals.append(".".join(part for _, part in path))
if not goals:
raise Malformed("README.md's ## Goals has no numbered goal")
if len(set(goals)) < len(goals):
raise Malformed(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
return goals
@@ -146,14 +155,20 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float:
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
return evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
try:
return evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
except ZeroDivisionError:
raise Malformed(f"the formula divides by zero for item {item.id}") from None
def number(text: str, what: str) -> float:
try:
return float(text)
value = float(text)
except ValueError:
raise Malformed(f"{what} {text!r} is not a number") from None
value = math.nan
if not math.isfinite(value):
raise Malformed(f"{what} {text!r} is not a finite number")
return value
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float]:
@@ -181,6 +196,14 @@ def table_rows(lines: list[str], header: str) -> tuple[int, int]:
return start, end
def section_lines(lines: list[str], start: int) -> list[str]:
"""The lines from start up to the next ## heading."""
end = start
while end < len(lines) and not lines[end].startswith("## "):
end += 1
return lines[start:end]
def cells(row: str, count: int) -> list[str]:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
if len(found) != count:
@@ -189,29 +212,31 @@ def cells(row: str, count: int) -> list[str]:
def parse_item(row: str, weights: dict[str, float]) -> Item:
id_, release, tagline, r, s, a, g, goals, _ = cells(row, 9)
if not id_.isdigit() or int(id_) < 1:
id_, release, exempt, tagline, r, s, a, g, goals, _ = cells(row, 10)
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
raise Malformed(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"\d+\.\d+\.\d+", release):
raise Malformed(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
raise Malformed(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
raise Malformed(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
scores = {}
for name, value in zip("RSAG", (r, s, a, g)):
if not value.isdigit() or not 1 <= int(value) <= 10:
if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10:
raise Malformed(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
if unknown := [goal for goal in cited if goal not in weights]:
raise Malformed(f"item {id_} cites goal {', '.join(unknown)}, which the goal weights do not list")
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), tagline, scores, cited)
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
def render_item(item: Item, value: float) -> str:
release = ".".join(str(part) for part in item.release)
scores = " | ".join(str(item.scores[name]) for name in "RSAG")
return f"| {item.id} | {release} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
def rank_details(text: str, items: list[Item]) -> str:
@@ -219,6 +244,9 @@ def rank_details(text: str, items: list[Item]) -> str:
if section is None:
return text
body = section.group(1)
# A fenced line such as "## Goals" or "### 2. x" would read as a heading and split a detail.
if re.search(r"^ {0,3}(```|~~~)", body, re.M):
raise Malformed("## Details holds a fenced code block; indent quoted markdown by four spaces instead")
parts = re.split(r"^### (\d+)\. [^\n]*\n", body, flags=re.M)
if parts[0].strip():
raise Malformed("## Details holds text before its first ### <ID>. heading")
+33 -13
View File
@@ -1,3 +1,5 @@
import contextlib
import io
import pathlib
import sys
import tempfile
@@ -26,11 +28,12 @@ TODO = """# todo
## Items
| ID | Release | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|
| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 |
| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |
| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |
| 3 | 0.1.0 | | **Make it fast, `a \| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |
| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | 0 |
## Details
@@ -41,6 +44,10 @@ Later detail.
### 3. Make it fast.
Fast detail.
## Notes
Kept as written.
"""
@@ -50,11 +57,12 @@ class Rank(unittest.TestCase):
def test_scores_and_sorts_by_release_then_score_and_orders_the_details_to_match(self):
text, under_bar = self.ranked()
self.assertIn("""| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 |
| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 |
| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 |
self.assertIn("""| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | -6.8 |
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 |
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 |
""", text)
self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n"))
self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast, `a \\| b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n"))
self.assertEqual(under_bar, [])
self.assertEqual(self.ranked(text), (text, []))
@@ -64,6 +72,9 @@ class Rank(unittest.TestCase):
def test_reads_goals_and_sub_goals_in_reading_order(self):
self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"])
self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), ["1", "2", "2.1"])
with self.assertRaises(rank_todo.Malformed):
rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct."))
def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self):
with self.assertRaises(rank_todo.Malformed) as raised:
@@ -76,11 +87,16 @@ class Rank(unittest.TestCase):
self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula))
def test_refuses_a_row_or_detail_off_the_format(self):
row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |"
broken = {
"| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |": "| 2 | 0.1 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |",
"| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |": "| 3 | 0.1.0 | Make it fast. | 3 | 11 | 6 | 8 | 7 | 0 |",
"### 3. Make it fast.": "### 4. Make it fast.",
"`Bar = 9`": "",
row: row.replace("0.1.0", "0.1"),
row + "\n": row.replace("5 | 5", "5 | ²") + "\n",
"| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 0 |\n\n## Details",
"| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |",
"Fast detail.": "```\n## Goals\n```",
"### 3. Make it fast.": "### 5. Make it fast.",
"`Bar = 9`": "`Bar = nan`",
"-R - S/4 + 2*A + 2*G*W": "R / (S - 2)",
}
for old, new in broken.items():
with self.subTest(new=new), self.assertRaises(rank_todo.Malformed):
@@ -97,6 +113,10 @@ class Main(unittest.TestCase):
self.assertEqual(todo.read_text(), TODO)
self.assertEqual(rank_todo.main([str(todo)]), 0)
self.assertEqual(rank_todo.main(["--check", str(todo)]), 0)
pathlib.Path(temp, "README.md").unlink()
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(rank_todo.main([str(todo)]), 1)
self.assertIn("README.md", said.getvalue())
class ThisRepo(unittest.TestCase):