FORGE-F014 Add portable existing-project testtask runner

This commit is contained in:
rob
2026-11-19 12:21:34 +00:00
parent 860d6d43c7
commit 17660d8957
8 changed files with 283 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec python3 "$script_dir/testtask_runner.py" "$@"
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Run a repository-configured test command in an existing branch worktree."""
import json
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*`([^`]+)`")
def fail(message, code=2):
print(f"testtask: {message}", file=sys.stderr)
return code
def git(*args):
return subprocess.check_output(["git", "-C", str(ROOT), *args], text=True).strip()
def tasks():
path = ROOT / "docs/TASKS.md"
if not path.is_file():
return {}
content = path.read_text(encoding="utf-8")
headings = list(HEADING.finditer(content))
result = {}
for index, match in enumerate(headings):
end = headings[index + 1].start() if index + 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 resolve(identifier):
branches = set(git("for-each-ref", "--format=%(refname:short)", "refs/heads").splitlines())
records = tasks()
if identifier in records:
if len(records[identifier]) != 1:
raise ValueError(f"ambiguous task ID {identifier}: multiple task records")
matches = task_branches(identifier, records[identifier][0], branches)
if not matches:
raise ValueError(f"task {identifier} has no recorded local branch")
if len(matches) != 1:
raise ValueError(f"ambiguous task {identifier}: branches {', '.join(sorted(matches))}")
branch = next(iter(matches))
task_id = identifier
elif identifier in branches:
branch = identifier
matches = [task_id for task_id, sections in records.items()
if any(branch in task_branches(task_id, section, branches) for section in sections)]
if len(matches) > 1 or (matches and len(records[matches[0]]) > 1):
raise ValueError(f"ambiguous branch {branch}: task records {', '.join(sorted(matches))}")
task_id = matches[0] if matches else None
else:
raise ValueError(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}" 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)
if not paths:
raise ValueError(f"branch {branch} has no existing worktree")
if len(paths) != 1:
raise ValueError(f"ambiguous branch {branch}: multiple worktrees")
return task_id, branch, paths[0]
def configured_command(worktree):
path = worktree / ".bortstack/testtask.json"
if not path.is_file():
raise FileNotFoundError(f"testing unavailable: missing {path}")
try:
config = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise ValueError(f"invalid test configuration {path}: {exc}") from exc
if not isinstance(config, dict) or set(config) != {"command"}:
raise ValueError(f"invalid test configuration {path}: expected only a command field")
command = config["command"]
if not isinstance(command, list) or not command or any(not isinstance(arg, str) or not arg for arg in command):
raise ValueError(f"invalid test configuration {path}: command must be a nonempty string array")
return command
def main(argv):
if argv == ["--help"]:
print("Usage: scripts/testtask.sh <task-id|branch-name>")
print("Runs .bortstack/testtask.json command from the resolved branch worktree.")
return 0
if len(argv) != 1 or not argv[0] or argv[0].startswith("-"):
return fail("Usage: scripts/testtask.sh <task-id|branch-name>")
try:
task_id, branch, worktree = resolve(argv[0])
command = configured_command(worktree)
except FileNotFoundError as exc:
return fail(str(exc), 3)
except (ValueError, subprocess.CalledProcessError) as exc:
return fail(str(exc))
print(f"task: {task_id or '(none)'}\nbranch: {branch}\nworktree: {worktree}\ntests: {command!r}", flush=True)
try:
result = subprocess.run(command, cwd=worktree, check=False)
except OSError as exc:
return fail(f"could not start configured tests: {exc}", 3)
print(f"testtask: tests exited {result.returncode}", file=sys.stderr)
return result.returncode
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))