Track bin/todo-item and its package

This commit is contained in:
2026-11-09 01:37:52 +01:00
parent c47d65996e
commit 0c5ea295f1
6 changed files with 324 additions and 0 deletions
+3
View File
@@ -89,6 +89,9 @@
!bin/subagent_rung/
!bin/subagent_rung/*.py
!bin/test_*.py
!bin/todo-item
!bin/todo_item/
!bin/todo_item/*.py
!bin/transcript_archive/
!bin/transcript_archive/*.py
!docs/
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from todo_item import main
sys.exit(main.main(sys.argv[1:]))
View File
+82
View File
@@ -0,0 +1,82 @@
"""The text edits behind todo-item: filing an item in todo.md, removing a finished one, and adding a bullet to CHANGELOG.md. Each returns new text; ranking.rank then orders the table and details and writes the derived cells."""
import re
from failure import Failure
from release_plan.ranking import stated
from release_plan.todo_table import cells, DETAILS, items_table, Table
# A line that would end the item's detail, or open another one, inside ## Details.
HEADING = re.compile(r"^#{1,3} ", re.M)
UNRELEASED = "## Unreleased"
def added(todo: str, named: dict[str, str], detail: str) -> tuple[int, str] | Failure:
"""todo with an item filed under Next ID, and that ID; named holds its cells by column name, its Item cell a plain tagline."""
next_id = stated(todo, "Next ID")
if isinstance(next_id, Failure):
return next_id
if not next_id.isdigit():
return Failure(f"Next ID {next_id!r} is not a whole number")
tagline = named["Item"].strip().removeprefix("**").removesuffix("**")
if "\n" in tagline:
return Failure("the tagline holds a line break; keep it on one line")
if HEADING.search(detail):
return Failure("the detail holds a markdown heading, which would split ## Details; drop the #s")
id_ = int(next_id)
lines = re.sub(r"^`Next ID = [0-9]+`$", f"`Next ID = {id_ + 1}`", todo, count=1, flags=re.M).split("\n")
table = held_table(lines)
if isinstance(table, Failure):
return table
row = {**named, "ID": str(id_), "Item": "**" + re.sub(r"(?<!\\)\|", r"\\|", tagline) + "**"}
lines.insert(table.start + len(table.rows), "| " + " | ".join(row.get(column, "") for column in table.columns) + " |")
text = "\n".join(lines)
if not detail.strip():
return id_, text
entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n"
section = DETAILS.search(text)
if section is None:
return id_, text.rstrip("\n") + f"\n\n## Details\n\n{entry}"
return id_, text[:section.start(1)] + f"\n{entry}" + text[section.start(1):]
def finished(todo: str, id_: int) -> str | Failure:
"""todo without item id_'s row and its detail."""
lines = todo.split("\n")
table = held_table(lines)
if isinstance(table, Failure):
return table
for at, row in enumerate(table.rows, table.start):
found = cells(row, len(table.columns))
if isinstance(found, Failure):
return found
if found[0] == str(id_):
del lines[at]
break
else:
return Failure(f"todo.md holds no item {id_}")
text = "\n".join(lines)
section = DETAILS.search(text)
if section is None:
return text
body = re.sub(rf"^### {id_}\. .*?(?=^### |\Z)", "", section.group(1), count=1, flags=re.M | re.S)
return text[:section.start(1)] + body + text[section.end(1):]
def with_bullet(changelog: str, bullet: str) -> str | Failure:
"""changelog with bullet first under ## Unreleased, which goes above the first release where missing; a new changelog where changelog is empty."""
line = "- " + bullet.strip().removeprefix("- ")
if "\n" in line:
return Failure("the changelog bullet holds a line break; keep it on one line")
if not changelog.strip():
return f"# Changelog\n\n{UNRELEASED}\n\n{line}\n"
if section := re.search(rf"^{UNRELEASED}\n+", changelog, re.M):
rest = changelog[section.end():]
return changelog[:section.end()] + line + "\n" + ("" if rest.startswith("- ") or not rest else "\n") + rest
if release := re.search(r"^## ", changelog, re.M):
return changelog[:release.start()] + f"{UNRELEASED}\n\n{line}\n\n" + changelog[release.start():]
return changelog.rstrip("\n") + f"\n\n{UNRELEASED}\n\n{line}\n"
def held_table(lines: list[str]) -> Table | Failure:
table = items_table(lines)
return Failure("todo.md holds no items table; rank_todo.py --help shows one") if table is None else table
+114
View File
@@ -0,0 +1,114 @@
"""File an item in todo.md, or finish one, and rank the file as rank_todo.py does.
usage: todo-item add --release <version> --l <L> --e <E> --i <I> --s <S> [--moves <moves>]
[--blocked-by <IDs>] [--exempt <reason>] <tagline> [<<'EOF' detail EOF]
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
Works on the todo.md in the current folder, and the CHANGELOG.md and docs/decisions.md beside it.
The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L.
add takes Next ID as the item's ID and raises Next ID by one. It writes the row, with the tagline
in bold and each | in it escaped, and the detail it reads from stdin, if any, under ## Details.
It prints `Filed item <ID>.` It writes nothing where ranking fails or scores the item under the bar.
finish removes the item's row and its detail. With --changelog it adds the bullet first under
CHANGELOG.md's ## Unreleased, creating the section, or the file, where missing. Where CHANGELOG.md
exists, finish needs --changelog or --no-changelog, so no bullet is left out by mistake. It prints
`Finished item <ID>.` It writes nothing while docs/decisions.md cites the item.
Exit 2 on bad arguments; exit 1, saying why, where it writes nothing.
"""
import argparse
import pathlib
import sys
import typing
from failure import Failure
from release_plan import ranking
from release_plan.todo_table import BLOCKED_BY, MOVES
from todo_item.edits import added, finished, with_bullet
# Each score flag, as --l or --L, and the column it fills.
LETTERS = ("L", "E", "I", "S")
def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.TextIO = sys.stdin) -> int:
args = parser().parse_args(argv)
done = add(args, folder, stdin) if args.command == "add" else finish(args, folder)
if isinstance(done, Failure):
print(done.reason, file=sys.stderr)
return 1
print(done)
return 0
def parser() -> argparse.ArgumentParser:
parsed = argparse.ArgumentParser(prog="todo-item", description=__doc__.split("\n\n")[0])
commands = parsed.add_subparsers(dest="command", required=True)
adding = commands.add_parser("add")
adding.add_argument("--release", required=True)
for letter in LETTERS:
adding.add_argument(f"--{letter.lower()}", f"--{letter}", dest=letter, required=True)
adding.add_argument("--moves", default="")
adding.add_argument("--blocked-by", default="")
adding.add_argument("--exempt", default="")
adding.add_argument("tagline")
finishing = commands.add_parser("finish")
finishing.add_argument("id", type=int)
bullet = finishing.add_mutually_exclusive_group()
bullet.add_argument("--changelog")
bullet.add_argument("--no-changelog", action="store_true")
return parsed
def add(args: argparse.Namespace, folder: pathlib.Path, stdin: typing.TextIO) -> str | Failure:
todo = folder / "todo.md"
texts = ranking.read_all(todo)
if isinstance(texts, Failure):
return texts
named = {"Release": args.release, BLOCKED_BY: args.blocked_by, "Exempt": args.exempt, "Item": args.tagline, MOVES: args.moves}
filed = added(texts[0], named | {letter: getattr(args, letter) for letter in LETTERS}, "" if stdin.isatty() else stdin.read())
if isinstance(filed, Failure):
return Failure(f"not filed: {filed.reason}")
id_, text = filed
ranked = ranking.rank(text, *texts[1:])
if isinstance(ranked, Failure):
return Failure(f"not filed: {ranked.reason}")
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
return Failure(f"not filed: {under[0]}")
if unwritten := ranking.write(todo, ranked.text):
return unwritten
report(todo, ranked)
return f"Filed item {id_}."
def finish(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure:
todo, changelog = folder / "todo.md", folder / "CHANGELOG.md"
if changelog.exists() and args.changelog is None and not args.no_changelog:
return Failure("CHANGELOG.md exists beside todo.md; pass --changelog <bullet>, or --no-changelog for an item consumers don't notice")
texts = ranking.read_all(todo)
if isinstance(texts, Failure):
return texts
text = finished(texts[0], args.id)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:])
if isinstance(ranked, Failure):
return ranked
news = None
if args.changelog is not None:
news = with_bullet(changelog.read_text(encoding="utf-8") if changelog.exists() else "", args.changelog)
if isinstance(news, Failure):
return news
if unwritten := ranking.write(todo, ranked.text):
return unwritten
if news is not None and (unwritten := ranking.write(changelog, news)):
return Failure(f"{unwritten.reason}; todo.md no longer holds item {args.id}, so add its bullet by hand")
report(todo, ranked)
return f"Finished item {args.id}."
def report(todo: pathlib.Path, ranked: ranking.Ranked) -> None:
"""Print what ranking says beside the ranked file, as rank_todo.py does."""
for line in ranked.notes + ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
+116
View File
@@ -0,0 +1,116 @@
import contextlib
import io
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from release_plan import ranking
from release_plan.test_ranking import DECISIONS, README, TODO
from todo_item import main
ADD = ["add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count the `a | b` runs."]
ROW = "| 6 | 0.1.0 | | | **Count the `a \\| b` runs.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 |"
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- Older news.\n\n## 0.1.0\n\n- First.\n"
class TodoItem(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.folder = pathlib.Path(temp.name)
self.todo = self.folder / "todo.md"
(self.folder / "README.md").write_text(README)
(self.folder / "docs").mkdir()
(self.folder / "docs" / "decisions.md").write_text(DECISIONS)
ranked = ranking.rank(TODO, README, DECISIONS, "")
assert not isinstance(ranked, ranking.Failure)
self.todo.write_text(ranked.text)
def run_main(self, *argv, stdin=""):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
code = main.main(list(argv), self.folder, io.StringIO(stdin))
return code, out.getvalue(), err.getvalue()
def assert_ranked(self):
self.assertEqual(ranking.check_failures(self.todo), [])
class Add(TodoItem):
def test_takes_next_id_bumps_it_and_writes_the_row_and_detail_ranked(self):
self.assertEqual(self.run_main(*ADD, stdin="What the tagline leaves out.\n"), (0, "Filed item 6.\n", ""))
text = self.todo.read_text()
self.assertIn("`Next ID = 7`", text)
self.assertIn(ROW, text)
self.assertIn("### 6. Count the `a | b` runs.\n\nWhat the tagline leaves out.\n", text)
self.assert_ranked()
def test_files_no_detail_from_empty_stdin_and_takes_upper_case_letters_blockers_and_exempt(self):
argv = ["add", "--release", "0.1.0", "--blocked-by", "2", "--exempt", "owner", "--L", "1", "--E", "1", "--I", "1", "--S", "1", "**Count the runs.**"]
self.assertEqual(self.run_main(*argv)[:2], (0, "Filed item 6.\n"))
text = self.todo.read_text()
self.assertIn("| 6 | 0.1.0 | 2 | owner | **Count the runs.** | 1 | 1 | 1 | 1 | 1 | |", text)
self.assertNotIn("### 6.", text)
self.assert_ranked()
def test_creates_details_where_todo_has_none(self):
self.todo.write_text(self.todo.read_text().split("## Details")[0].rstrip("\n") + "\n")
self.assertEqual(self.run_main(*ADD, stdin="Detail.")[0], 0)
self.assertTrue(self.todo.read_text().endswith("## Details\n\n### 6. Count the `a | b` runs.\n\nDetail.\n"))
self.assert_ranked()
def test_writes_nothing_for_an_item_under_the_bar_or_one_ranking_rejects(self):
before = self.todo.read_text()
code, _, err = self.run_main("add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "Count the runs.")
self.assertEqual((code, err), (1, "not filed: item 6 scores 0.0, under the bar 2; delete it, or mark it with a reason the bar does not apply\n"))
code, _, err = self.run_main("add", "--release", "0.1.0", "--l", "9", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count the runs.")
self.assertEqual((code, err), (1, "not filed: item 6's L '9' is not a whole number from 1 to 4\n"))
code, _, err = self.run_main("add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count\nthe runs.")
self.assertEqual((code, err), (1, "not filed: the tagline holds a line break; keep it on one line\n"))
self.assertEqual(self.todo.read_text(), before)
class Finish(TodoItem):
def test_removes_the_row_and_detail_and_adds_the_bullet_first_under_unreleased(self):
(self.folder / "CHANGELOG.md").write_text(CHANGELOG)
self.assertEqual(self.run_main("finish", "3", "--changelog", "Runs are fast."), (0, "Finished item 3.\n", ""))
text = self.todo.read_text()
self.assertNotRegex(text, r"(?m)^\| 3 \|")
self.assertNotIn("### 3.", text)
self.assertIn("### 1. Ship the later thing.\n\nLater detail.\n", text)
self.assert_ranked()
self.assertEqual((self.folder / "CHANGELOG.md").read_text(), "# Changelog\n\n## Unreleased\n\n- Runs are fast.\n- Older news.\n\n## 0.1.0\n\n- First.\n")
def test_creates_unreleased_or_the_changelog_where_missing(self):
(self.folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(self.run_main("finish", "3", "--changelog", "- Runs are fast.")[0], 0)
self.assertEqual((self.folder / "CHANGELOG.md").read_text(), "# Changelog\n\n## Unreleased\n\n- Runs are fast.\n\n## 0.1.0\n\n- First.\n")
(self.folder / "CHANGELOG.md").unlink()
self.assertEqual(self.run_main("finish", "2", "--changelog", "Tests are tight.")[0], 0)
self.assertEqual((self.folder / "CHANGELOG.md").read_text(), "# Changelog\n\n## Unreleased\n\n- Tests are tight.\n")
def test_needs_a_changelog_choice_where_a_changelog_exists(self):
(self.folder / "CHANGELOG.md").write_text(CHANGELOG)
before = self.todo.read_text()
code, _, err = self.run_main("finish", "2")
self.assertEqual((code, err), (1, "CHANGELOG.md exists beside todo.md; pass --changelog <bullet>, or --no-changelog for an item consumers don't notice\n"))
self.assertEqual(self.todo.read_text(), before)
self.assertEqual(self.run_main("finish", "2", "--no-changelog"), (0, "Finished item 2.\n", ""))
self.assertEqual((self.folder / "CHANGELOG.md").read_text(), CHANGELOG)
self.assertNotRegex(self.todo.read_text(), r"(?m)^\| 2 \|")
def test_writes_nothing_for_an_item_a_decision_cites(self):
before = self.todo.read_text()
code, _, err = self.run_main("finish", "5", "--changelog", "Writes moved out.")
self.assertEqual((code, err), (1, 'docs/decisions.md cites "`todo.md` item 5", which todo.md no longer holds; revise that decision to say what holds now\n'))
self.assertEqual(self.todo.read_text(), before)
self.assertFalse((self.folder / "CHANGELOG.md").exists())
def test_fails_on_an_item_the_table_does_not_hold(self):
self.assertEqual(self.run_main("finish", "9", "--no-changelog"), (1, "", "todo.md holds no item 9\n"))
if __name__ == "__main__":
unittest.main()