Answer the architecture, stability and product-owner rounds: errors as values, security first, defect rows, Next ID, the format in --help

This commit is contained in:
2026-10-02 20:16:01 +02:00
parent c0dba6625c
commit 798dfd781e
7 changed files with 309 additions and 174 deletions
+217 -114
View File
@@ -3,15 +3,50 @@
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 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.
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is
one. Rewrites each item's Score from the formula, sorts the items by release, then security rows,
then score from highest, then ID, and orders the details to match. --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 that is not exempt scores under the `Bar = <number>` it states, judged on the Score as
shown, or --check finds it unranked.
A valid todo.md, every line shown required:
# todo
## Scoring
`Score = -R - S/4 + 2*A + 2*G*W`
`Bar = 9`
`Next ID = 2`
| Goal | W |
|---|---|
| 1 | 1.00 |
## Items
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 8 | 9 | 1 | 0 |
## Details
### 1. Make the first thing work.
What the tagline cannot say.
- The formula holds numbers, + - * / and parentheses over R, S, A, G and W.
- The bar is judged on the Score as shown, to one decimal.
- A new item takes Next ID, and Next ID then counts up; no row may reach it.
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
- An item's R, S, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, question
or security. An item docs/decisions.md cites as "`todo.md` item N" is marked decision.
- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details.
Exit 1, saying why, when a file cannot be read, todo.md breaks the format, an item that is not
exempt scores under the bar, or --check finds the file unranked.
"""
import ast
import dataclasses
@@ -20,10 +55,14 @@ import pathlib
import re
import sys
EXEMPTIONS = ("", "decision", "question", "security")
from loop_claude.failure import Failure
from loop_claude.project.premises import sections
EXEMPTIONS = ("", "decision", "defect", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
WEIGHTS_HEADER = "| Goal | W |"
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
VARIABLES = ("A", "G", "R", "S", "W")
WEIGHTS_HEADER = "| Goal | W |"
@dataclasses.dataclass(frozen=True)
@@ -36,8 +75,10 @@ class Item:
goals: tuple[str, ...]
class Malformed(Exception):
pass
@dataclasses.dataclass(frozen=True)
class Ranked:
text: str
under_bar: list[str]
def main(argv: list[str]) -> int:
@@ -47,87 +88,131 @@ def main(argv: list[str]) -> int:
check = "--check" in argv
paths = [arg for arg in argv if arg != "--check"]
if len(paths) > 1 or any(path.startswith("-") for path in paths):
print(__doc__.strip(), file=sys.stderr)
print(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]", file=sys.stderr)
return 1
todo = pathlib.Path(paths[0] if paths else "todo.md")
try:
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, UnicodeDecodeError, Malformed) as failure:
print(failure if isinstance(failure, OSError) else f"{todo}: {failure}", file=sys.stderr)
decisions = todo.parent / "docs" / "decisions.md"
read_in = [read(todo), read(todo.parent / "README.md"), read(decisions) if decisions.exists() else ""]
unread = next((found for found in read_in if isinstance(found, Failure)), None)
if unread:
print(unread.reason, file=sys.stderr)
return 1
if check and ranked != text:
print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr)
text, readme, cited = (str(found) for found in read_in)
ranked = rank(text, readme, cited)
if isinstance(ranked, Failure):
print(ranked.reason, file=sys.stderr)
return 1
if not check and ranked != text:
todo.write_text(ranked, encoding="utf-8")
for line in under_bar:
if ranked.text != text:
if check:
print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr)
return 1
todo.write_text(ranked.text, encoding="utf-8")
for line in ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return 1 if under_bar else 0
return 1 if ranked.under_bar else 0
def rank(text: str, goals: list[str]) -> tuple[str, list[str]]:
"""Returns todo.md ranked, and a line for each item under the bar."""
def read(path: pathlib.Path) -> str | Failure:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
lines = text.split("\n")
if ITEMS_HEADER not in lines and "## Items" not in lines:
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
goals = readme_goals(readme)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"))
if isinstance(formula, Failure):
return formula
bar = number(stated(text, "Bar"), "the bar")
if isinstance(bar, Failure):
return bar
next_id = number(stated(text, "Next ID"), "Next ID")
if isinstance(next_id, Failure):
return next_id
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, 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 not item.exempt and round(value, 1) < bar]
return text, under_bar
if isinstance(weights, Failure):
return weights
items = parse_items(lines, weights)
if isinstance(items, Failure):
return items
ids = [item.id for item in items]
if ids and max(ids) >= next_id:
return Failure(f"item {max(ids)} is not under Next ID {next_id:g}; raise Next ID past every ID")
marked = {item.id for item in items if item.exempt == "decision"}
if unmarked := sorted(set(cited_items(decisions)) - marked):
return Failure(f"docs/decisions.md cites todo.md item {', '.join(map(str, unmarked))}, which no row marked decision holds")
scored = []
for item in items:
value = score(formula, item, weights)
if isinstance(value, Failure):
return value
scored.append((item, value))
scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id))
start = lines.index(ITEMS_HEADER) + 2
lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored]
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
if isinstance(ranked, Failure):
return ranked
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < bar]
return Ranked(ranked, under_bar)
def readme_goals(readme: str) -> list[str]:
def readme_goals(readme: str) -> list[str] | Failure:
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
section = re.search(r"^## Goals\n(.*?)(?=^## |\Z)", readme, re.M | re.S)
if section is None:
raise Malformed("README.md has no ## Goals")
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[str] = []
path: list[tuple[int, str]] = []
for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", section.group(1).expandtabs(4), re.M):
for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", found[0].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")
return Failure("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 Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
return goals
def stated(text: str, name: str) -> str:
def cited_items(decisions: str) -> list[int]:
return [int(id_) for cited in re.findall(r"`todo\.md` items? (\d+(?:(?:, | and )\d+)*)", decisions) for id_ in re.findall(r"\d+", cited)]
def stated(text: str, name: str) -> str | Failure:
found = re.findall(rf"^`{name} = ([^`]+)`$", text, re.M)
if len(found) != 1:
raise Malformed(f"todo.md states `{name} = ...` {len(found)} times; state it once, on a line of its own under ## Scoring")
return Failure(f"todo.md states `{name} = ...` {len(found)} times; state it once, on a line of its own under ## Scoring")
return found[0]
def parse_formula(source: str) -> ast.Expression:
def parse_formula(source: str | Failure) -> ast.Expression | Failure:
if isinstance(source, Failure):
return source
try:
tree = ast.parse(source, mode="eval")
except SyntaxError:
raise Malformed(f"the formula {source!r} does not parse") from None
return Failure(f"the formula {source!r} does not parse")
for node in ast.walk(tree):
allowed = isinstance(node, (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Add, ast.Sub, ast.Mult, ast.Div, ast.USub, ast.UAdd, ast.Load))
allowed = allowed or (isinstance(node, ast.Constant) and type(node.value) in (int, float))
allowed = allowed or (isinstance(node, ast.Name) and node.id in VARIABLES)
if not allowed:
raise Malformed(f"the formula {source!r} may hold only numbers, {', '.join(VARIABLES)}, + - * / and parentheses")
numeric = isinstance(node, ast.Constant) and type(node.value) in (int, float)
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in VARIABLES)):
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(VARIABLES)}, + - * / and parentheses")
return tree
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
"""Evaluates a tree parse_formula accepted; a division by zero gives nan."""
match node:
case ast.Expression(body):
return evaluate(body, values)
@@ -139,96 +224,114 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
return -evaluate(operand, values)
case ast.UnaryOp(ast.UAdd(), operand):
return evaluate(operand, values)
case ast.BinOp(left, operator, right):
a, b = evaluate(left, values), evaluate(right, values)
match operator:
case ast.Add():
return a + b
case ast.Sub():
return a - b
case ast.Mult():
return a * b
case ast.Div():
return a / b
raise Malformed(f"the formula holds {ast.dump(node)}")
case ast.BinOp(left, ast.Add(), right):
return evaluate(left, values) + evaluate(right, values)
case ast.BinOp(left, ast.Sub(), right):
return evaluate(left, values) - evaluate(right, values)
case ast.BinOp(left, ast.Mult(), right):
return evaluate(left, values) * evaluate(right, values)
case ast.BinOp(left, ast.Div(), right):
divisor = evaluate(right, values)
return evaluate(left, values) / divisor if divisor else math.nan
return math.nan
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float:
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float | Failure:
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
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
value = evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
def number(text: str, what: str) -> float:
def number(text: str | Failure, what: str) -> float | Failure:
if isinstance(text, Failure):
return text
try:
value = float(text)
except ValueError:
value = math.nan
if not math.isfinite(value):
raise Malformed(f"{what} {text!r} is not a finite number")
return value
return value if math.isfinite(value) else Failure(f"{what} {text!r} is not a finite number")
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float]:
start, end = table_rows(lines, WEIGHTS_HEADER)
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure:
rows = table_rows(lines, WEIGHTS_HEADER)
if isinstance(rows, Failure):
return rows
weights: dict[str, float] = {}
for row in lines[start:end]:
goal, weight = cells(row, 2)
weights[goal] = number(weight, f"goal {goal}'s weight")
for row in rows:
found = cells(row, 2)
if isinstance(found, Failure):
return found
weight = number(found[1], f"goal {found[0]}'s weight")
if isinstance(weight, Failure):
return weight
weights[found[0]] = weight
if list(weights) != goals:
default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals))
raise Malformed(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position, (n + 1 - p) / n, they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}")
return Failure(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}")
return weights
def table_rows(lines: list[str], header: str) -> tuple[int, int]:
"""The index range of a table's body rows, below its header and divider."""
def parse_items(lines: list[str], weights: dict[str, float]) -> list[Item] | Failure:
rows = table_rows(lines, ITEMS_HEADER)
if isinstance(rows, Failure):
return rows
after = lines[lines.index(ITEMS_HEADER) + 2 + len(rows):]
if any(line.startswith("|") for line in section_lines(after)):
return Failure("## Items holds a row outside its table; keep the rows together under the header")
items = []
for row in rows:
item = parse_item(row, weights)
if isinstance(item, Failure):
return item
items.append(item)
if len({item.id for item in items}) < len(items):
return Failure("two items share an ID")
return items
def table_rows(lines: list[str], header: str) -> list[str] | Failure:
"""A table's body rows, below its header and divider."""
if lines.count(header) != 1:
raise Malformed(f"todo.md needs the table header {header} once")
return Failure(f"todo.md needs the table header {header} once")
start = lines.index(header) + 2
if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")):
raise Malformed(f"the table under {header} has no |---| divider line")
return Failure(f"the table under {header} has no |---| divider line")
end = start
while end < len(lines) and lines[end].startswith("|"):
end += 1
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]:
def section_lines(lines: list[str]) -> list[str]:
return lines[:next((index for index, line in enumerate(lines) if line.startswith("## ")), len(lines))]
def cells(row: str, count: int) -> list[str] | Failure:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
if len(found) != count:
raise Malformed(f"this row needs {count} cells: {row}")
return found
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
def parse_item(row: str, weights: dict[str, float]) -> Item:
id_, release, exempt, tagline, r, s, a, g, goals, _ = cells(row, 10)
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
found = cells(row, 10)
if isinstance(found, Failure):
return found
id_, release, exempt, tagline, r, s, a, g, goals, _ = found
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")
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
return Failure(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:])}")
return Failure(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}")
return Failure(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 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")
return Failure(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")
return Failure(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), exempt, tagline, scores, cited)
@@ -239,25 +342,25 @@ def render_item(item: Item, value: float) -> str:
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
def rank_details(text: str, items: list[Item]) -> str:
def rank_details(text: str, items: list[Item]) -> str | Failure:
section = re.search(r"^## Details\n(.*?)(?=^## |\Z)", text, re.M | re.S)
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")
return Failure("## 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")
details = {}
return Failure("## Details holds text before its first ### <ID>. heading")
details: dict[int, str] = {}
for id_, detail in zip(parts[1::2], parts[2::2]):
if int(id_) in details:
raise Malformed(f"## Details holds item {id_} twice")
return Failure(f"## Details holds item {id_} twice")
details[int(id_)] = detail.strip("\n")
if unknown := sorted(set(details) - {item.id for item in items}):
raise Malformed(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
headed = [f"### {item.id}. {item.tagline.strip('*')}\n\n{details[item.id]}\n" for item in items if item.id in details]
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
ranked = "\n" + "\n".join(headed) if headed else "\n"
tail = "\n" if section.end() < len(text) else ""
return text[:section.start(1)] + ranked + tail + text[section.end():]
+56 -32
View File
@@ -8,10 +8,13 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import rank_todo
from loop_claude.failure import Failure
from test_python_floor import ROOT
README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n"
DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n"
TODO = """# todo
## Scoring
@@ -20,6 +23,8 @@ TODO = """# todo
`Bar = 9`
`Next ID = 6`
| Goal | W |
|---|---|
| 1 | 1.00 |
@@ -32,8 +37,9 @@ TODO = """# todo
|---|---|---|---|---|---|---|---|---|---|
| 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 |
| 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 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 0 |
## Details
@@ -52,74 +58,92 @@ Kept as written.
class Rank(unittest.TestCase):
def ranked(self, todo=TODO, readme=README):
return rank_todo.rank(todo, rank_todo.readme_goals(readme))
def ranked(self, todo=TODO, readme=README, decisions=DECISIONS):
return rank_todo.rank(todo, readme, decisions)
def test_scores_and_sorts_by_release_then_score_and_orders_the_details_to_match(self):
text, under_bar = self.ranked()
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
ranked = self.ranked()
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 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 5.1 |
| 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, `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, []))
""", 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.assertEqual(self.ranked(ranked.text), ranked)
def test_names_each_item_under_the_bar(self):
_, under_bar = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`"))
self.assertEqual(under_bar, ["item 2 scores 10.3, under the bar 11; rescore it or delete it"])
def test_names_each_item_under_the_bar_that_is_not_exempt(self):
ranked = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`"))
self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, or mark it with a reason the bar does not apply"])
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."))
self.assertEqual(rank_todo.readme_goals(README.replace("2. Correct.", "```\n## Goals\n```\n2. Correct.")), ["1", "2", "2.1"])
self.assertIsInstance(rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct.")), Failure)
def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self):
with self.assertRaises(rank_todo.Malformed) as raised:
self.ranked(readme=README.replace(" 1. Tested.", " 1. Tested.\n3. Small."))
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", str(raised.exception))
failure = self.ranked(readme=README.replace(" 1. Tested.", " 1. 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_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +"):
with self.subTest(formula=formula), self.assertRaises(rank_todo.Malformed):
self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula))
for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)"):
with self.subTest(formula=formula):
self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure)
def test_refuses_a_row_or_detail_off_the_format(self):
def test_refuses_a_file_off_the_format(self):
row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |"
broken = {
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 |",
"| 5 | 0.1.0 | decision |": "| 5 | 0.1.0 | |",
"`Next ID = 6`": "`Next ID = 5`",
"Fast detail.": "```\n## Goals\n```",
"### 3. Make it fast.": "### 5. Make it fast.",
"### 3. Make it fast.": "### 7. Make it fast.",
"`Bar = 9`": "`Bar = nan`",
"-R - S/4 + 2*A + 2*G*W": "R / (S - 2)",
"## Items\n\n| ID | Release | Exempt |": "## Plan\n\n| ID | Release |",
}
for old, new in broken.items():
with self.subTest(new=new), self.assertRaises(rank_todo.Malformed):
self.ranked(TODO.replace(old, new))
with self.subTest(new=new):
self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure)
class Main(unittest.TestCase):
def run_main(self, *argv):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
code = rank_todo.main(list(argv))
return code, said.getvalue()
def test_ranks_the_file_in_place_and_check_writes_nothing(self):
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
todo.write_text(TODO)
pathlib.Path(temp, "README.md").write_text(README)
self.assertEqual(rank_todo.main(["--check", str(todo)]), 1)
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS)
self.assertEqual(self.run_main("--check", str(todo))[0], 1)
self.assertEqual(todo.read_text(), TODO)
self.assertEqual(rank_todo.main([str(todo)]), 0)
self.assertEqual(rank_todo.main(["--check", str(todo)]), 0)
self.assertEqual(self.run_main(str(todo)), (0, ""))
self.assertEqual(self.run_main("--check", str(todo)), (0, ""))
pathlib.Path(temp, "README.md").write_bytes(b"\xff")
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n"))
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())
self.assertIn("README.md: not found", self.run_main(str(todo))[1])
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
self.assertEqual(self.run_main("--help")[0], 0)
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. Work.\n", "")
self.assertIsInstance(ranked, rank_todo.Ranked)
self.assertEqual(ranked.under_bar, [])
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
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")
self.assertEqual(rank_todo.rank(text, rank_todo.readme_goals((ROOT / "README.md").read_text(encoding="utf-8"))), (text, []))
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, []))