Files
bortstack-forge/toolkits/testing/runtime/target.py
T
2026-12-02 15:44:24 +00:00

98 lines
4.4 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]+)+)(?::|[ \t]+[—-])", 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 acceptance_snapshot(root, directory, task_id):
directory = (root / directory).resolve()
selected = (directory / task_id.lower()).resolve()
if not directory.is_relative_to(root) or not selected.is_relative_to(directory):
raise TargetError("acceptance snapshot path leaves its configured location")
for block in git(root, "worktree", "list", "--porcelain").split("\n\n"):
lines = block.splitlines()
if f"worktree {selected}" in lines and "detached" in lines and selected.is_dir():
return selected
raise TargetError(f"task {task_id} requires a registered detached acceptance snapshot at {selected}")
def resolve(script_path, identifier=None, snapshot_directory=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_id = identifier
if re.fullmatch(r"[0-9]{3}", identifier):
task_id = f"TASK-{identifier}"
task_match = task_id 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[task_id]) != 1:
raise TargetError(f"ambiguous task ID {identifier}: duplicate records")
if snapshot_directory is not None:
return root, task_id, acceptance_snapshot(root, snapshot_directory, task_id)
matches = associated(task_id, records[task_id][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