"""todo.md on disk: read it with the files beside it that ranking reads, rank it, write it back, and print what ranking reports.""" import pathlib import sys from failure import Failure from review_rules.comprehension_history import HISTORY from release_plan.ranking import rank, Ranked from records.file_writes import replace_file def rank_file(todo: pathlib.Path) -> Ranked | Failure: """Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr.""" texts = read_all(todo) if isinstance(texts, Failure): return texts ranked = rank(*texts) if isinstance(ranked, Failure): return ranked if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)): return unwritten print_report(todo, ranked) return ranked def print_report(todo: pathlib.Path, ranked: Ranked) -> None: """Print ranking's notes and under-bar lines on stderr, each prefixed with todo's path.""" for line in ranked.notes + ranked.under_bar: print(f"{todo}: {line}", file=sys.stderr) def check_failures(todo: pathlib.Path) -> list[str]: """Why --check fails on todo, empty when it passes.""" texts = read_all(todo) if isinstance(texts, Failure): return [texts.reason] ranked = rank(*texts) if isinstance(ranked, Failure): return [ranked.reason] unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"] return unranked + [f"{todo}: {line}" for line in ranked.under_bar] def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure: """todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none.""" texts = [] for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)): try: texts.append(path.read_text(encoding="utf-8")) except FileNotFoundError: if missing: return Failure(f"{path}: not found; {missing}") texts.append("") except OSError as failure: return Failure(f"{path}: {failure.strerror}") except UnicodeDecodeError: return Failure(f"{path}: not UTF-8") return texts[0], texts[1], texts[2], texts[3] def write(path: pathlib.Path, text: str) -> Failure | None: unwritten = replace_file(path.resolve(), text.encode("utf-8")) return Failure(f"{path}: {unwritten.reason}") if unwritten else None