107 lines
3.8 KiB
Python
107 lines
3.8 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. A last line without its newline counts once a check finds the file unchanged, since the
|
|
job may still be writing it. 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, bad arguments or a file it cannot read, 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 text_of(path: pathlib.Path) -> str | None | Failure:
|
|
"""What the file holds; None where it doesn't exist."""
|
|
try:
|
|
return path.read_text(errors="replace")
|
|
except FileNotFoundError:
|
|
return None
|
|
except OSError as error:
|
|
return Failure(f"cannot read {path}: {error.strerror}")
|
|
|
|
|
|
def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None:
|
|
"""The first line of text matching pattern, or without one its last line; None where there is none."""
|
|
lines = text.splitlines()
|
|
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
|
|
before = None
|
|
while True:
|
|
text = text_of(path)
|
|
if isinstance(text, Failure):
|
|
return text
|
|
# A last line without its newline may still be being written: it counts once a poll finds it unchanged.
|
|
settled = text is None or text.endswith("\n") or text == before
|
|
whole = text if settled or text is None else text[:text.rfind("\n") + 1]
|
|
# Without a pattern the last line is wanted, so an unsettled one waits.
|
|
if whole is not None and (settled or compiled is not None) and (found := line_in(whole, compiled)) is not None:
|
|
return found
|
|
before = text
|
|
left = deadline - clock.monotonic()
|
|
if left <= 0:
|
|
if text is None:
|
|
return Failure(f"{file} did not appear in {timeout:g} s")
|
|
last = line_in(text, None)
|
|
wanted = f"no line matching `{pattern}`" if pattern is not None else "no text"
|
|
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))
|
|
|
|
|
|
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
|