From bcacdf991a41c56f8a14eff62ba1ca9dce1ad75f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 20:57:00 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20move=20rank?= =?UTF-8?q?=5Ftodo.py's=20command=20line=20out=20of=20release=5Fplan/ranki?= =?UTF-8?q?ng.py=20and=20restore=20the=20blank=20lines=20after=20imports;?= =?UTF-8?q?=20the=20parse=5Fmoves=20docstring=20fix=20comes=20in=20the=20p?= =?UTF-8?q?rose=20round?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/git_cli/test_git_repo.py | 2 + bin/rank_todo.py | 120 +++++++++++++++++++++++++++++- bin/records/test_file_writes.py | 2 + bin/records/test_markdown_text.py | 2 + bin/release_plan/ranking.py | 114 +--------------------------- bin/release_plan/release.py | 1 + bin/release_plan/test_ranking.py | 62 ++------------- bin/rule_hook/git.py | 2 + bin/rule_hook/todo_check.py | 2 + bin/statusline.py | 1 + bin/test_rank_todo.py | 69 +++++++++++++++++ 11 files changed, 204 insertions(+), 173 deletions(-) create mode 100644 bin/test_rank_todo.py diff --git a/bin/git_cli/test_git_repo.py b/bin/git_cli/test_git_repo.py index 0ab95b0c..7921e0a0 100644 --- a/bin/git_cli/test_git_repo.py +++ b/bin/git_cli/test_git_repo.py @@ -9,6 +9,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from git_cli import git_repo + + class Git(unittest.TestCase): # Each command is a shell alias, so it touches no repository, whatever GIT_DIR the test runs under. diff --git a/bin/rank_todo.py b/bin/rank_todo.py index fd6154a2..c6cffadf 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -1,9 +1,123 @@ #!/usr/bin/env python3 +"""Score todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar. + +usage: rank_todo.py [--check] [todo.md] + +Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md and +docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and +sorts the items by release; within a release, question rows come first, then security rows, then +the rest, each group by score from highest, then by ID. Then it moves each blocker, an item +another's Blocked by cell names, that ranks below an item it blocks to just above the first such +item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a +table without them. --check writes nothing and fails when the file is not ranked as it would be. + +A valid todo.md; ## Details and each item's detail are optional: + + # todo + + ## Scoring + + `Score = 100 * V / (2**S + 8)` + + `Bar = 1` + + `Next ID = 2` + + ## Items + + | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | + |---|---|---|---|---|---|---|---|---|---|---|---| + | 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 2 | 1 | 3 | 3 | 1 by 9 | 0 | + + ## Details + + ### 1. Make the first thing work. + + What the tagline cannot say. + +- The formula holds numbers, + - * / ** and parentheses over L, E, I, R, S and V. +- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it. + README.md marks each goal **Maintain:** or **Achieve:**. Code health, the achieve goal every + project shares, ranks first; a Moves cell names it as in `code health by 6`. README.md's achieve + goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one + before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188. + With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring + run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history + holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep + theirs. A line `**Void:** code health, since .` in README.md's ## Goals drops code health, + and an item may not name it. A project must void it where its docs/decisions.md has a + `## review opt-out:` title naming the comprehension check. Only an item marked defect may name a + maintain goal, the one it restores, which weighs as the heaviest achieve goal. +- The bar is judged on the Score as shown, to one decimal. +- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it. +- An item's L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1 + to 3 and I from 1 to 5. + rank_todo.py writes its R, L + E + I - 2, at least 7 when I is 5 and at least 5 when I is 4. Its S + is a whole number from 1 to 10. +- An item's Moves cell is empty, or names each goal it moves and how far, a whole number from 1 to + 10, such as `1.1 by 8, 1.2 by 5`: the most specific goal, and a parent only for a move none of its + sub-goals covers, so never a goal beside its own sub-goal. An empty cell scores V 0. +- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, owner, + principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be + exempt, and a row marked decision must be cited there. +- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details. +- An item's Blocked by cell is empty, or lists IDs such as `12, 14`: each must be done before the + item starts, so no blocker may sit in a later release, and no item may block itself or form a + loop. An ID at or above Next ID fails; one below it that the table no longer holds was finished + or deleted, and is dropped. +- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column. +- The table holds the columns above. One missing L, E or I fails, and so does one with a column this + version does not know, since writing it would drop that column. +- A table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still + ranks, by a formula over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W + being the heaviest cited goal's weight; ranking it says to reshape it. +- ## Renamed is optional: one line `- 0.2.1 renamed to 0.3.0` per renamed release. chunk-preflight, + loop-claude and larv-review skip the line's first release, and ignore the second, which is for the + reader. No item may sit under a marked release, and a line goes once a tag at or past its first + release is cut. A release whose items all moved elsewhere without a line reads as finished. + +Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or +docs/decisions.md that breaks the rules above, a scoring run on docs/comprehension-history.md's +newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring +under the bar, or --check finding the file unranked. +""" import pathlib import sys -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) - +from failure import Failure from release_plan import ranking -sys.exit(ranking.main(sys.argv[1:])) + +def main(argv: list[str]) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + args = parse_args(argv) + if isinstance(args, Failure): + return fail(args) + check, todo = args + if check: + failures = ranking.check_failures(todo) + for line in failures: + print(line, file=sys.stderr) + return 1 if failures else 0 + ranked = ranking.rank_file(todo) + if isinstance(ranked, Failure): + return fail(ranked) + return 1 if ranked.under_bar else 0 + + +def fail(failure: Failure) -> int: + print(failure.reason, file=sys.stderr) + return 1 + + +def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure: + paths = [arg for arg in argv if arg != "--check"] + if len(paths) > 1 or any(path.startswith("-") for path in paths): + return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]") + return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md") + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/bin/records/test_file_writes.py b/bin/records/test_file_writes.py index 864bc0a2..9f87de33 100644 --- a/bin/records/test_file_writes.py +++ b/bin/records/test_file_writes.py @@ -8,6 +8,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from records import file_writes + + class ReplaceFile(unittest.TestCase): def test_removes_what_it_staged_when_the_replace_fails(self): with tempfile.TemporaryDirectory() as root: diff --git a/bin/records/test_markdown_text.py b/bin/records/test_markdown_text.py index 7c7e8507..92de02c5 100644 --- a/bin/records/test_markdown_text.py +++ b/bin/records/test_markdown_text.py @@ -5,6 +5,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from records import markdown_text + + class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" diff --git a/bin/release_plan/ranking.py b/bin/release_plan/ranking.py index 149670a5..9d4b1b41 100644 --- a/bin/release_plan/ranking.py +++ b/bin/release_plan/ranking.py @@ -1,85 +1,4 @@ -"""Score todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar. - -usage: rank_todo.py [--check] [todo.md] - -Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md and -docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and -sorts the items by release; within a release, question rows come first, then security rows, then -the rest, each group by score from highest, then by ID. Then it moves each blocker, an item -another's Blocked by cell names, that ranks below an item it blocks to just above the first such -item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a -table without them. --check writes nothing and fails when the file is not ranked as it would be. - -A valid todo.md; ## Details and each item's detail are optional: - - # todo - - ## Scoring - - `Score = 100 * V / (2**S + 8)` - - `Bar = 1` - - `Next ID = 2` - - ## Items - - | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | - |---|---|---|---|---|---|---|---|---|---|---|---| - | 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 2 | 1 | 3 | 3 | 1 by 9 | 0 | - - ## Details - - ### 1. Make the first thing work. - - What the tagline cannot say. - -- The formula holds numbers, + - * / ** and parentheses over L, E, I, R, S and V. -- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it. - README.md marks each goal **Maintain:** or **Achieve:**. Code health, the achieve goal every - project shares, ranks first; a Moves cell names it as in `code health by 6`. README.md's achieve - goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one - before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188. - With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring - run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history - holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep - theirs. A line `**Void:** code health, since .` in README.md's ## Goals drops code health, - and an item may not name it. A project must void it where its docs/decisions.md has a - `## review opt-out:` title naming the comprehension check. Only an item marked defect may name a - maintain goal, the one it restores, which weighs as the heaviest achieve goal. -- The bar is judged on the Score as shown, to one decimal. -- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it. -- An item's L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1 - to 3 and I from 1 to 5. - rank_todo.py writes its R, L + E + I - 2, at least 7 when I is 5 and at least 5 when I is 4. Its S - is a whole number from 1 to 10. -- An item's Moves cell is empty, or names each goal it moves and how far, a whole number from 1 to - 10, such as `1.1 by 8, 1.2 by 5`: the most specific goal, and a parent only for a move none of its - sub-goals covers, so never a goal beside its own sub-goal. An empty cell scores V 0. -- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, owner, - principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be - exempt, and a row marked decision must be cited there. -- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details. -- An item's Blocked by cell is empty, or lists IDs such as `12, 14`: each must be done before the - item starts, so no blocker may sit in a later release, and no item may block itself or form a - loop. An ID at or above Next ID fails; one below it that the table no longer holds was finished - or deleted, and is dropped. -- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column. -- The table holds the columns above. One missing L, E or I fails, and so does one with a column this - version does not know, since writing it would drop that column. -- A table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still - ranks, by a formula over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W - being the heaviest cited goal's weight; ranking it says to reshape it. -- ## Renamed is optional: one line `- 0.2.1 renamed to 0.3.0` per renamed release. chunk-preflight, - loop-claude and larv-review skip the line's first release, and ignore the second, which is for the - reader. No item may sit under a marked release, and a line goes once a tag at or past its first - release is cut. A release whose items all moved elsewhere without a line reads as finished. - -Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or -docs/decisions.md that breaks the rules above, a scoring run on docs/comprehension-history.md's -newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring -under the bar, or --check finding the file unranked. -""" +"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules.""" import ast import dataclasses import decimal @@ -136,25 +55,6 @@ class Ranked: notes: list[str] -def main(argv: list[str]) -> int: - if argv[:1] in (["-h"], ["--help"]): - print(__doc__.strip()) - return 0 - args = parse_args(argv) - if isinstance(args, Failure): - return fail(args) - check, todo = args - if check: - failures = check_failures(todo) - for line in failures: - print(line, file=sys.stderr) - return 1 if failures else 0 - ranked = rank_file(todo) - if isinstance(ranked, Failure): - return fail(ranked) - return 1 if ranked.under_bar else 0 - - 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) @@ -182,18 +82,6 @@ def check_failures(todo: pathlib.Path) -> list[str]: return unranked + [f"{todo}: {line}" for line in ranked.under_bar] -def fail(failure: Failure) -> int: - print(failure.reason, file=sys.stderr) - return 1 - - -def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure: - paths = [arg for arg in argv if arg != "--check"] - if len(paths) > 1 or any(path.startswith("-") for path in paths): - return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]") - return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md") - - 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 = [] diff --git a/bin/release_plan/release.py b/bin/release_plan/release.py index 92882701..5444a47a 100644 --- a/bin/release_plan/release.py +++ b/bin/release_plan/release.py @@ -3,6 +3,7 @@ import re from failure import Failure from git_cli import git_repo + Release = tuple[int, int, int] VERSION = r"[0-9]+\.[0-9]+\.[0-9]+" # The digits of a dated heading's year, month and day, which DATED and dated_heading_pattern each render. diff --git a/bin/release_plan/test_ranking.py b/bin/release_plan/test_ranking.py index 25e26c5b..7cef6cb2 100644 --- a/bin/release_plan/test_ranking.py +++ b/bin/release_plan/test_ranking.py @@ -12,6 +12,7 @@ from failure import Failure from release_plan import ranking from repo_checks import ROOT from release_plan import todo_table + # Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it. VOID = "**Void:** code health, since a test project has no code to read.\n\n" @@ -121,15 +122,12 @@ class Rank(unittest.TestCase): readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" self.assertEqual({goal: round(weight, 4) for goal, weight in ranking.goal_weights(ranking.readme_goals(readme), None).items()}, {"1": 0.3435, "1.1": 0.3435, "1.2": 0.3332, "2": 0.3232}) - def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053_as_the_help_says(self): + def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053(self): for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)): with self.subTest(count=count): goals = ranking.readme_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1))) weights = list(ranking.goal_weights(goals, None).values()) self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1)) - for figure in (ranking.GOAL_STEP, first, last): - self.assertIn(str(figure), ranking.__doc__) - self.assertIn(f"While it is under {ranking.FLOOR}, or the history holds no scoring run, code health weighs {ranking.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(ranking.__doc__.split())) def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self): readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" @@ -345,7 +343,9 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00")) with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(ranking.main([str(todo)]), 0) + ranked = ranking.rank_file(todo) + self.assertIsInstance(ranked, ranking.Ranked) + self.assertEqual(ranked.under_bar, []) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) @@ -572,58 +572,6 @@ class Renamed(unittest.TestCase): -class Main(unittest.TestCase): - def run_main(self, *argv): - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: - code = ranking.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) - 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(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() - self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n")) - - def test_writes_the_ranked_file_yet_fails_on_an_item_under_the_bar(self): - under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply" - with tempfile.TemporaryDirectory() as temp: - todo = pathlib.Path(temp, "todo.md") - todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`")) - pathlib.Path(temp, "README.md").write_text(README) - pathlib.Path(temp, "docs").mkdir() - pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) - self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: {under}\n")) - self.assertEqual(self.run_main("--check", str(todo)), (1, f"{todo}: {under}\n")) - - def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self): - with tempfile.TemporaryDirectory() as temp: - todo = pathlib.Path(temp, "todo.md") - todo.write_text(OLD_SHAPE) - pathlib.Path(temp, "README.md").write_text(README) - pathlib.Path(temp, "docs").mkdir() - pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) - self.assertEqual(self.run_main(str(todo)), (0, f"{todo}: {ranking.RESHAPE}\n")) - self.assertEqual(self.run_main("--check", str(todo)), (0, "")) - - 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 ranking.__doc__.split("\n") if line.startswith(" ")) - ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "") - self.assertIsInstance(ranked, ranking.Ranked) - 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")) - - 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") diff --git a/bin/rule_hook/git.py b/bin/rule_hook/git.py index a93768e5..f041d2f6 100644 --- a/bin/rule_hook/git.py +++ b/bin/rule_hook/git.py @@ -2,6 +2,8 @@ import pathlib from failure import Failure from git_cli import git_repo + + def guarded_git(directory: str, *args: str) -> str | Failure: """What git printed in directory, stripped, run guarded: the hook runs git in a checkout the call has not yet been allowed to touch.""" ran = git_repo.git(*args, cwd=directory, guarded=True) diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 83b826fa..6bdf5aac 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -5,6 +5,8 @@ from rule_hook.rules import Breach from failure import Failure from rule_hook.git import guarded_git from release_plan import ranking + + def todo_breaches(directory: str) -> list[Breach]: top = guarded_git(directory, "rev-parse", "--show-toplevel") if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file(): diff --git a/bin/statusline.py b/bin/statusline.py index d3c4bfb4..69d28800 100755 --- a/bin/statusline.py +++ b/bin/statusline.py @@ -8,6 +8,7 @@ import sys from failure import Failure from git_cli import git_repo + CYAN = "\033[36m" DIM = "\033[2m" GREEN = "\033[32m" diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py new file mode 100644 index 00000000..e2e53208 --- /dev/null +++ b/bin/test_rank_todo.py @@ -0,0 +1,69 @@ +import contextlib +import io +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from release_plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO +import rank_todo +from release_plan import ranking + + +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) + 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(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() + self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n")) + + def test_writes_the_ranked_file_yet_fails_on_an_item_under_the_bar(self): + under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply" + with tempfile.TemporaryDirectory() as temp: + todo = pathlib.Path(temp, "todo.md") + todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`")) + pathlib.Path(temp, "README.md").write_text(README) + pathlib.Path(temp, "docs").mkdir() + pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) + self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: {under}\n")) + self.assertEqual(self.run_main("--check", str(todo)), (1, f"{todo}: {under}\n")) + + def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self): + with tempfile.TemporaryDirectory() as temp: + todo = pathlib.Path(temp, "todo.md") + todo.write_text(OLD_SHAPE) + pathlib.Path(temp, "README.md").write_text(README) + pathlib.Path(temp, "docs").mkdir() + pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) + self.assertEqual(self.run_main(str(todo)), (0, f"{todo}: {ranking.RESHAPE}\n")) + self.assertEqual(self.run_main("--check", str(todo)), (0, "")) + + 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 = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "") + self.assertIsInstance(ranked, ranking.Ranked) + 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")) + + def test_states_the_goal_weights_the_ranking_computes(self): + for figure in (ranking.GOAL_STEP, 0.212, 0.188, 0.082, 0.053): + self.assertIn(str(figure), rank_todo.__doc__) + self.assertIn(f"While it is under {ranking.FLOOR}, or the history holds no scoring run, code health weighs {ranking.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split()))