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:]))
|
||||
Reference in New Issue
Block a user