Add chunk-pr sync and wait-for

This commit is contained in:
2026-11-12 08:43:14 +01:00
parent 0d32cab386
commit 2ab44beca2
7 changed files with 287 additions and 2 deletions
View File
+88
View File
@@ -0,0 +1,88 @@
"""Wait until a file a background job writes holds a line matching a pattern, and print that line.
usage: wait-for <file> [<pattern>] [--timeout <seconds>]
<pattern> is a Python regular expression, searched for in each line; it prints the first line that
holds a match. Without <pattern>, it waits until the file holds anything, and prints its last
line. It checks every 2 seconds and gives up after --timeout seconds, 540 by default, so it fits
one foreground call of the Bash tool, whose limit is 600 seconds.
Exit 0 on the line, 1 on the timeout or bad arguments, saying why.
"""
import pathlib
import re
import sys
import time
import typing
from failure import Failure
POLL_SECONDS = 2
TIMEOUT_SECONDS = 540
USAGE = "usage: wait-for <file> [<pattern>] [--timeout <seconds>]"
class Clock(typing.Protocol):
def monotonic(self) -> float: ...
def sleep(self, seconds: float) -> None: ...
def line_in(path: pathlib.Path, pattern: re.Pattern[str] | None) -> str | None:
"""The first line matching pattern, or without one the last line, where the file holds anything; else None."""
try:
lines = path.read_text(errors="replace").splitlines()
except FileNotFoundError:
return None
if pattern is None:
return lines[-1] if lines else None
return next((line for line in lines if pattern.search(line)), None)
def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) -> str | Failure:
path = pathlib.Path(file)
compiled = re.compile(pattern) if pattern is not None else None
deadline = clock.monotonic() + timeout
while (found := line_in(path, compiled)) is None:
left = deadline - clock.monotonic()
if left <= 0:
if not path.exists():
return Failure(f"{file} did not appear in {timeout:g} s")
last = line_in(path, None)
wanted = f"no line matching `{pattern}`" if pattern is not None else "nothing"
return Failure(f"{file} held {wanted} after {timeout:g} s" + (f"; its last line: {last}" if last is not None else ""))
clock.sleep(min(POLL_SECONDS, left))
return found
def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure:
operands = list(argv)
timeout = float(TIMEOUT_SECONDS)
if "--timeout" in operands:
at = operands.index("--timeout")
given = operands[at + 1:at + 2]
if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0:
return Failure(f"give --timeout a number of seconds above 0; {USAGE}")
timeout = float(given[0])
del operands[at:at + 2]
if not 1 <= len(operands) <= 2:
return Failure(USAGE)
pattern = operands[1] if len(operands) == 2 else None
if pattern is not None:
try:
re.compile(pattern)
except re.error as error:
return Failure(f"cannot read the pattern `{pattern}`: {error}")
return operands[0], pattern, timeout
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
parsed = arguments(argv)
done = parsed if isinstance(parsed, Failure) else waited(*parsed)
if isinstance(done, Failure):
print(f"wait-for: {done.reason}", file=sys.stderr)
return 1
print(done)
return 0
+76
View File
@@ -0,0 +1,76 @@
import pathlib
import subprocess
import sys
import tempfile
import threading
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from wait_for import main
TOOL = pathlib.Path(__file__).resolve().parents[1] / "wait-for"
class Clock:
"""A fake clock whose sleep advances time and runs the next of the steps given, one per sleep."""
def __init__(self, *steps):
self.now = 0.0
self.steps = list(steps)
def monotonic(self) -> float:
return self.now
def sleep(self, seconds: float):
self.now += seconds
if self.steps:
self.steps.pop(0)()
class WaitFor(unittest.TestCase):
def setUp(self):
self.file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "report.md")
def test_prints_the_first_line_matching_the_pattern_once_the_file_holds_it(self):
clock = Clock(lambda: self.file.write_text("running\n"), lambda: self.file.write_text("running\n== 3 passed in 1s ==\nFull log: x\n"))
self.assertEqual(main.waited(str(self.file), r"passed|failed", 60, clock), "== 3 passed in 1s ==")
self.assertEqual(clock.now, 2 * main.POLL_SECONDS)
def test_without_a_pattern_prints_the_last_line_once_the_file_holds_anything(self):
clock = Clock(lambda: self.file.write_text(""), lambda: self.file.write_text("# Report\nNo findings.\n"))
self.assertEqual(main.waited(str(self.file), None, 60, clock), "No findings.")
def test_a_file_already_holding_the_line_returns_at_once(self):
self.file.write_text("done\n")
clock = Clock()
self.assertEqual(main.waited(str(self.file), "done", 60, clock), "done")
self.assertEqual(clock.now, 0)
def test_gives_up_at_the_timeout_naming_the_file_and_its_last_line(self):
self.file.write_text("still running\n")
clock = Clock()
self.assertEqual(main.waited(str(self.file), "passed", 30, clock), Failure(f"{self.file} held no line matching `passed` after 30 s; its last line: still running"))
self.assertLessEqual(clock.now, 30)
def test_gives_up_on_a_file_that_never_appears(self):
self.assertEqual(main.waited(str(self.file), None, 5, Clock()), Failure(f"{self.file} did not appear in 5 s"))
def test_the_command_waits_for_a_file_another_process_writes(self):
writer = threading.Timer(0.5, lambda: self.file.write_text("== 1 passed in 0.1s ==\n"))
writer.start()
self.addCleanup(writer.cancel)
result = subprocess.run([sys.executable, str(TOOL), str(self.file), "passed", "--timeout", "20"], capture_output=True, text=True)
self.assertEqual((result.returncode, result.stdout, result.stderr), (0, "== 1 passed in 0.1s ==\n", ""))
def test_refuses_a_bad_pattern_timeout_or_argument_count_waiting_for_nothing(self):
for argv in ([], [str(self.file), "("], [str(self.file), "--timeout", "0"], [str(self.file), "--timeout", "x"], [str(self.file), "a", "b"]):
with self.subTest(argv=argv):
result = subprocess.run([sys.executable, str(TOOL), *argv], capture_output=True, text=True, timeout=10)
self.assertEqual((result.returncode, result.stdout), (1, ""))
self.assertIn("wait-for: ", result.stderr)
if __name__ == "__main__":
unittest.main()