Route every read and write of the plan through plan_store and todo-item, which gains list, edit and move
CI / tests (pull_request) Failing after 2m13s

This commit is contained in:
2026-11-14 15:15:25 +01:00
parent a87b6cff98
commit 0ac8cad97f
35 changed files with 1088 additions and 421 deletions
+137 -98
View File
@@ -1,48 +1,67 @@
"""File an item in todo.md or finish one, ranking the file as rank_todo.py does, or show one.
"""Read and change a project's plan: list its items, show one, file, edit, move or finish one.
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]
usage: todo-item list [--release <version>]
todo-item show <ID>
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 edit <ID> [--tagline <tagline>] [--l <L>] [--e <E>] [--i <I>] [--s <S>] [--moves <moves>]
[--blocked-by <IDs>] [--exempt <reason>] [--detail <<'EOF' detail EOF | --clear-detail]
todo-item move <ID> --release <version>
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
Run inside a checkout. All three work on the project's todo.md, and name its path in what they
print. add and finish also use its CHANGELOG.md, and read its docs/decisions.md and its goals file.
Each file sits where the project's config puts it, which `project-config` prints.
Run inside a checkout. Every command works on the plan the project's config names, which
`project-config plan` prints, and names it in what it prints. Read and change the plan only through
these commands: they work the same whatever holds it. Today that is a markdown file, todo.md, and
each command that changes it ranks it as rank_todo.py does, so it also reads the goals file and
docs/decisions.md, each where the config puts 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.
The detail may hold no ## or ### heading.
It prints `Filed item <ID> in <todo.md's path>.` It doesn't write anything where ranking fails or scores the item under the bar.
list prints `From <plan>, in its order:`, then one table row per item, without details: first the
earliest release, and within a release the item to take first. --release prints one release's items.
finish removes the item's row and its detail. With --changelog it adds the bullet first under
show prints `From <plan>:`, then the table's header and divider, item <ID>'s row, and its detail under
`### <ID>. <tagline>`, sub-headings included. It fails, saying so, where the plan holds no item <ID>.
list and show read only the plan, and print no Score: an item's place in list's order says how it ranks.
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
stdin, if any. The detail may hold no ## or ### heading.
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
edit sets the cells whose flag is given and leaves the rest; an empty value, as in --blocked-by "",
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
Text on stdin without --detail, and --detail without text on stdin, are refused, so no detail is
dropped or wiped by mistake. It prints `Edited item <ID> in <plan>.` It doesn't write anything where
ranking fails or scores the item under the bar.
move sets the item's release, as edit sets a cell. It prints `Moved item <ID> to release <version> in <plan>.`
finish removes the item and its detail. With --changelog it adds the bullet first under
CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the
file, where missing. It refuses where that section holds ### subsections: add the bullet by hand.
Where CHANGELOG.md holds text, finish needs --changelog or --no-changelog, so no bullet is left out by
mistake. It prints `Finished item <ID> in <todo.md's path>.` It doesn't write anything while docs/decisions.md cites the item.
mistake. It prints `Finished item <ID> in <plan>.` It doesn't write anything while docs/decisions.md cites the item.
show reads only todo.md. It prints `From <todo.md's path>:`, then the items table's header and divider, item <ID>'s row, and its detail
from its ### heading to the next item's, sub-headings included. It fails, saying so, where todo.md has
no row for <ID>.
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`
or `not finished:` means it didn't write anything.
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`,
`not edited:`, `not moved:` or `not finished:` means it didn't write anything.
"""
import argparse
import pathlib
import sys
import typing
from todo_item.edits import added, finished, shown, with_bullet
from release_plan.todo_table import BLOCKED_BY, MOVES
from failure import Failure
from project_config.main import located
from release_plan import plan_file, ranking
from project_config.settings import ProjectConfig
from record_store.stores import store
from release_plan.release import parsed
from plan_store.stores import store as plan_store, PlanStore, TAGLINE, Written
from record_store.stores import RecordStore, store
from todo_item.table import shown, table
from todo_item.edits import with_bullet
# Each score flag, as --l or --L, and the column it fills.
# Each score flag, as --l or --L, and the field it sets.
LETTERS = ("L", "E", "I", "S")
# Each other flag of add and edit that sets a field, by its name on the parsed arguments.
NAMED = {"release": "Release", "blocked_by": BLOCKED_BY, "exempt": "Exempt", "tagline": TAGLINE, "moves": MOVES}
def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.TextIO = sys.stdin) -> int:
@@ -53,10 +72,21 @@ def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.T
config = located(str(folder), pathlib.Path.home())
if isinstance(config, Failure):
done: str | Failure = config
elif args.command == "show":
done = show(args, config.paths["plan"])
else:
done = add(args, config, stdin) if args.command == "add" else finish(args, config)
plan = plan_store(config)
match args.command:
case "list":
done = list_(args, plan)
case "show":
done = show(args, plan)
case "add":
done = reported(plan.add(fields(args), piped(stdin)), "not filed", lambda written: f"Filed item {written.id} in {plan.label}.")
case "edit":
done = edit(args, plan, piped(stdin))
case "move":
done = reported(plan.edit(args.id, {"Release": args.release}, None), "not moved", lambda written: f"Moved item {written.id} to release {args.release} in {plan.label}.")
case _:
done = finish(args, plan, store(config, "changelog"))
if isinstance(done, Failure):
print(done.reason, file=sys.stderr)
return 1
@@ -65,93 +95,102 @@ def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.T
def parser() -> argparse.ArgumentParser:
parsed = argparse.ArgumentParser(prog="todo-item")
commands = parsed.add_subparsers(dest="command", required=True)
parsed_ = argparse.ArgumentParser(prog="todo-item")
commands = parsed_.add_subparsers(dest="command", required=True)
commands.add_parser("list").add_argument("--release")
commands.add_parser("show").add_argument("id", type=int)
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="")
cell_flags(adding, required=True)
adding.add_argument("tagline")
editing = commands.add_parser("edit")
editing.add_argument("id", type=int)
editing.add_argument("--tagline")
cell_flags(editing, required=False)
detail = editing.add_mutually_exclusive_group()
detail.add_argument("--detail", action="store_true")
detail.add_argument("--clear-detail", action="store_true")
moving = commands.add_parser("move")
moving.add_argument("id", type=int)
moving.add_argument("--release", required=True)
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")
showing = commands.add_parser("show")
showing.add_argument("id", type=int)
return parsed
return parsed_
def show(args: argparse.Namespace, todo: pathlib.Path) -> str | Failure:
try:
found = shown(todo.read_text(encoding="utf-8"), args.id)
return found if isinstance(found, Failure) else f"From {todo}:\n\n{found}"
except OSError as failure:
return Failure(f"{todo}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{todo}: not UTF-8")
def cell_flags(command: argparse.ArgumentParser, required: bool) -> None:
"""The flags add and edit share. add needs each score; a flag edit is not given stays None, so its cell stays as it is."""
for letter in LETTERS:
command.add_argument(f"--{letter.lower()}", f"--{letter}", dest=letter, required=required)
for flag in ("--moves", "--blocked-by", "--exempt"):
command.add_argument(flag)
def add(args: argparse.Namespace, config: ProjectConfig, stdin: typing.TextIO) -> str | Failure:
todo = config.paths["plan"]
texts = plan_file.read_all(todo, config)
if isinstance(texts, Failure):
return texts
named = {"Release": args.release, BLOCKED_BY: args.blocked_by, "Exempt": args.exempt, "Item": args.tagline, MOVES: args.moves}
# Claude Code's Bash tool gives a command /dev/null as stdin (readlink /proc/self/fd/0 shows it), so without a heredoc read() returns "" at once.
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 := plan_file.write(todo, ranked.text):
return unwritten
for line in plan_file.report_lines(todo, ranked):
print(line, file=sys.stderr)
return f"Filed item {id_} in {todo}."
def fields(args: argparse.Namespace) -> dict[str, str]:
"""Each field a flag of args gives."""
given = {field: getattr(args, name, None) for name, field in (NAMED | {letter: letter for letter in LETTERS}).items()}
return {field: value for field, value in given.items() if value is not None}
def finish(args: argparse.Namespace, config: ProjectConfig) -> str | Failure:
todo, changelog = config.paths["plan"], store(config, "changelog")
texts = finish_texts(args, config)
if isinstance(texts, Failure):
return Failure(f"not finished: {texts.reason}")
ranked, news = texts
if unwritten := plan_file.write(todo, ranked.text):
return Failure(f"not finished: {unwritten.reason}")
if news is not None and (unwritten := changelog.write(news)):
return Failure(f"{unwritten.reason}; todo.md no longer holds item {args.id}, so add its bullet by hand")
for line in plan_file.report_lines(todo, ranked):
print(line, file=sys.stderr)
return f"Finished item {args.id} in {todo}."
def piped(stdin: typing.TextIO) -> str:
"""The text piped in, empty from a terminal. Claude Code's Bash tool gives a command /dev/null as stdin (readlink /proc/self/fd/0 shows it), so without a heredoc read() returns "" at once."""
return "" if stdin.isatty() else stdin.read()
def finish_texts(args: argparse.Namespace, config: ProjectConfig) -> tuple[ranking.Ranked, str | None] | Failure:
"""What finish writes: the plan ranked without item args.id, and the changelog's new text, None where finish leaves it as is."""
todo, changelog = config.paths["plan"], store(config, "changelog")
def reported(written: Written | Failure, refusal: str, done: typing.Callable[[Written], str]) -> str | Failure:
"""What a write prints: done's line, after the backend's notes on stderr; else the Failure, opened with refusal."""
if isinstance(written, Failure):
return Failure(f"{refusal}: {written.reason}")
for note in written.notes:
print(note, file=sys.stderr)
return done(written)
def list_(args: argparse.Namespace, plan: PlanStore) -> str | Failure:
if args.release is not None and parsed(args.release) is None:
return Failure(f"--release {args.release!r} is not a semver version")
read = plan.read()
if isinstance(read, Failure):
return read
found = [item for item in read.items if args.release is None or item.release == parsed(args.release)]
if not found:
return f"{plan.label} holds no item{'' if args.release is None else f' for release {args.release}'}."
return f"From {plan.label}, in its order:\n\n{table(found)}"
def show(args: argparse.Namespace, plan: PlanStore) -> str | Failure:
read = plan.read()
if isinstance(read, Failure):
return read
found = next((item for item in read.items if item.id == args.id), None)
return Failure(f"{plan.label} holds no item {args.id}") if found is None else f"From {plan.label}:\n\n{shown(found)}"
def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure:
if args.detail and not text.strip():
return Failure("not edited: --detail got no text on stdin; pass the new detail in a heredoc, or --clear-detail to remove the detail")
if text.strip() and not args.detail:
return Failure(f"not edited: stdin holds text; pass --detail to replace item {args.id}'s detail with it")
detail = text if args.detail else "" if args.clear_detail else None
if not fields(args) and detail is None:
return Failure("not edited: no flag names a change; todo-item --help lists them")
return reported(plan.edit(args.id, fields(args), detail), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> str | Failure:
news = changelog.read()
if isinstance(news, Failure):
return news
return Failure(f"not finished: {news.reason}")
if news and args.changelog is None and not args.no_changelog:
return Failure(f"{changelog.label} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything")
texts = plan_file.read_all(todo, config)
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
if args.changelog is None:
return ranked, None
added = with_bullet(news, args.changelog)
return added if isinstance(added, Failure) else (ranked, added)
return Failure(f"not finished: {changelog.label} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything")
# The bullet is checked before the plan changes, so a bullet finish refuses leaves both as they were.
added = None if args.changelog is None else with_bullet(news, args.changelog)
if isinstance(added, Failure):
return Failure(f"not finished: {added.reason}")
done = reported(plan.finish(args.id), "not finished", lambda written: f"Finished item {written.id} in {plan.label}.")
if not isinstance(done, Failure) and added is not None and (unwritten := changelog.write(added)):
return Failure(f"{unwritten.reason}; the plan no longer holds item {args.id}, so add its bullet by hand")
return done