Answer stability round 1: 0 🔴, 3 🟡 (0 misread); bound the forge's CLI with a timeout in one runner, and read a pull request from a deleted fork
CI / tests (pull_request) Successful in 3m20s

This commit is contained in:
Lilleman
2026-11-19 23:30:30 +01:00
parent 356ae263e1
commit 0c52688ff8
7 changed files with 35 additions and 30 deletions
+5 -2
View File
@@ -24,12 +24,15 @@ def url_beside(origin_url: str, name: str) -> str | None:
return place.group(1) + name if place and not place.group(1).endswith("//") else None
def runner(cwd: str) -> Run:
def runner(cwd: str, timeout: float | None = None) -> Run:
"""Runs a command in cwd, stopped after timeout seconds where one is given."""
def run(command: list[str]) -> str | Failure:
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
except subprocess.TimeoutExpired:
return Failure(f"{' '.join(command[:3])}: stopped after {timeout} s")
if done.returncode:
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
return done.stdout
+3 -3
View File
@@ -56,9 +56,9 @@ class ReadyPull:
def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure:
"""Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it."""
"""Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT); Gitea names no head repo for a fork that was deleted. A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it."""
if forge == "gh":
# 100 is the most GitHub's API lists a page; gh lists 30 unless told.
# A limit: an awaited pull request past the first 100 open ones, drafts and forks counted, is not seen. `--draft=false` would make gh search, and GitHub's search index lags a pull request just marked ready.
listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"])
if isinstance(listed, Failure):
return listed
@@ -69,7 +69,7 @@ def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure:
if isinstance(pulls, Failure):
return pulls
try:
found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)]
found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if (pull["head"]["repo"] or {}).get("full_name") == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)]
except (AttributeError, KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
return [pull for pull in found if pull.number.isascii() and pull.number.isdigit() and isinstance(pull.head, str) and re.fullmatch(r"[0-9a-f]{40,64}", pull.head)]
+17 -7
View File
@@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, ready_pulls, ReadyPull, required_checks, WAIT_SECONDS
from failure import Failure
from forge.commands import forge_of, gitea, url_beside
from forge.commands import forge_of, gitea, runner, url_beside
class ForgeOf(unittest.TestCase):
@@ -136,11 +136,6 @@ class ChecksPassed(unittest.TestCase):
self.assertEqual(checks_passed("tea", "1", "abc", set(), tea([LONG]), self.fail).reason, f"tea api printed no commit status for abc: {LONG[:200]}")
if __name__ == "__main__":
unittest.main()
SHA = "a" * 40
GITEA_PULL = {"number": 7, "html_url": "https://gitea.example/o/r/pulls/7", "title": "Do 7", "head": {"sha": SHA, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}}
@@ -158,10 +153,25 @@ class ReadyPulls(unittest.TestCase):
def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self):
fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}}
draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"}
deleted_fork = {**GITEA_PULL, "number": 10, "head": {"sha": SHA, "repo": None}}
commands: list[list[str]] = []
self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)])
self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft, deleted_fork])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)])
self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]])
def test_fails_where_the_forge_cannot_list_them(self):
self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network")
self.assertEqual(ready_pulls("tea", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}")
class Runner(unittest.TestCase):
def test_prints_what_a_command_printed_and_fails_where_it_exits_nonzero_cannot_start_or_outlasts_its_timeout(self):
self.assertEqual(runner("/")(["echo", "hello"]), "hello\n")
self.assertEqual(runner("/")(["sh", "-c", "echo no >&2; exit 3"]), Failure("sh -c echo no >&2; exit 3: no"))
failed = runner("/")(["no-such-forge-cli", "pr", "list"])
self.assertIsInstance(failed, Failure)
self.assertTrue(failed.reason.startswith("no-such-forge-cli could not start: "), failed.reason)
self.assertEqual(runner("/", 0.05)(["sleep", "5"]), Failure("sleep 5: stopped after 0.05 s"))
if __name__ == "__main__":
unittest.main()