Score and rank todo.md in one table by the formula, bar and goal weights it states
This commit is contained in:
Executable
+239
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score and rank todo.md's items by the formula, bar and goal weights it states.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
ITEMS_HEADER = "| ID | Release | Item | R | S | A | G | Goals | Score |"
|
||||
WEIGHTS_HEADER = "| Goal | W |"
|
||||
VARIABLES = ("A", "G", "R", "S", "W")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Item:
|
||||
id: int
|
||||
release: tuple[int, int, int]
|
||||
tagline: str
|
||||
scores: dict[str, int]
|
||||
goals: tuple[str, ...]
|
||||
|
||||
|
||||
class Malformed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
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)
|
||||
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, Malformed) as failure:
|
||||
print(f"{todo}: {getattr(failure, 'strerror', None) or 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)
|
||||
return 1
|
||||
if not check and ranked != text:
|
||||
todo.write_text(ranked, encoding="utf-8")
|
||||
for line in under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if 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."""
|
||||
lines = text.split("\n")
|
||||
formula = parse_formula(stated(text, "Score"))
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
weights = parse_weights(lines, goals)
|
||||
start, end = table_rows(lines, ITEMS_HEADER)
|
||||
items = [parse_item(row, weights) for row in lines[start:end]]
|
||||
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))
|
||||
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]
|
||||
return text, under_bar
|
||||
|
||||
|
||||
def readme_goals(readme: str) -> list[str]:
|
||||
"""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")
|
||||
goals: list[str] = []
|
||||
path: list[tuple[int, str]] = []
|
||||
for indent, number in re.findall(r"^( *)(\d+)\. ", section.group(1), 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 goals
|
||||
|
||||
|
||||
def stated(text: str, name: str) -> str:
|
||||
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 found[0]
|
||||
|
||||
|
||||
def parse_formula(source: str) -> ast.Expression:
|
||||
try:
|
||||
tree = ast.parse(source, mode="eval")
|
||||
except SyntaxError:
|
||||
raise Malformed(f"the formula {source!r} does not parse") from None
|
||||
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")
|
||||
return tree
|
||||
|
||||
|
||||
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
match node:
|
||||
case ast.Expression(body):
|
||||
return evaluate(body, values)
|
||||
case ast.Constant(value) if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
case ast.Name(name):
|
||||
return values[name]
|
||||
case ast.UnaryOp(ast.USub(), operand):
|
||||
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)}")
|
||||
|
||||
|
||||
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)})
|
||||
|
||||
|
||||
def number(text: str, what: str) -> float:
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
raise Malformed(f"{what} {text!r} is not a number") from None
|
||||
|
||||
|
||||
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float]:
|
||||
start, end = table_rows(lines, WEIGHTS_HEADER)
|
||||
weights: dict[str, float] = {}
|
||||
for row in lines[start:end]:
|
||||
goal, weight = cells(row, 2)
|
||||
weights[goal] = number(weight, f"goal {goal}'s 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 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."""
|
||||
if lines.count(header) != 1:
|
||||
raise Malformed(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")
|
||||
end = start
|
||||
while end < len(lines) and lines[end].startswith("|"):
|
||||
end += 1
|
||||
return 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:
|
||||
raise Malformed(f"this row needs {count} cells: {row}")
|
||||
return found
|
||||
|
||||
|
||||
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:
|
||||
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 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:
|
||||
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)
|
||||
|
||||
|
||||
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} |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str:
|
||||
section = re.search(r"^## Details\n(.*?)(?=^## |\Z)", text, re.M | re.S)
|
||||
if section is None:
|
||||
return text
|
||||
body = section.group(1)
|
||||
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 = {}
|
||||
for id_, detail in zip(parts[1::2], parts[2::2]):
|
||||
if int(id_) in details:
|
||||
raise Malformed(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]
|
||||
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():]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,105 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
import rank_todo
|
||||
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"
|
||||
|
||||
TODO = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = -R - S/4 + 2*A + 2*G*W`
|
||||
|
||||
`Bar = 9`
|
||||
|
||||
| Goal | W |
|
||||
|---|---|
|
||||
| 1 | 1.00 |
|
||||
| 2 | 0.67 |
|
||||
| 2.1 | 0.33 |
|
||||
|
||||
## 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 |
|
||||
|
||||
## Details
|
||||
|
||||
### 1. stale heading
|
||||
|
||||
Later detail.
|
||||
|
||||
### 3. Make it fast.
|
||||
|
||||
Fast detail.
|
||||
"""
|
||||
|
||||
|
||||
class Rank(unittest.TestCase):
|
||||
def ranked(self, todo=TODO, readme=README):
|
||||
return rank_todo.rank(todo, rank_todo.readme_goals(readme))
|
||||
|
||||
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 |
|
||||
""", 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.assertEqual(under_bar, [])
|
||||
self.assertEqual(self.ranked(text), (text, []))
|
||||
|
||||
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_reads_goals_and_sub_goals_in_reading_order(self):
|
||||
self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"])
|
||||
|
||||
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))
|
||||
|
||||
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))
|
||||
|
||||
def test_refuses_a_row_or_detail_off_the_format(self):
|
||||
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`": "",
|
||||
}
|
||||
for old, new in broken.items():
|
||||
with self.subTest(new=new), self.assertRaises(rank_todo.Malformed):
|
||||
self.ranked(TODO.replace(old, new))
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
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)
|
||||
self.assertEqual(todo.read_text(), TODO)
|
||||
self.assertEqual(rank_todo.main([str(todo)]), 0)
|
||||
self.assertEqual(rank_todo.main(["--check", str(todo)]), 0)
|
||||
|
||||
|
||||
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, []))
|
||||
+1
-1
@@ -11,5 +11,5 @@ class Types(unittest.TestCase):
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
if shutil.which("uv") is None:
|
||||
self.fail("uv on PATH fetches mypy; see README.md's Test line")
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
Reference in New Issue
Block a user