89 lines
3.0 KiB
Python
89 lines
3.0 KiB
Python
"""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
|