kanban_boards.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """``hermes kanban boards …`` — board directories, the ``current`` pointer and ``board.json``.
  2. Filesystem-only, so every action works before ``kanban init`` and must ignore the shared
  3. ``--board`` task-routing override.
  4. """
  5. from __future__ import annotations
  6. import argparse
  7. from typing import Optional
  8. from hermes_cli import kanban_db as kb
  9. from hermes_cli import kanban_db_connect as kbc
  10. from hermes_cli.kanban_output import _err, _fmt_counts, _json_out
  11. def _dispatch_boards(args: argparse.Namespace) -> int:
  12. """``hermes kanban boards <action>`` — filesystem-only, so it works before ``kanban init``."""
  13. sub = getattr(args, "boards_action", None) or "list"
  14. handler = _BOARD_HANDLERS.get(sub)
  15. if handler is None:
  16. return _err(f"kanban boards: unknown action {sub!r}", 2)
  17. return handler(args)
  18. def _board_task_counts(slug: str) -> dict[str, int]:
  19. """``{status: count}`` for a board. Safe to call on an empty DB."""
  20. try:
  21. if not kb.kanban_db_path(board=slug).exists():
  22. return {}
  23. with kbc.connect_closing(board=slug) as conn:
  24. rows = conn.execute("SELECT status, COUNT(*) AS n FROM tasks GROUP BY status").fetchall()
  25. return {r["status"]: int(r["n"]) for r in rows}
  26. except Exception:
  27. return {}
  28. def _board_slug_arg(args: argparse.Namespace, cmd: str, *, must_exist: bool) -> tuple[Optional[str], int]:
  29. """Normalize ``args.slug`` for a ``boards`` subcommand; ``(slug, 0)`` or ``(None, rc)``."""
  30. try:
  31. normed = kb._normalize_board_slug(args.slug)
  32. except ValueError as exc:
  33. return None, _err(f"kanban boards {cmd}: {exc}", 2)
  34. if must_exist:
  35. if not normed or not kb.board_exists(normed):
  36. return None, _err(f"kanban boards {cmd}: board {args.slug!r} does not exist")
  37. elif not normed:
  38. return None, _err(f"kanban boards {cmd}: slug is required", 2)
  39. return normed, 0
  40. def _cmd_boards_list(args: argparse.Namespace) -> int:
  41. boards = kb.list_boards(include_archived=bool(getattr(args, "all", False)))
  42. current = kb.get_current_board()
  43. for b in boards:
  44. b["is_current"] = (b["slug"] == current)
  45. b["counts"] = _board_task_counts(b["slug"])
  46. b["total"] = sum(b["counts"].values())
  47. if _json_out(args, boards):
  48. return 0
  49. if not boards:
  50. print("(no boards — create one with `hermes kanban boards create <slug>`)")
  51. return 0
  52. print(f"{'':2s} {'SLUG':24s} {'NAME':28s} COUNTS")
  53. for b in boards:
  54. marker = "●" if b["is_current"] else " "
  55. name = (b.get("name") or "") + (" [archived]" if b.get("archived") else "")
  56. print(f"{marker:2s} {b['slug']:24s} {name:28s} {_fmt_counts(b['counts'] or {}, '(empty)')}")
  57. print(f"\nCurrent board: {current}")
  58. if len(boards) > 1:
  59. print("Switch boards with `hermes kanban boards switch <slug>`.")
  60. return 0
  61. def _cmd_boards_create(args: argparse.Namespace) -> int:
  62. normed, rc = _board_slug_arg(args, "create", must_exist=False)
  63. if rc:
  64. return rc
  65. already = kb.board_exists(normed) and normed != kb.DEFAULT_BOARD
  66. meta = kb.create_board(
  67. normed, name=args.name, description=args.description, icon=args.icon, color=args.color,
  68. default_workdir=args.default_workdir,
  69. )
  70. print(f"Board {meta['slug']!r} {'already exists' if already else 'created'}.\n"
  71. f" Display name: {meta.get('name', '')}\n"
  72. f" DB path: {meta['db_path']}")
  73. if getattr(args, "switch", False):
  74. kb.set_current_board(meta["slug"])
  75. print(f" Switched to {meta['slug']!r}.")
  76. else:
  77. print(f" Use `hermes kanban boards switch {meta['slug']}` to make it current.")
  78. return 0
  79. def _cmd_boards_rm(args: argparse.Namespace) -> int:
  80. # `boards delete <slug>` (alias) never sets args.delete because --delete belongs to the 'rm'
  81. # subparser only; treat the alias as `rm --delete`.
  82. # See #23139.
  83. force_delete = getattr(args, "delete", False) or getattr(args, "boards_action", "") == "delete"
  84. try:
  85. res = kb.remove_board(args.slug, archive=not force_delete)
  86. except ValueError as exc:
  87. return _err(f"kanban boards rm: {exc}")
  88. if res["action"] == "archived":
  89. print(f"Board {res['slug']!r} archived → {res['new_path']}\n"
  90. "Recover by moving the directory back to <root>/kanban/boards/<slug>/ "
  91. "and deleting the archived tombstone board.json left in its place.")
  92. else:
  93. print(f"Board {res['slug']!r} deleted.")
  94. return 0
  95. def _cmd_boards_switch(args: argparse.Namespace) -> int:
  96. normed, rc = _board_slug_arg(args, "switch", must_exist=False)
  97. if rc:
  98. return rc
  99. if not kb.board_exists(normed):
  100. return _err(
  101. f"kanban boards switch: board {normed!r} does not exist. "
  102. f"Create it with `hermes kanban boards create {normed}`."
  103. )
  104. # An archived board has a tombstone board.json; switching to it would pin
  105. # `current` at a dead slug (#43243).
  106. if kb.read_board_metadata(normed).get("archived"):
  107. return _err(f"kanban boards switch: board {normed!r} is archived.")
  108. kb.set_current_board(normed)
  109. print(f"Active board is now {normed!r}.")
  110. return 0
  111. def _cmd_boards_show(args: argparse.Namespace) -> int:
  112. current = kb.get_current_board()
  113. meta = kb.read_board_metadata(current)
  114. counts = _board_task_counts(current)
  115. print(f"Current board: {current}\n Display name: {meta.get('name', '')}")
  116. if meta.get("description"):
  117. print(f" Description: {meta['description']}")
  118. print(f" DB path: {meta['db_path']}\n"
  119. f" Tasks: {sum(counts.values())} total" + (f" ({_fmt_counts(counts)})" if counts else ""))
  120. return 0
  121. def _cmd_boards_rename(args: argparse.Namespace) -> int:
  122. normed, rc = _board_slug_arg(args, "rename", must_exist=True)
  123. if rc:
  124. return rc
  125. meta = kb.write_board_metadata(normed, name=args.name)
  126. print(f"Board {normed!r} renamed to {meta['name']!r}.")
  127. return 0
  128. def _cmd_boards_set_default_workdir(args: argparse.Namespace) -> int:
  129. normed, rc = _board_slug_arg(args, "set-default-workdir", must_exist=True)
  130. if rc:
  131. return rc
  132. new_val = kb.write_board_metadata(normed, default_workdir=args.path).get("default_workdir")
  133. if new_val:
  134. print(f"Board {normed!r} default workdir set to {new_val!r}.")
  135. else:
  136. print(f"Board {normed!r} default workdir cleared.")
  137. return 0
  138. def _cmd_boards_export(args: argparse.Namespace) -> int:
  139. from hermes_cli import kanban_transfer
  140. from hermes_cli.sizefmt import format_bytes
  141. slug = args.slug or kb.get_current_board()
  142. output = args.output or f"{slug}.tar.gz"
  143. try:
  144. res = kanban_transfer.export_board(
  145. slug, output, include_attachments=not args.no_attachments, include_logs=args.include_logs,
  146. )
  147. except (OSError, ValueError) as exc:
  148. return _err(f"kanban boards export: {exc}")
  149. if _json_out(args, res):
  150. return 0
  151. counts = res["counts"]
  152. print(f"Exported board {res['board']!r} → {res['archive']}\n"
  153. f" Size: {format_bytes(res['size'])}\n"
  154. f" Tasks: {counts['tasks']}\n"
  155. f" Comments: {counts['task_comments']}\n"
  156. f" Attachments: {counts['attachment_files']}\n"
  157. "Import it with `hermes kanban boards import <archive>`.")
  158. return 0
  159. def _cmd_boards_import(args: argparse.Namespace) -> int:
  160. from hermes_cli import kanban_transfer
  161. try:
  162. res = kanban_transfer.import_board(args.archive, args.as_slug, activate=args.switch)
  163. except (OSError, ValueError) as exc:
  164. return _err(f"kanban boards import: {exc}")
  165. if _json_out(args, res):
  166. return 0
  167. print(f"Imported board {res['board']!r} ({res['name']}).")
  168. if res["renamed"]:
  169. print(f" Renamed from {res['requested_board']!r} — that slug was taken.")
  170. print(f" Path: {res['path']}\n Tasks: {res['counts']['tasks']}")
  171. for warning in res["warnings"]:
  172. print(f" Note: {warning}")
  173. if res["activated"]:
  174. print(f" Active board is now {res['board']!r}.")
  175. else:
  176. print(f" Switch to it with `hermes kanban boards switch {res['board']}`.")
  177. return 0
  178. _BOARD_HANDLERS = {
  179. "list": _cmd_boards_list, "ls": _cmd_boards_list,
  180. "create": _cmd_boards_create, "new": _cmd_boards_create,
  181. "rm": _cmd_boards_rm, "remove": _cmd_boards_rm, "delete": _cmd_boards_rm,
  182. "switch": _cmd_boards_switch, "use": _cmd_boards_switch,
  183. "show": _cmd_boards_show, "current": _cmd_boards_show,
  184. "rename": _cmd_boards_rename,
  185. "set-default-workdir": _cmd_boards_set_default_workdir,
  186. "export": _cmd_boards_export,
  187. "import": _cmd_boards_import,
  188. }