236 lines
13 KiB
Python
236 lines
13 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]
|
|
[--comment <why>]
|
|
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. 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.
|
|
In a Jira epic, add files a Task under the epic, and <ID> is the new issue's number. The release
|
|
must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there, and --exempt
|
|
security also labels the issue `security`. The item scores by the config's `jira-score-formula`, and
|
|
add refuses it under `jira-score-bar` unless it is exempt. add then asks Jira to rank the new issue
|
|
just before the first issue the loop filed that ranks after it: a question before any other, then a
|
|
security finding, then the higher score. Where none does, it stays last. A person's issues don't
|
|
count, and keep their rank. Where Jira files the issue and then refuses a --blocked-by link or the
|
|
rank, add still prints `Filed item <ID> …`, and says on stderr what to do in Jira.
|
|
|
|
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.
|
|
In a Jira epic, edit changes an issue the loop filed: its summary, description and scores, and
|
|
the label `security` with --exempt. It doesn't change a link, so --blocked-by fails.
|
|
Of an issue a person filed it sets only the scores, --moves and --exempt, and only with --comment.
|
|
The four scores are set together where the issue holds none yet.
|
|
--comment is posted as a comment on the Jira issue, for the client's team, in the project's
|
|
language. Jira doesn't show the team the scores, so say that the issue is scored, and why.
|
|
A todo.md keeps no comment, so there the flag doesn't do anything.
|
|
Where Jira takes the edit and then refuses the comment, edit still prints `Edited item <ID> …`,
|
|
and says on stderr to post the comment in Jira.
|
|
|
|
move sets the item's release, as edit sets a cell. It prints `Moved item <ID> to release <version> in <plan>.`
|
|
In a Jira epic, move sets the Fix Version of an issue the loop filed; a person moves their own.
|
|
|
|
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.
|
|
In a Jira epic, finish doesn't remove anything: it moves the item's issue by the transition, and to
|
|
the status, that the config's `jira-finish-transition` and `jira-finish-status` name, as
|
|
`project-config --help` shows. The --changelog rules hold there too, and docs/decisions.md isn't checked.
|
|
It fails, moving no issue, where the config sets neither, where the issue has no such transition
|
|
from its present status, or where the transition leads to another status or to one Jira doesn't
|
|
count as done. An issue that no chunk built is dropped in Jira, not with finish, which would mark it done.
|
|
|
|
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. The one exception is an add,
|
|
an edit, a move or a finish in a Jira epic that Jira didn't answer or answered brokenly: the message then
|
|
says the issue may exist, may have changed or may have moved.
|
|
"""
|
|
import argparse
|
|
import pathlib
|
|
import sys
|
|
import typing
|
|
|
|
from plan.todo_table import BLOCKED_BY, MOVES
|
|
from failure import Failure
|
|
from project_config.main import located
|
|
from plan_store.plans import no_item, PlanStore, TAGLINE, Written
|
|
from plan.release import parsed, Release, version as release_version
|
|
from plan_store.stores import store as plan_store
|
|
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")
|
|
editing.add_argument("--comment")
|
|
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(no_item(plan.label, 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, args.comment), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
|
|
|
|
|
def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> str | Failure:
|
|
held = changelog.held()
|
|
if isinstance(held, Failure):
|
|
return Failure(f"not finished: {held.reason}")
|
|
news = held.text
|
|
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}.")
|
|
written = changelog.write(added, held.version) if not isinstance(done, Failure) and added is not None else None
|
|
if isinstance(written, Failure):
|
|
return Failure(f"{written.reason}; the plan no longer holds item {args.id}, so add its bullet by hand")
|
|
return done
|