Files

84 lines
3.5 KiB
Python

#!/usr/bin/env python3
"""Read-only task, branch and worktree lookup for Forge testtask."""
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
HEADING = re.compile(r"^## ([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\s+[—-]", re.M)
LABEL = re.compile(r"(?:Task )?[Bb]ranch(?:/worktree)?:\s*`([^`]+)`")
USAGE = "Usage: scripts/testtask.sh <task-id|branch-name>"
def git(*args):
return subprocess.check_output(["git", "-C", str(ROOT), *args], text=True).strip()
def records():
content = (ROOT / "docs/TASKS.md").read_text(encoding="utf-8")
headings = list(HEADING.finditer(content))
result = {}
for i, match in enumerate(headings):
end = headings[i + 1].start() if i + 1 < len(headings) else len(content)
result.setdefault(match.group(1), []).append(content[match.end():end])
return result
def task_branches(task_id, section, branches):
slug = task_id.lower()
found = {branch for branch in branches if re.search(rf"(^|[-/]){re.escape(slug)}($|[-/])", branch.lower())}
found.update(branch for branch in LABEL.findall(section) if branch in branches)
return found
def error(message):
print(f"testtask: {message}", file=sys.stderr)
return 2
def main(args):
if args == ["--help"]:
print(USAGE)
print("Resolve an existing task and worktree; Forge has no application runtime or manual-test hook.")
return 0
if len(args) != 1 or not args[0] or args[0].startswith("-"):
print(USAGE, file=sys.stderr)
return 2
identifier = args[0]
tasks = records()
branches = set(git("for-each-ref", "--format=%(refname:short)", "refs/heads").splitlines())
if identifier in tasks:
if len(tasks[identifier]) != 1:
return error(f"ambiguous task ID {identifier}: multiple task records")
task_id = identifier
matches = task_branches(task_id, tasks[task_id][0], branches)
if not matches:
return error(f"task {task_id} has no recorded local task branch")
if len(matches) != 1:
return error(f"ambiguous task {task_id}: branches {', '.join(sorted(matches))}")
branch = next(iter(matches))
elif identifier in branches:
branch = identifier
matches = [task_id for task_id, sections in tasks.items() if any(branch in task_branches(task_id, section, branches) for section in sections)]
if not matches:
return error(f"branch {branch} has no corresponding task record")
if len(matches) != 1 or len(tasks[matches[0]]) != 1:
return error(f"ambiguous branch {branch}: task records {', '.join(sorted(matches))}")
task_id = matches[0]
else:
return error(f"unknown task ID or branch: {identifier}")
paths = []
for block in git("worktree", "list", "--porcelain").split("\n\n"):
lines = block.splitlines()
if f"branch refs/heads/{branch}" not in lines:
continue
path = next((Path(line[9:]) for line in lines if line.startswith("worktree ")), None)
if path and path.is_dir():
paths.append(path)
if not paths:
return error(f"task {task_id} on branch {branch} has no existing worktree")
if len(paths) != 1:
return error(f"ambiguous branch {branch}: multiple worktrees")
print(f"task: {task_id}\nbranch: {branch}\nworktree: {paths[0]}")
print("testtask is provisioned but blocked: Forge has no application runtime or task-specific manual-test hook.", file=sys.stderr)
return 3
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))