81 lines
3.5 KiB
Python
81 lines
3.5 KiB
Python
"""Read-only Git branch, task, and worktree selection shared by both entry points."""
|
|
import re
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
HEADING = re.compile(r"^## ([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\s+[—-]", re.M)
|
|
LABEL = re.compile(r"(?:Task )?[Bb]ranch(?:/worktree)?:\s*`([^`]+)`")
|
|
|
|
|
|
class TargetError(Exception):
|
|
pass
|
|
|
|
|
|
def git(root, *args):
|
|
result = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise TargetError(result.stderr.strip() or "Git command failed")
|
|
return result.stdout.strip()
|
|
|
|
|
|
def task_records(root):
|
|
path = root / "docs/TASKS.md"
|
|
if not path.is_file():
|
|
return {}
|
|
content = path.read_text(encoding="utf-8")
|
|
headings = list(HEADING.finditer(content))
|
|
records = {}
|
|
for i, match in enumerate(headings):
|
|
end = headings[i + 1].start() if i + 1 < len(headings) else len(content)
|
|
records.setdefault(match.group(1), []).append(content[match.end():end])
|
|
return records
|
|
|
|
|
|
def associated(task_id, section, branches):
|
|
slug = task_id.lower()
|
|
found = {name for name in branches if re.search(rf"(^|[-/]){re.escape(slug)}($|[-/])", name.lower())}
|
|
found.update(name for name in LABEL.findall(section) if name in branches)
|
|
return found
|
|
|
|
|
|
def resolve(script_path, identifier=None):
|
|
origin = Path.cwd() if identifier is None else script_path.parent
|
|
root = Path(git(origin, "rev-parse", "--show-toplevel")).resolve()
|
|
branches = set(git(root, "for-each-ref", "--format=%(refname:short)", "refs/heads").splitlines())
|
|
records = task_records(root)
|
|
if identifier is None:
|
|
result = subprocess.run(["git", "-C", str(origin), "symbolic-ref", "--quiet", "--short", "HEAD"], capture_output=True, text=True)
|
|
branch = result.stdout.strip()
|
|
if not branch:
|
|
raise TargetError("current worktree has detached HEAD; specify a branch or task ID")
|
|
selected = Path(git(origin, "rev-parse", "--show-toplevel")).resolve()
|
|
else:
|
|
task_match = identifier in records
|
|
branch_match = identifier in branches
|
|
if task_match and branch_match:
|
|
raise TargetError(f"ambiguous identifier {identifier}: both task ID and branch; disambiguate in project records")
|
|
if task_match:
|
|
if len(records[identifier]) != 1:
|
|
raise TargetError(f"ambiguous task ID {identifier}: duplicate records")
|
|
matches = associated(identifier, records[identifier][0], branches)
|
|
if len(matches) != 1:
|
|
raise TargetError(f"task {identifier} maps to {len(matches)} branches: {', '.join(sorted(matches))}")
|
|
branch = next(iter(matches))
|
|
elif branch_match:
|
|
branch = identifier
|
|
else:
|
|
raise TargetError(f"unknown task ID or local branch: {identifier}")
|
|
paths = []
|
|
for block in git(root, "worktree", "list", "--porcelain").split("\n\n"):
|
|
lines = block.splitlines()
|
|
if f"branch refs/heads/{branch}" in lines:
|
|
path = next((Path(line[9:]) for line in lines if line.startswith("worktree ")), None)
|
|
if path and path.is_dir():
|
|
paths.append(path.resolve())
|
|
if len(paths) != 1:
|
|
raise TargetError(f"branch {branch} has {len(paths)} existing worktrees; require exactly one")
|
|
selected = paths[0]
|
|
if identifier is not None and branch not in branches:
|
|
raise TargetError(f"branch unavailable: {branch}")
|
|
return root, branch, selected
|