GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — python-ticket/ticket.py at master · sjaandi-project/python-ticket Expand file tree/ Copy pathticket.pyMore file actions executable file ·1178 lines (969 loc) · 37.7 KB / Copy pathticket.pyFile metadata and controlsexecutable file ·1178 lines (969 loc) · 37.7 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #!/usr/bin/env python3 # Portions adapted from ticket (https://github.com/wedow/ticket) # Copyright (c) Greg Wedow and ticket contributors # Licensed under MIT # Local changes: full Python rewrite with tree and recent commands. # # This file is part of the ticket Project. # License: MIT. Contact: [email protected] # from __future__ import annotations import argparse import os import re import secrets import shlex import string import subprocess # nosec B404 import sys from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path TK_VERSION = "0.7.1" TK_PART_NUMBER = "SJ-ACC-0001-20260912" VALID_STATUSES = ("open", "in_progress", "closed") VALID_TYPES = ("bug", "feature", "task", "epic", "chore") TYPE_MARKERS: dict[str, str] = { "epic": "(E)", "bug": "(B)", "feature": "(F)", "chore": "(C)", } @dataclass class Ticket: id: str = "" status: str = "open" deps: list[str] = field(default_factory=list) links: list[str] = field(default_factory=list) created: str = "" type: str = "task" priority: int = 2 assignee: str = "" external_ref: str = "" parent: str = "" repo: str = "" tags: list[str] = field(default_factory=list) title: str = "" path: Path | None = None # --------------------------------------------------------------------------- # Frontmatter parsing # --------------------------------------------------------------------------- def _parse_list(raw: str) -> list[str]: """Parse a bracket list like '[a, b, c]' into a list of strings.""" raw = raw.strip() if raw in ("[]", ""): return [] raw = raw.strip("[]") return [item.strip() for item in raw.split(",") if item.strip()] def load_ticket(path: Path) -> Ticket: """Load a ticket from a markdown file with YAML frontmatter.""" text = path.read_text(encoding="utf-8") lines = text.split("\n") boundaries = [i for i, line in enumerate(lines) if line.strip() == "---"] if len(boundaries) < 2: return Ticket(path=path) fields: dict[str, str] = {} for line in lines[boundaries[0] + 1 : boundaries[1]]: if ":" in line: key, _, value = line.partition(":") fields[key.strip()] = value.strip() title = "" for line in lines[boundaries[1] + 1 :]: if line.startswith("# "): title = line[2:].strip() break priority_raw = fields.get("priority", "2") try: priority = int(priority_raw) except ValueError: priority = 2 return Ticket( id=fields.get("id", ""), status=fields.get("status", "open"), deps=_parse_list(fields.get("deps", "[]")), links=_parse_list(fields.get("links", "[]")), created=fields.get("created", ""), type=fields.get("type", "task"), priority=priority, assignee=fields.get("assignee", ""), external_ref=fields.get("external-ref", ""), parent=fields.get("parent", ""), repo=fields.get("repo", ""), tags=_parse_list(fields.get("tags", "[]")), title=title, path=path, ) def load_all(tickets_dir: Path) -> list[Ticket]: """Load all tickets from a directory, following symlinks.""" tickets = [] seen_inodes: set[tuple[int, int]] = set() for dirpath, dirnames, filenames in os.walk(tickets_dir, followlinks=True): dp = Path(dirpath) rel = dp.relative_to(tickets_dir) if any(part.startswith(".") for part in rel.parts): dirnames.clear() continue # Guard against symlink loops st = dp.stat() inode_key = (st.st_dev, st.st_ino) if inode_key in seen_inodes: dirnames.clear() continue seen_inodes.add(inode_key) for fn in sorted(filenames): if fn.endswith(".md"): tickets.append(load_ticket(dp / fn)) return tickets def save_field(path: Path, field_name: str, value: str) -> None: """Update one YAML field in a ticket file, preserving the rest.""" text = path.read_text(encoding="utf-8") lines = text.split("\n") boundaries = [i for i, line in enumerate(lines) if line.strip() == "---"] if len(boundaries) < 2: return found = False for i in range(boundaries[0] + 1, boundaries[1]): if lines[i].startswith(f"{field_name}:"): lines[i] = f"{field_name}: {value}" found = True break if not found: lines.insert(boundaries[0] + 1, f"{field_name}: {value}") path.write_text("\n".join(lines), encoding="utf-8") # --------------------------------------------------------------------------- # Ticket discovery and ID generation # --------------------------------------------------------------------------- def find_tickets_dir(start: Path | None = None) -> Path | None: """Walk parent directories to find .tickets/. Returns None if not found.""" env_dir = os.environ.get("TICKETS_DIR") if env_dir: # abspath, not resolve: the prefix comes from the symlink's folder, as in the walk below. return Path(os.path.abspath(env_dir)) current = start or Path.cwd() while True: candidate = current / ".tickets" if candidate.is_dir(): return candidate parent = current.parent if parent == current: break current = parent return None def generate_id(tickets_dir: Path) -> str: """Generate a ticket ID with prefix from .tickets/prefix or directory name.""" prefix = "" prefix_file = tickets_dir / "prefix" if prefix_file.is_file(): prefix = prefix_file.read_text(encoding="utf-8").split("\n")[0].strip() if not prefix: dir_name = tickets_dir.parent.name parts = re.split(r"[-_]", dir_name) prefix = "".join(p[0] for p in parts if p) if len(prefix) < 2: prefix = dir_name[:3] # argparse reads an ID starting with '-' as an option, and a space splits it in two. prefix = re.sub(r"\s+", "", prefix).strip("-_") or "tk" alphabet = string.ascii_lowercase + string.digits suffix = "".join(secrets.choice(alphabet) for _ in range(4)) return f"{prefix}-{suffix}" def resolve_ticket(tickets_dir: Path, partial_id: str) -> Path: """Resolve a partial ticket ID to a file path. Raises SystemExit on ambiguous or not-found. """ partial_id = partial_id.strip() exact = tickets_dir / f"{partial_id}.md" if exact.is_file(): return exact matches = [] for dirpath, dirnames, filenames in os.walk(tickets_dir, followlinks=True): dp = Path(dirpath) rel = dp.relative_to(tickets_dir) if any(part.startswith(".") for part in rel.parts): dirnames.clear() continue for fn in filenames: if fn.endswith(".md") and partial_id in Path(fn).stem: matches.append(dp / fn) if len(matches) == 1: return matches[0] if len(matches) > 1: lines = [f"Ambiguous ID '{partial_id}' matches {len(matches)} tickets:"] for m in sorted(matches): t = load_ticket(m) lines.append(f" {t.id} - {t.title}") _error("\n".join(lines)) _error(f"Ticket '{partial_id}' not found") def _error(msg: str) -> None: """Print error and exit.""" print(f"Error: {msg}", file=sys.stderr) sys.exit(1) def _iso_date() -> str: """Return current UTC time in ISO 8601 format.""" return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # --------------------------------------------------------------------------- # Lifecycle commands # --------------------------------------------------------------------------- def cmd_create(args: argparse.Namespace, tickets_dir: Path) -> None: """Create a new ticket.""" tickets_dir.mkdir(parents=True, exist_ok=True) parent_id = "" if args.parent: parent_path = resolve_ticket(tickets_dir, args.parent) parent_id = parent_path.stem title = args.title or "Untitled" for _ in range(20): ticket_id = generate_id(tickets_dir) if not (tickets_dir / f"{ticket_id}.md").exists(): break else: _error("Could not generate a unique ticket ID after 20 attempts") now = _iso_date() assignee = args.assignee if not assignee: try: # Partial path on purpose: the name comes from whichever git the user runs. result = subprocess.run( # nosec B603 B607 ["git", "config", "user.name"], capture_output=True, text=True, timeout=5, check=False, ) if result.returncode == 0: assignee = result.stdout.strip() except (FileNotFoundError, subprocess.TimeoutExpired): pass lines = [ "---", f"id: {ticket_id}", "status: open", "deps: []", "links: []", f"created: {now}", f"type: {args.type}", f"priority: {args.priority}", ] if assignee: lines.append(f"assignee: {assignee}") if args.external_ref: lines.append(f"external-ref: {args.external_ref}") if parent_id: lines.append(f"parent: {parent_id}") if args.repo: lines.append(f"repo: {args.repo}") if args.tags: tags = [t.strip() for t in args.tags.split(",")] lines.append(f"tags: [{', '.join(tags)}]") lines.append("---") lines.append(f"# {title}") lines.append("") if args.description: lines.append(args.description) lines.append("") if args.design: lines.append("## Design") lines.append("") lines.append(args.design) lines.append("") if args.acceptance: lines.append("## Acceptance Criteria") lines.append("") lines.append(args.acceptance) lines.append("") path = tickets_dir / f"{ticket_id}.md" path.write_text("\n".join(lines), encoding="utf-8") print(ticket_id) def cmd_status(args: argparse.Namespace, tickets_dir: Path) -> None: """Set ticket status.""" new_status = args.new_status if new_status not in VALID_STATUSES: _error( f"Invalid status '{new_status}'. " f"Must be one of: {', '.join(VALID_STATUSES)}" ) path = resolve_ticket(tickets_dir, args.id) save_field(path, "status", new_status) print(f"Updated {path.stem} -> {new_status}") def cmd_start(args: argparse.Namespace, tickets_dir: Path) -> None: args.new_status = "in_progress" cmd_status(args, tickets_dir) def cmd_close(args: argparse.Namespace, tickets_dir: Path) -> None: args.new_status = "closed" cmd_status(args, tickets_dir) def cmd_reopen(args: argparse.Namespace, tickets_dir: Path) -> None: args.new_status = "open" cmd_status(args, tickets_dir) # --------------------------------------------------------------------------- # Dependency commands # --------------------------------------------------------------------------- def cmd_dep(args: argparse.Namespace, tickets_dir: Path) -> None: """Dep command router: 'dep tree', 'dep cycle', or 'dep <id> <dep-id>'.""" positionals = args.dep_args if not positionals: _error( "Usage: tk dep <id> <dep-id>\n" " tk dep tree [--full] <id>\n" " tk dep cycle" ) if positionals[0] == "tree": _cmd_dep_tree(positionals[1:], tickets_dir) elif positionals[0] == "cycle": _cmd_dep_cycle(tickets_dir) elif len(positionals) >= 2: _dep_add(positionals[0], positionals[1], tickets_dir) else: _error("Usage: tk dep <id> <dep-id>") def _dep_add(id_str: str, dep_str: str, tickets_dir: Path) -> None: """Add a dependency.""" path = resolve_ticket(tickets_dir, id_str) dep_path = resolve_ticket(tickets_dir, dep_str) dep_id = dep_path.stem t = load_ticket(path) if dep_id in t.deps: print("Dependency already exists") return new_deps = t.deps + [dep_id] save_field(path, "deps", "[" + ", ".join(new_deps) + "]") print(f"Added dependency: {path.stem} -> {dep_id}") def cmd_undep(args: argparse.Namespace, tickets_dir: Path) -> None: """Remove a dependency.""" path = resolve_ticket(tickets_dir, args.id) dep_path = resolve_ticket(tickets_dir, args.dep_id) dep_id = dep_path.stem t = load_ticket(path) if dep_id not in t.deps: _error("Dependency not found") new_deps = [d for d in t.deps if d != dep_id] save_field(path, "deps", "[" + ", ".join(new_deps) + "]" if new_deps else "[]") print(f"Removed dependency: {path.stem} -/-> {dep_id}") def _cmd_dep_tree(argv: list[str], tickets_dir: Path) -> None: """Show dependency tree for a ticket.""" full_mode = "--full" in argv argv = [a for a in argv if a != "--full"] if not argv: _error("Usage: tk dep tree [--full] <id>") root_path = resolve_ticket(tickets_dir, argv[0]) root_id = root_path.stem all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets} if root_id not in by_id: _error(f"Ticket '{root_id}' not found") printed: set[str] = set() def print_node( tid: str, prefix: str, connector: str, visited: set[str], ) -> None: if tid not in by_id or tid in visited: return if not full_mode and tid in printed: return t = by_id[tid] print(f"{prefix}{connector}{tid} [{t.status}] {t.title}") if not full_mode: printed.add(tid) children = [d for d in t.deps if d in by_id and d not in visited] new_visited = visited | {tid} for i, child in enumerate(children): is_last = i == len(children) - 1 if connector == "": child_prefix = prefix elif connector == "└── ": child_prefix = prefix + " " else: child_prefix = prefix + "│ " child_conn = "└── " if is_last else "├── " print_node(child, child_prefix, child_conn, new_visited) root = by_id[root_id] print(f"{root_id} [{root.status}] {root.title}") printed.add(root_id) children = [d for d in root.deps if d in by_id] for i, child in enumerate(children): is_last = i == len(children) - 1 connector = "└── " if is_last else "├── " print_node(child, "", connector, {root_id}) def _cmd_dep_cycle(tickets_dir: Path) -> None: """Find dependency cycles in open tickets.""" all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets if t.status != "closed"} WHITE, GRAY, BLACK = 0, 1, 2 color: dict[str, int] = {tid: WHITE for tid in by_id} cycles: list[list[str]] = [] seen_normalized: set[str] = set() def dfs(node: str, path: list[str]) -> None: color[node] = GRAY path.append(node) for dep in by_id[node].deps: if dep not in by_id: continue if color[dep] == GRAY: idx = path.index(dep) cycle = path[idx:] min_idx = cycle.index(min(cycle)) normalized = cycle[min_idx:] + cycle[:min_idx] norm_key = ",".join(normalized) if norm_key not in seen_normalized: seen_normalized.add(norm_key) cycles.append(normalized) elif color[dep] == WHITE: dfs(dep, path) path.pop() color[node] = BLACK for tid in by_id: if color[tid] == WHITE: dfs(tid, []) if not cycles: print("No dependency cycles found") return for i, cycle in enumerate(cycles): if i > 0: print() cycle_str = " -> ".join(cycle + [cycle[0]]) print(f"Cycle {i + 1}: {cycle_str}") for tid in cycle: t = by_id[tid] print(f" {tid:<8s} [{t.status}] {t.title}") # --------------------------------------------------------------------------- # Link commands # --------------------------------------------------------------------------- def cmd_link(args: argparse.Namespace, tickets_dir: Path) -> None: """Link tickets together (symmetric).""" raw_ids = args.ids if len(raw_ids) < 2: _error("Usage: tk link <id> <id> [id...]") paths = [] ids = [] for raw in raw_ids: p = resolve_ticket(tickets_dir, raw) paths.append(p) ids.append(p.stem) count = 0 for i, (p, self_id) in enumerate(zip(paths, ids)): t = load_ticket(p) others = [oid for j, oid in enumerate(ids) if j != i] new_links = list(t.links) for oid in others: if oid not in new_links: new_links.append(oid) count += 1 fmt = "[" + ", ".join(new_links) + "]" if new_links else "[]" save_field(p, "links", fmt) if count == 0: print("All links already exist") else: print(f"Added {count} link(s) between {len(ids)} tickets") def cmd_unlink(args: argparse.Namespace, tickets_dir: Path) -> None: """Remove link between two tickets (symmetric).""" path = resolve_ticket(tickets_dir, args.id) target_path = resolve_ticket(tickets_dir, args.target_id) self_id = path.stem target_id = target_path.stem for p, remove_id in [(path, target_id), (target_path, self_id)]: t = load_ticket(p) if remove_id in t.links: new_links = [lid for lid in t.links if lid != remove_id] fmt = "[" + ", ".join(new_links) + "]" if new_links else "[]" save_field(p, "links", fmt) print(f"Removed link: {self_id} <-> {target_id}") # --------------------------------------------------------------------------- # Listing commands # --------------------------------------------------------------------------- def cmd_ready(args: argparse.Namespace, tickets_dir: Path) -> None: """List open/in_progress tickets with all deps resolved.""" all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets} assignee_filter = getattr(args, "assignee", "") or "" tag_filter = getattr(args, "tag", "") or "" ready = [] for t in all_tickets: if t.status not in ("open", "in_progress"): continue if assignee_filter and t.assignee != assignee_filter: continue if tag_filter and tag_filter not in t.tags: continue all_closed = all( by_id[d].status == "closed" for d in t.deps if d in by_id ) if all_closed: ready.append(t) ready.sort(key=lambda t: (t.priority, t.id)) for t in ready: print(f"{t.id:<8s} [P{t.priority}][{t.status}] - {t.title}") def cmd_blocked(args: argparse.Namespace, tickets_dir: Path) -> None: """List open/in_progress tickets with unresolved deps.""" all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets} assignee_filter = getattr(args, "assignee", "") or "" tag_filter = getattr(args, "tag", "") or "" blocked: list[tuple[Ticket, list[str]]] = [] for t in all_tickets: if t.status not in ("open", "in_progress"): continue if assignee_filter and t.assignee != assignee_filter: continue if tag_filter and tag_filter not in t.tags: continue blockers = [d for d in t.deps if d in by_id and by_id[d].status != "closed"] if blockers: blocked.append((t, blockers)) blocked.sort(key=lambda pair: (pair[0].priority, pair[0].id)) for t, blockers in blocked: blocker_str = ", ".join(blockers) print(f"{t.id:<8s} [P{t.priority}][{t.status}] - {t.title} <- [{blocker_str}]") def cmd_closed(args: argparse.Namespace, tickets_dir: Path) -> None: """List recently closed tickets by mtime.""" limit = getattr(args, "limit", 20) or 20 assignee_filter = getattr(args, "assignee", "") or "" tag_filter = getattr(args, "tag", "") or "" all_tickets = load_all(tickets_dir) closed: list[tuple[float, Ticket]] = [] for t in all_tickets: if t.status not in ("closed", "done"): continue if assignee_filter and t.assignee != assignee_filter: continue if tag_filter and tag_filter not in t.tags: continue mtime = t.path.stat().st_mtime if t.path else 0 closed.append((mtime, t)) closed.sort(key=lambda pair: pair[0], reverse=True) for _, t in closed[:limit]: print(f"{t.id:<8s} [{t.status}] - {t.title}") def cmd_recent(args: argparse.Namespace, tickets_dir: Path) -> None: """List last N modified tickets regardless of status.""" limit = getattr(args, "limit", 5) or 5 all_tickets = load_all(tickets_dir) with_mtime: list[tuple[float, Ticket]] = [] for t in all_tickets: mtime = t.path.stat().st_mtime if t.path else 0 with_mtime.append((mtime, t)) with_mtime.sort(key=lambda pair: pair[0], reverse=True) for _, t in with_mtime[:limit]: marker = TYPE_MARKERS.get(t.type, "") marker_str = f" {marker}" if marker else "" print(f"{t.id:<8s} [P{t.priority}][{t.status}]{marker_str} - {t.title}") # --------------------------------------------------------------------------- # Display commands # --------------------------------------------------------------------------- def cmd_show(args: argparse.Namespace, tickets_dir: Path) -> None: """Display ticket with computed sections.""" path = resolve_ticket(tickets_dir, args.id) target_id = path.stem all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets} target = by_id.get(target_id) text = path.read_text(encoding="utf-8") for line in text.split("\n"): if line.startswith("parent:") and target and target.parent in by_id: parent_title = by_id[target.parent].title print(f"{line} # {parent_title}") else: print(line) if not target: return blockers = [d for d in target.deps if d in by_id and by_id[d].status != "closed"] if blockers: print() print("## Blockers") print() for d in blockers: t = by_id[d] print(f"- {d} [{t.status}] {t.title}") blocking = [ t for t in all_tickets if target_id in t.deps and t.status != "closed" ] if blocking: print() print("## Blocking") print() for t in blocking: print(f"- {t.id} [{t.status}] {t.title}") children = [t for t in all_tickets if t.parent == target_id] if children: print() print("## Children") print() for t in children: print(f"- {t.id} [{t.status}] {t.title}") if target.links: print() print("## Linked") print() for lid in target.links: if lid in by_id: t = by_id[lid] print(f"- {lid} [{t.status}] {t.title}") def cmd_add_note(args: argparse.Namespace, tickets_dir: Path) -> None: """Append a timestamped note to a ticket.""" path = resolve_ticket(tickets_dir, args.id) note_parts = getattr(args, "text", []) or [] if note_parts: note = " ".join(note_parts) elif not sys.stdin.isatty(): note = sys.stdin.read() else: _error("No note provided") timestamp = _iso_date() content = path.read_text(encoding="utf-8") if "## Notes" not in content: content += "\n## Notes\n" content += f"\n**{timestamp}**\n\n{note}\n" path.write_text(content, encoding="utf-8") print(f"Note added to {path.stem}") EDITABLE_FIELDS = { "priority": lambda v: str(int(v)), "type": lambda v: v if v in VALID_TYPES else None, "assignee": lambda v: v, "repo": lambda v: v, "parent": None, "tags": lambda v: f"[{', '.join(t.strip() for t in v.split(',') if t.strip())}]", "external-ref": lambda v: v, } def cmd_edit(args: argparse.Namespace, tickets_dir: Path) -> None: """Edit frontmatter fields on an existing ticket.""" path = resolve_ticket(tickets_dir, args.id) changed = [] for field_name, validator in EDITABLE_FIELDS.items(): attr = field_name.replace("-", "_") val = getattr(args, attr, None) if val is None: continue if validator is None: continue converted = validator(val) if converted is None: _error(f"Invalid value for {field_name}: {val}") save_field(path, field_name, converted) changed.append(f"{field_name}={val}") parent = getattr(args, "parent", None) if parent is not None: parent_path = resolve_ticket(tickets_dir, parent) save_field(path, "parent", parent_path.stem) changed.append(f"parent={parent_path.stem}") if not changed: _error("No fields specified. Use --priority, --type, --assignee, " "--repo, --parent, --tags, --external-ref") print(f"Updated {path.stem}: {', '.join(changed)}") # --------------------------------------------------------------------------- # Tree command (parent-child hierarchy) # --------------------------------------------------------------------------- def _format_tree_line(t: Ticket) -> str: """Format a single tree line with type marker.""" marker = TYPE_MARKERS.get(t.type, "") marker_str = f" {marker}" if marker else "" return f"{t.id} [P{t.priority}][{t.status}]{marker_str} {t.title}" def _print_tree_node( tid: str, prefix: str, connector: str, by_id: dict[str, Ticket], children_map: dict[str, list[str]], visited: set[str] | None = None, ) -> None: """Recursively print a tree node and its children.""" if visited is None: visited = set() if tid in visited: return visited = visited | {tid} t = by_id[tid] print(f"{prefix}{connector}{_format_tree_line(t)}") kids = children_map.get(tid, []) for i, child_id in enumerate(kids): is_last = i == len(kids) - 1 child_connector = "└── " if is_last else "├── " if connector == "": child_prefix = prefix elif connector == "└── ": child_prefix = prefix + " " else: child_prefix = prefix + "│ " _print_tree_node( child_id, child_prefix, child_connector, by_id, children_map, visited, ) def cmd_tree(args: argparse.Namespace, tickets_dir: Path) -> None: """Show parent-child hierarchy.""" all_tickets = load_all(tickets_dir) by_id = {t.id: t for t in all_tickets} children_map: dict[str, list[str]] = {} for t in all_tickets: if t.parent and t.parent in by_id: children_map.setdefault(t.parent, []).append(t.id) for children in children_map.values(): children.sort( key=lambda cid: (by_id[cid].priority, cid) ) root_id = getattr(args, "id", None) if root_id: root_path = resolve_ticket(tickets_dir, root_id) root_id = root_path.stem if root_id not in by_id: _error(f"Ticket '{root_id}' not found") _print_tree_node(root_id, "", "", by_id, children_map) else: roots = [ t for t in all_tickets if not t.parent or t.parent not in by_id ] roots.sort(key=lambda t: (t.priority, t.id)) for i, root in enumerate(roots): if i > 0: print() _print_tree_node(root.id, "", "", by_id, children_map) # --------------------------------------------------------------------------- # Plugin system # --------------------------------------------------------------------------- def _find_plugin(cmd: str) -> str | None: """Find a plugin executable (tk-cmd or ticket-cmd) in PATH.""" for prefix in ("tk", "ticket"): plugin_name = f"{prefix}-{cmd}" for directory in os.environ.get("PATH", "").split(os.pathsep): candidate = Path(directory) / plugin_name if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate) return None def _list_plugins() -> list[tuple[str, str]]: """List installed plugins with descriptions.""" seen: set[str] = set() plugins: list[tuple[str, str]] = [] for prefix in ("tk", "ticket"): for directory in os.environ.get("PATH", "").split(os.pathsep): d = Path(directory) if not d.is_dir(): continue try: entries = sorted(d.iterdir()) except PermissionError: continue for candidate in entries: if not candidate.name.startswith(f"{prefix}-"): continue if not candidate.is_file() or not os.access(candidate, os.X_OK): continue cmd = candidate.name[len(prefix) + 1 :] if cmd in seen: continue seen.add(cmd) desc = "" try: with open(candidate, encoding="utf-8", errors="replace") as f: for _, line in zip(range(10), f): if line.startswith("# tk-plugin:"): desc = line[len("# tk-plugin:") :].strip() break except (OSError, UnicodeDecodeError): pass if not desc: try: # Plugins are executables the user put on PATH; running them is the plugin system. result = subprocess.run( # nosec B603 [str(candidate), "--tk-describe"], capture_output=True, text=True, timeout=1, check=False, ) if result.returncode == 0: first = result.stdout.strip().split("\n")[0] if first.startswith("tk-plugin:"): desc = first[len("tk-plugin:") :].strip() except (FileNotFoundError, subprocess.TimeoutExpired, OSError): pass plugins.append((cmd, desc or "(no description)")) return plugins def _pager_command(pager: str, windows: bool) -> list[str] | str | None: """How to start the pager, or None when the setting cannot be run.""" if not pager.strip(): return None if windows: # CreateProcess parses the quoting of a command line itself. return pager.strip() try: # shlex keeps a quoted pager path in one piece. return shlex.split(pager) or None except ValueError: return None def _exec_plugin(plugin_path: str, argv: list[str]) -> None: """Execute a plugin, setting up the environment.""" tickets_dir = find_tickets_dir() if tickets_dir and tickets_dir.is_dir(): os.environ["TICKETS_DIR"] = str(tickets_dir) os.environ["TK_SCRIPT"] = str(Path(__file__).resolve()) os.execv(plugin_path, [plugin_path, *argv]) # nosec B606 # --------------------------------------------------------------------------- # CLI parser # --------------------------------------------------------------------------- def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="tk", description="Minimal ticket system with dependency tracking.", ) parser.add_argument( "--version", "-V", action="version", version=f"tk {TK_VERSION} ({TK_PART_NUMBER})", ) sub = parser.add_subparsers(dest="command", metavar="<command>") # create p = sub.add_parser("create", help="Create a new ticket.") p.add_argument("title", nargs="?", default="") p.add_argument("-d", "--description", default="") p.add_argument("-p", "--priority", type=int, default=2) p.add_argument("-t", "--type", default="task", choices=VALID_TYPES) p.add_argument("-a", "--assignee", default="") p.add_argument("--parent", default="") p.add_argument("--tags", default="") p.add_argument("--external-ref", dest="external_ref", default="") p.add_argument("--repo", default="", help="repository the ticket belongs to (owner/name)") p.add_argument("--design", default="") p.add_argument("--acceptance", default="") for name, help_text in [ ("start", "Set status to in_progress."), ("close", "Set status to closed."), ("reopen", "Set status to open."), ]: |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |