okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
3.1 KiB82 linesraw
1#!/usr/bin/env python3
2"""Run a command in a real terminal (a pty) and answer its questions, for the real-package flow tests (update_model_flow.sh).
3
4    pty_drive.py [--timeout S] [--cols N --rows N] [--quit-after S --quit-with KEYS] [--answer 'REGEX=>TEXT' ...] -- command args
5
6Each --answer is used once, in order, the first time its REGEX shows in what the command printed after the previous answer; TEXT is typed followed by
7Enter (TEXT may be empty).  The whole transcript goes to stdout (control codes kept: the screens are drawn with them); the exit code is the command's,
8or 124 when the time ran out.  Standard library only.
9"""
10import argparse
11import fcntl
12import os
13import pty
14import re
15import select
16import struct
17import sys
18import termios
19import time
20
21
22def main() -> int:
23    ap = argparse.ArgumentParser()
24    ap.add_argument("--timeout", type=float, default=600)
25    ap.add_argument("--cols", type=int, default=140)
26    ap.add_argument("--rows", type=int, default=45)
27    ap.add_argument("--answer", action="append", default=[])
28    ap.add_argument("--quit-after", type=float, default=0, help="seconds after which --quit-with is typed (a screen that never ends by itself)")
29    ap.add_argument("--quit-with", default="q")
30    ap.add_argument("cmd", nargs=argparse.REMAINDER)
31    a = ap.parse_args()
32    cmd = a.cmd[1:] if a.cmd and a.cmd[0] == "--" else a.cmd
33    answers = []
34    for item in a.answer:
35        pattern, _, text = item.partition("=>")
36        answers.append((re.compile(pattern), text))
37    pid, fd = pty.fork()
38    if pid == 0:
39        os.environ["TERM"] = os.environ.get("TERM", "xterm-256color")
40        os.execvp(cmd[0], cmd)
41    fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", a.rows, a.cols, 0, 0))
42    start = time.monotonic()
43    seen = ""                      # what was printed since the last answer
44    quit_sent = False
45    code = None
46    while True:
47        if time.monotonic() - start > a.timeout:
48            os.kill(pid, 15)
49            code = 124
50            break
51        if a.quit_after and not quit_sent and time.monotonic() - start > a.quit_after:
52            os.write(fd, a.quit_with.encode())
53            quit_sent = True
54        ready, _, _ = select.select([fd], [], [], 0.5)
55        if ready:
56            try:
57                data = os.read(fd, 65536)
58            except OSError:
59                data = b""
60            if not data:
61                break
62            text = data.decode("utf-8", "replace")
63            sys.stdout.write(text)
64            sys.stdout.flush()
65            seen += text
66            plain = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", seen)
67            if answers and answers[0][0].search(plain):
68                os.write(fd, (answers[0][1] + "\n").encode())
69                answers.pop(0)
70                seen = ""
71    try:
72        _, status = os.waitpid(pid, 0)
73        if code is None:
74            code = os.waitstatus_to_exitcode(status)
75    except ChildProcessError:
76        code = code if code is not None else 0
77    sys.stdout.write(f"\n[pty_drive] exit {code}; unanswered: {[p.pattern for p, _ in answers]}\n")
78    return code
79
80
81if __name__ == "__main__":
82    sys.exit(main())