Files
claude-config/bin/todo_item/main.py
T

206 lines
10 KiB
Python

"""Read and change a project's plan: list its items, show one, file, edit, move or finish one.
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. Every command works on the plan the project's config names, which
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. A plan in a Jira epic is
only read so far: list and show work, and add, edit, move and finish fail. Each command that changes
a todo.md ranks it as rank_todo.py does, and so reads the goals file, docs/decisions.md and the
comprehension history, 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.
list prints `From <plan>, in its order:`, then the table's header and divider and one row per item,
without details: first the earliest release, and within a release the item to take first.
A plan in a Jira epic lists in Jira's backlog order instead.
--release prints one release's items. Where no item fits, it prints `<plan> holds no item.`
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 <plan>.` It doesn't write anything while docs/decisions.md cites the item.
finish <ID> --no-changelog also drops an item no chunk built.
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 release_plan.todo_table import BLOCKED_BY, MOVES
from failure import Failure
from project_config.main import located
from release_plan.release import parsed, Release, version as release_version
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 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:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
args = parser().parse_args(argv)
config = located(str(folder), pathlib.Path.home())
if isinstance(config, Failure):
done: str | Failure = config
else:
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
print(done)
return 0
def parser() -> argparse.ArgumentParser:
parsed_ = argparse.ArgumentParser(prog="todo-item")
commands = parsed_.add_subparsers(dest="command", required=True)
commands.add_parser("list").add_argument("--release", type=version)
commands.add_parser("show").add_argument("id", type=int)
adding = commands.add_parser("add")
adding.add_argument("--release", required=True)
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")
return parsed_
def version(text: str) -> Release:
"""The release a --release value names; a bad argument where it is no semver version."""
release = parsed(text)
if release is None:
raise argparse.ArgumentTypeError(f"{text!r} is not a semver version")
return release
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 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 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 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:
read = plan.read()
if isinstance(read, Failure):
return read
found = [item for item in read.items if args.release is None or item.release == args.release]
if not found:
return f"{plan.label} holds no item{'' if args.release is None else f' for release {release_version(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 Failure(f"not finished: {news.reason}")
if news and args.changelog is None and not args.no_changelog:
return Failure(f"not finished: {changelog.label} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything or no chunk built the item")
# The bullet is checked before the plan changes: where finish refuses the bullet, the plan and the changelog stay 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