Answer architecture round 1: 5 🔴, 8 🟡; one Shape per table shape, one moves field, end item 156 for the old shape
This commit is contained in:
@@ -34,7 +34,7 @@ def said(overall: str, locality: str = "same") -> str:
|
||||
|
||||
|
||||
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
|
||||
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "C": 3, "A": 1, "G": 1}, ("1",), ())
|
||||
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "C": 3, "A": 1, "G": 1}, (("1", None),), ())
|
||||
|
||||
|
||||
def todo(*rows: str) -> str:
|
||||
|
||||
+73
-52
@@ -70,8 +70,9 @@ import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from todo_table import BLOCKED_BY, cells, COLUMNS, HEADER_START, Item, items_table, MOVES, OLD_COLUMNS, parse_row, Table, table_rows
|
||||
from todo_table import BLOCKED_BY, cells, HEADER_START, Item, items_table, MOVES, OLD_SHAPE, parse_row, Shape, shape_of, Table, table_rows
|
||||
from failure import Failure
|
||||
from markdown_text import FENCE, sections
|
||||
from file_writes import replace_file
|
||||
@@ -79,30 +80,30 @@ from file_writes import replace_file
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
VARIABLES = ("R", "S", "V")
|
||||
OLD_VARIABLES = ("A", "G", "R", "S", "W")
|
||||
WEIGHTS_HEADER = "| Goal | W |"
|
||||
RESHAPE = f"the items table scores A and G against goal weights todo.md states, the shape before {MOVES}; reshaping it to the shape rank_todo.py --help shows is a chunk of its own"
|
||||
# How README.md marks a goal; None where it marks it neither way.
|
||||
Mark = typing.Literal["Maintain", "Achieve"] | None
|
||||
RESHAPE = f"the items table scores A and G against goal weights todo.md states, the shape before {MOVES}; reshaping it to the shape rank_todo.py --help shows, after marking README.md's goals **Maintain:** or **Achieve:**, is a chunk of its own"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scoring:
|
||||
shape: Shape
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
# README.md's goal numbers in reading order, and the weight of each goal that scores: in an old-shape table every goal, at the weight todo.md states; else each achieve goal.
|
||||
# README.md's goal numbers, in reading order.
|
||||
goals: list[str]
|
||||
# The weight of each goal an item may name: in OLD_SHAPE every goal, at the weight todo.md states; else each achieve goal, by its rank in README.md.
|
||||
weights: dict[str, float]
|
||||
old_shape: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ranked:
|
||||
text: str
|
||||
under_bar: list[str]
|
||||
# Blocker IDs the ranking dropped because the table no longer holds them; printed, since a mistyped ID is dropped the same way.
|
||||
dropped: list[str]
|
||||
old_shape: bool
|
||||
# The lines ranking prints and --check does not: that an old-shape table wants reshaping, and each blocker ID dropped because the table no longer holds it, since a mistyped ID is dropped the same way.
|
||||
notes: list[str]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -128,7 +129,7 @@ def main(argv: list[str]) -> int:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
for line in [RESHAPE] * ranked.old_shape + ranked.dropped + ranked.under_bar:
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
@@ -181,15 +182,14 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
|
||||
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
if "## Items" not in lines:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
found = read_table(lines)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
scoring = read_scoring(text, lines, readme, MOVES not in found.columns)
|
||||
table = read_table(lines)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(found, scoring)
|
||||
items = read_items(table, scoring)
|
||||
if isinstance(items, Failure):
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
@@ -197,17 +197,26 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
# Every table gets the header of all its shape's columns, so one from before BLOCKED_BY joined gains the column.
|
||||
columns = OLD_COLUMNS if scoring.old_shape else COLUMNS
|
||||
lines[found.header:found.start] = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
lines[found.start:found.start + len(scored)] = [render_item(item, value, scoring.old_shape) for item, value in scored]
|
||||
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
|
||||
ranked = rank_details(rewrite_table(lines, table, scored), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
return Ranked(ranked, under_bar, notes(items, shape))
|
||||
|
||||
|
||||
def rewrite_table(lines: list[str], table: Table, scored: list[tuple[Item, float]]) -> str:
|
||||
"""lines with the table's rows in scored's order, under a header naming every column of its shape, so a table from before BLOCKED_BY joined gains the column."""
|
||||
shape = shape_of(table.columns)
|
||||
columns = shape.columns
|
||||
header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
rows = [render_item(item, value, shape) for item, value in scored]
|
||||
return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):])
|
||||
|
||||
|
||||
def notes(items: list[Item], shape: Shape) -> list[str]:
|
||||
held = {item.id for item in items}
|
||||
dropped = [f"item {item.id}: dropped {', '.join(map(str, gone))} from its {BLOCKED_BY}; the table no longer holds {'it' if len(gone) == 1 else 'them'}" for item in items if (gone := sorted(set(item.blocked_by) - held))]
|
||||
return Ranked(ranked, under_bar, dropped, scoring.old_shape)
|
||||
return ([RESHAPE] if shape is OLD_SHAPE else []) + dropped
|
||||
|
||||
|
||||
def blocked_through(id_: int, items: list[Item]) -> set[int]:
|
||||
@@ -238,11 +247,11 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
|
||||
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> Scoring | Failure:
|
||||
def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), OLD_VARIABLES if old_shape else VARIABLES)
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
@@ -252,7 +261,7 @@ def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> S
|
||||
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
|
||||
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
|
||||
numbers = [number for number, _ in goals]
|
||||
if old_shape:
|
||||
if shape is OLD_SHAPE:
|
||||
weights = parse_weights(lines, numbers)
|
||||
elif WEIGHTS_HEADER in lines:
|
||||
weights = Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs each achieve goal by its rank in README.md")
|
||||
@@ -260,11 +269,13 @@ def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> S
|
||||
weights = achieve_weights(goals)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(formula, bar, int(next_id), numbers, weights, old_shape)
|
||||
return Scoring(shape, formula, bar, int(next_id), numbers, weights)
|
||||
|
||||
|
||||
def read_table(lines: list[str]) -> Table | Failure:
|
||||
"""The items table, held to its shape's columns and alone under ## Items."""
|
||||
if "## Items" not in lines:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
table = items_table(lines)
|
||||
if table is None:
|
||||
return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one")
|
||||
@@ -273,17 +284,24 @@ def read_table(lines: list[str]) -> Table | Failure:
|
||||
# A table without C fails, so no chunk starts on an unscored item.
|
||||
if "C" not in table.columns:
|
||||
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
# Ranking writes its shape's columns, so it would drop a column it does not know.
|
||||
known = COLUMNS if MOVES in table.columns else OLD_COLUMNS
|
||||
if unknown := [column for column in table.columns if column not in known]:
|
||||
return unknown_columns(table) or outside_items(lines, table) or table
|
||||
|
||||
|
||||
def unknown_columns(table: Table) -> Failure | None:
|
||||
"""Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none."""
|
||||
known = shape_of(table.columns).columns
|
||||
unknown = [column for column in table.columns if column not in known]
|
||||
if old := [column for column in unknown if column in OLD_SHAPE.columns]:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(old)}, a column of the old shape, which {MOVES} replaced; drop it")
|
||||
if unknown:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(known)}. Rename it, or move this machine to the release that added it")
|
||||
return outside_items(lines, table) or table
|
||||
return None
|
||||
|
||||
|
||||
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
|
||||
items = []
|
||||
for row in table.rows:
|
||||
item = parse_item(row, scoring, table.columns)
|
||||
item = parse_item(row, scoring, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
items.append(item)
|
||||
@@ -365,18 +383,18 @@ def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def readme_goals(readme: str) -> list[tuple[str, str | None]] | Failure:
|
||||
def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""README.md's goals in reading order: each one's number, a sub-goal as 4.1, and its mark, Maintain, Achieve or None."""
|
||||
found = sections(readme).get("Goals", [])
|
||||
if len(found) != 1:
|
||||
return Failure(f"README.md has ## Goals {len(found)} times; it needs it once")
|
||||
goals: list[tuple[str, str | None]] = []
|
||||
goals: list[tuple[str, Mark]] = []
|
||||
path: list[tuple[int, str]] = []
|
||||
for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", found[0].expandtabs(4), re.M):
|
||||
while path and path[-1][0] >= len(indent):
|
||||
path.pop()
|
||||
path.append((len(indent), position))
|
||||
goals.append((".".join(part for _, part in path), mark or None))
|
||||
goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None)))
|
||||
numbers = [number for number, _ in goals]
|
||||
if not goals:
|
||||
return Failure("README.md's ## Goals has no numbered goal")
|
||||
@@ -385,7 +403,7 @@ def readme_goals(readme: str) -> list[tuple[str, str | None]] | Failure:
|
||||
return goals
|
||||
|
||||
|
||||
def achieve_weights(goals: list[tuple[str, str | None]]) -> dict[str, float] | Failure:
|
||||
def achieve_weights(goals: list[tuple[str, Mark]]) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's sum-reciprocal weight: the one ranked k of n in reading order weighs (1/k) / (1 + 1/2 + ... + 1/n)."""
|
||||
if unmarked := [number for number, mark in goals if mark is None]:
|
||||
return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
|
||||
@@ -450,6 +468,7 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
divisor = evaluate(right, values)
|
||||
return evaluate(left, values) / divisor if divisor else math.nan
|
||||
case ast.BinOp(left, ast.Pow(), right):
|
||||
# Caught in place of checking first: a negative base with a fractional exponent, zero to a negative power and an overflow each raise, and three checks would read worse than one catch.
|
||||
try:
|
||||
return math.pow(evaluate(left, values), evaluate(right, values))
|
||||
except (OverflowError, ValueError):
|
||||
@@ -457,12 +476,18 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
return math.nan
|
||||
|
||||
|
||||
def variables(shape: Shape) -> tuple[str, ...]:
|
||||
"""The names the formula may use: the shape's scores but C, which stays out of the formula, and the goal term score builds, W in OLD_SHAPE and V in the current shape."""
|
||||
return tuple(sorted({*shape.score_columns} - {"C"} | {"W" if shape is OLD_SHAPE else "V"}))
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure:
|
||||
if scoring.old_shape:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
|
||||
variables = {**item.scores, "W": max(scoring.weights[goal] for goal in item.goals)}
|
||||
variables = {**item.scores, "W": max(scoring.weights[goal] for goal, _ in item.moves)}
|
||||
else:
|
||||
variables = {**item.scores, "V": sum(scoring.weights[goal] * move for goal, move in zip(item.goals, item.moves))}
|
||||
# Only an OLD_SHAPE item names a goal without a move.
|
||||
variables = {**item.scores, "V": sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves)}
|
||||
value = evaluate(formula, variables)
|
||||
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
|
||||
|
||||
@@ -498,30 +523,26 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
|
||||
return weights
|
||||
|
||||
|
||||
def parse_item(row: str, scoring: Scoring, columns: tuple[str, ...]) -> Item | Failure:
|
||||
item = parse_row(row, columns)
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if scoring.old_shape:
|
||||
if unknown := [goal for goal in item.goals if goal not in scoring.weights]:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
if unknown := [goal for goal, _ in item.moves if goal not in scoring.weights]:
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
|
||||
return item
|
||||
for goal in item.goals:
|
||||
for goal, _ in item.moves:
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if goal not in scoring.weights:
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which vetoes and never scores; name only the achieve goals it moves")
|
||||
if item.goals.count(goal) > 1:
|
||||
return Failure(f"item {item.id} cites goal {goal} twice; name each goal once")
|
||||
return item
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, old_shape: bool) -> str:
|
||||
if old_shape:
|
||||
scores, goals = " | ".join(str(item.scores[name]) for name in "RSCAG"), ", ".join(item.goals)
|
||||
else:
|
||||
scores, goals = " | ".join(str(item.scores[name]) for name in "RSC"), ", ".join(f"{goal} by {move}" for goal, move in zip(item.goals, item.moves))
|
||||
return f"| {item.id} | {release_name(item)} | {', '.join(map(str, item.blocked_by))} | {item.exempt} | {item.tagline} | {scores} | {goals} | {value:.1f} |"
|
||||
def render_item(item: Item, value: float, shape: Shape) -> str:
|
||||
"""The item's row, each cell under its column of shape."""
|
||||
written = {"ID": str(item.id), "Release": release_name(item), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(item.scores[name]) for name in shape.score_columns}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in shape.columns) + " |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
|
||||
@@ -23,7 +23,7 @@ def todo(*rows: str, header: str = HEADER) -> str:
|
||||
|
||||
|
||||
def item(id_: int, scores: dict[str, int]) -> Item:
|
||||
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, ("1",), ())
|
||||
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
|
||||
|
||||
|
||||
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = ()) -> Outcome:
|
||||
|
||||
+18
-7
@@ -108,7 +108,7 @@ class Rank(unittest.TestCase):
|
||||
""", ranked.text)
|
||||
self.assertTrue(ranked.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(ranked.under_bar, [])
|
||||
self.assertFalse(ranked.old_shape)
|
||||
self.assertEqual(ranked.notes, [])
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
def test_weighs_each_achieve_goal_by_its_sum_reciprocal_rank(self):
|
||||
@@ -206,7 +206,7 @@ class OldShape(unittest.TestCase):
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 |
|
||||
""", ranked.text)
|
||||
self.assertTrue(ranked.old_shape)
|
||||
self.assertEqual(ranked.notes, [rank_todo.RESHAPE])
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
unmarked = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n"
|
||||
self.assertEqual(self.ranked(readme=unmarked), ranked)
|
||||
@@ -215,6 +215,9 @@ class OldShape(unittest.TestCase):
|
||||
failure = self.ranked(readme=README.replace(" 1. **Achieve:** Tested.", " 1. **Achieve:** Tested.\n3. Small."))
|
||||
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason)
|
||||
|
||||
def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list"))
|
||||
|
||||
def test_refuses_a_formula_over_v(self):
|
||||
self.assertIsInstance(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure)
|
||||
|
||||
@@ -224,7 +227,13 @@ class OldShape(unittest.TestCase):
|
||||
|
||||
def test_refuses_a_table_with_both_moves_and_goals(self):
|
||||
both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n")
|
||||
self.assertEqual(self.ranked(both), Failure("todo.md's items table has the column A, G, Goals, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, R, S, C, Moves, Score. Rename it, or move this machine to the release that added it"))
|
||||
self.assertEqual(self.ranked(both), Failure("todo.md's items table has the column A, G, Goals, a column of the old shape, which Moves replaced; drop it"))
|
||||
|
||||
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
|
||||
misspelt = TODO.replace("| C | Moves |", "| C | Move |")
|
||||
self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
|
||||
self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
|
||||
|
||||
|
||||
class Blockers(unittest.TestCase):
|
||||
@@ -254,8 +263,8 @@ class Blockers(unittest.TestCase):
|
||||
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
|
||||
ranked = self.ranked(finished)
|
||||
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
|
||||
self.assertEqual(ranked.dropped, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
|
||||
self.assertEqual(self.ranked(ranked.text).dropped, [])
|
||||
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
|
||||
self.assertEqual(self.ranked(ranked.text).notes, [])
|
||||
|
||||
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
|
||||
cases = {
|
||||
@@ -275,6 +284,8 @@ class Blockers(unittest.TestCase):
|
||||
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|")
|
||||
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
|
||||
self.assertEqual(self.ranked(without), self.ranked(TODO))
|
||||
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
|
||||
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
|
||||
|
||||
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_asks_for_c_beside_blocked_by(self):
|
||||
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
@@ -347,7 +358,7 @@ class Main(unittest.TestCase):
|
||||
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
|
||||
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "")
|
||||
self.assertIsInstance(ranked, rank_todo.Ranked)
|
||||
self.assertEqual((ranked.under_bar, ranked.old_shape), ([], False))
|
||||
self.assertEqual((ranked.under_bar, ranked.notes), ([], []))
|
||||
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
|
||||
|
||||
|
||||
@@ -355,4 +366,4 @@ class ThisRepo(unittest.TestCase):
|
||||
def test_todo_md_is_ranked_with_nothing_under_the_bar(self):
|
||||
text = (ROOT / "todo.md").read_text(encoding="utf-8")
|
||||
ranked = rank_todo.rank(text, (ROOT / "README.md").read_text(encoding="utf-8"), (ROOT / "docs" / "decisions.md").read_text(encoding="utf-8"))
|
||||
self.assertEqual(ranked, rank_todo.Ranked(text, [], [], False))
|
||||
self.assertEqual(ranked, rank_todo.Ranked(text, [], []))
|
||||
|
||||
+102
-33
@@ -1,24 +1,72 @@
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# Each of R, S, C, A and G, and each goal's move, runs from 1 to TOP_SCORE.
|
||||
# Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE.
|
||||
TOP_SCORE = 10
|
||||
EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "security")
|
||||
# The column naming the items that block an item: each must be done before the item starts.
|
||||
BLOCKED_BY = "Blocked by"
|
||||
# The column naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`.
|
||||
MOVES = "Moves"
|
||||
# The columns rank_todo writes, in order. A reader takes cells by column name, so it reads a table from before BLOCKED_BY or C joined, or with a column a later release adds.
|
||||
COLUMNS = ("ID", "Release", BLOCKED_BY, "Exempt", "Item", "R", "S", "C", MOVES, "Score")
|
||||
# The columns of a table from before MOVES replaced A, G and Goals, which rank_todo still ranks until its project reshapes it.
|
||||
OLD_COLUMNS = ("ID", "Release", BLOCKED_BY, "Exempt", "Item", "R", "S", "C", "A", "G", "Goals", "Score")
|
||||
# The columns without which no row can be read; a missing BLOCKED_BY reads as blocked by nothing, a missing C as no C.
|
||||
NEEDED = ("ID", "Release", "Exempt", "Item", "R", "S", MOVES)
|
||||
OLD_NEEDED = ("ID", "Release", "Exempt", "Item", "R", "S", "A", "G", "Goals")
|
||||
# How the items table's header opens, which tells it from the goal weights table.
|
||||
# How the items table's header opens, which tells it from any other table in todo.md.
|
||||
HEADER_START = "| ID | Release |"
|
||||
# Each goal an item names, in its order, with how far the item moves it; None in OLD_SHAPE, whose Goals cell names no move.
|
||||
Moves = tuple[tuple[str, int | None], ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Shape:
|
||||
"""A shape of the items table: its columns, and how its goals cell reads and writes."""
|
||||
# The score columns, in the order the table holds them.
|
||||
score_columns: tuple[str, ...]
|
||||
# The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back.
|
||||
goals_column: str
|
||||
read_goals: typing.Callable[[str, str], Moves | Failure]
|
||||
write_goals: typing.Callable[[Moves], str]
|
||||
|
||||
@property
|
||||
def columns(self) -> tuple[str, ...]:
|
||||
"""Every column of the shape, in order. A reader takes cells by column name, so it reads a table from before BLOCKED_BY or C joined, or with a column a later release adds."""
|
||||
return ("ID", "Release", BLOCKED_BY, "Exempt", "Item", *self.score_columns, self.goals_column, "Score")
|
||||
|
||||
@property
|
||||
def needed(self) -> tuple[str, ...]:
|
||||
"""The columns without which no row can be read: a missing BLOCKED_BY reads as blocked by nothing, a missing C as no C, and a missing Score as no score yet."""
|
||||
return tuple(column for column in self.columns if column not in (BLOCKED_BY, "C", "Score"))
|
||||
|
||||
|
||||
def parse_moves(id_: str, cell: str) -> Moves | Failure:
|
||||
"""A Moves cell: empty, or each goal the item moves, named once, and how far."""
|
||||
matches = [re.fullmatch(r"([0-9]+(?:\.[0-9]+)*) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
|
||||
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
|
||||
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
goals = [goal for goal, _ in moves]
|
||||
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
|
||||
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
|
||||
return moves
|
||||
|
||||
|
||||
def write_moves(moves: Moves) -> str:
|
||||
return ", ".join(f"{goal} by {by}" for goal, by in moves)
|
||||
|
||||
|
||||
def parse_cited(id_: str, cell: str) -> Moves:
|
||||
"""An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move."""
|
||||
return tuple((goal.strip(), None) for goal in cell.split(","))
|
||||
|
||||
|
||||
def write_cited(moves: Moves) -> str:
|
||||
return ", ".join(goal for goal, _ in moves)
|
||||
|
||||
|
||||
# The current shape.
|
||||
SHAPE = Shape(("R", "S", "C"), MOVES, parse_moves, write_moves)
|
||||
# The shape from before MOVES replaced A, G and Goals, which older todo.md files hold.
|
||||
OLD_SHAPE = Shape(("R", "S", "C", "A", "G"), "Goals", parse_cited, write_cited)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -28,10 +76,8 @@ class Item:
|
||||
exempt: str
|
||||
tagline: str
|
||||
scores: dict[str, int]
|
||||
goals: tuple[str, ...]
|
||||
moves: Moves
|
||||
blocked_by: tuple[int, ...]
|
||||
# How far the item moves each of goals, in their order; empty in an old-shape table.
|
||||
moves: tuple[int, ...] = ()
|
||||
|
||||
@property
|
||||
def risk_and_complexity(self) -> int:
|
||||
@@ -52,6 +98,12 @@ class Table:
|
||||
return self.header + 2
|
||||
|
||||
|
||||
def shape_of(columns: tuple[str, ...]) -> Shape:
|
||||
"""The items table's shape: OLD_SHAPE where columns hold one only that shape has and no MOVES, else SHAPE, so a misspelt MOVES is named as missing."""
|
||||
old_only = set(OLD_SHAPE.columns) - set(SHAPE.columns)
|
||||
return OLD_SHAPE if MOVES not in columns and old_only.intersection(columns) else SHAPE
|
||||
|
||||
|
||||
def items(todo: str) -> list[Item] | None | Failure:
|
||||
"""Each row of a todo.md's items table; None where todo.md holds no items table."""
|
||||
table = items_table(todo.splitlines())
|
||||
@@ -59,7 +111,7 @@ def items(todo: str) -> list[Item] | None | Failure:
|
||||
return table
|
||||
found = []
|
||||
for row in table.rows:
|
||||
item = parse_row(row, table.columns)
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
found.append(item)
|
||||
@@ -78,8 +130,7 @@ def items_table(lines: list[str]) -> Table | None | Failure:
|
||||
return table
|
||||
if repeated := sorted({column for column in table.columns if table.columns.count(column) > 1}):
|
||||
return Failure(f"todo.md's items table names the column {', '.join(repeated)} twice; keep one")
|
||||
needed = NEEDED if MOVES in table.columns else OLD_NEEDED
|
||||
if missing := [column for column in needed if column not in table.columns]:
|
||||
if missing := [column for column in shape_of(table.columns).needed if column not in table.columns]:
|
||||
return Failure(f"todo.md's items table has no {', '.join(missing)} column; rank_todo.py --help shows a valid one")
|
||||
return table
|
||||
|
||||
@@ -110,12 +161,30 @@ def cells(row: str, count: int) -> list[str] | Failure:
|
||||
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
|
||||
|
||||
|
||||
def parse_row(row: str, columns: tuple[str, ...]) -> Item | Failure:
|
||||
"""An item row under columns, every cell checked but the goals it cites."""
|
||||
found = cells(row, len(columns))
|
||||
def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
"""An item row of table, every cell checked but whether README.md numbers and weighs the goals it names."""
|
||||
found = cells(row, len(table.columns))
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
named = dict(zip(columns, found))
|
||||
named = dict(zip(table.columns, found))
|
||||
if misformed := check_cells(row, named):
|
||||
return misformed
|
||||
shape = shape_of(table.columns)
|
||||
scores = parse_scores(named["ID"], named, shape.score_columns)
|
||||
if isinstance(scores, Failure):
|
||||
return scores
|
||||
blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, ""))
|
||||
if isinstance(blocked_by, Failure):
|
||||
return blocked_by
|
||||
moves = shape.read_goals(named["ID"], named[shape.goals_column])
|
||||
if isinstance(moves, Failure):
|
||||
return moves
|
||||
major, minor, patch = (int(part) for part in named["Release"].split("."))
|
||||
return Item(int(named["ID"]), (major, minor, patch), named["Exempt"], named["Item"], scores, moves, blocked_by)
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Failure | None:
|
||||
"""Holds the row's ID, Release, Exempt and Item cells to the format: why one breaks it, None when none does."""
|
||||
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
|
||||
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
|
||||
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
|
||||
@@ -125,25 +194,25 @@ def parse_row(row: str, columns: tuple[str, ...]) -> Item | Failure:
|
||||
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
|
||||
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
|
||||
return None
|
||||
|
||||
|
||||
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
|
||||
"""Each score of names the row holds; only C may be missing, since the table holds every needed column."""
|
||||
scores: dict[str, int] = {}
|
||||
for name in ("R", "S", "C", "A", "G"):
|
||||
for name in names:
|
||||
if name not in named:
|
||||
continue
|
||||
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= TOP_SCORE:
|
||||
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {TOP_SCORE}")
|
||||
scores[name] = int(named[name])
|
||||
blockers = named.get(BLOCKED_BY, "")
|
||||
if not re.fullmatch(r"([0-9]+(, [0-9]+)*)?", blockers):
|
||||
return Failure(f"item {id_}'s {BLOCKED_BY} {blockers!r} is not empty or IDs separated by \", \"")
|
||||
blocked_by = tuple(int(blocker) for blocker in blockers.split(", ") if blocker)
|
||||
return scores
|
||||
|
||||
|
||||
def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure:
|
||||
if not re.fullmatch(r"([0-9]+(, [0-9]+)*)?", cell):
|
||||
return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"")
|
||||
blocked_by = tuple(int(blocker) for blocker in cell.split(", ") if blocker)
|
||||
if int(id_) in blocked_by:
|
||||
return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
|
||||
major, minor, patch = (int(part) for part in release.split("."))
|
||||
if MOVES not in named:
|
||||
cited = tuple(goal.strip() for goal in named["Goals"].split(","))
|
||||
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited, blocked_by)
|
||||
matches = [re.fullmatch(r"([0-9]+(?:\.[0-9]+)*) by ([0-9]+)", move) for move in named[MOVES].split(", ")] if named[MOVES] else []
|
||||
moves = [(match.group(1), int(match.group(2))) for match in matches if match]
|
||||
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
|
||||
return Failure(f"item {id_}'s {MOVES} {named[MOVES]!r} is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, tuple(goal for goal, _ in moves), blocked_by, tuple(by for _, by in moves))
|
||||
return blocked_by
|
||||
|
||||
Reference in New Issue
Block a user