|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import logging |
| 4 | +import os |
| 5 | +import re |
| 6 | +import threading |
2 | 7 | from datetime import datetime |
3 | | -from typing import Callable |
| 8 | +from typing import Callable, Pattern |
4 | 9 |
|
5 | 10 | from .._models._messages import LogMessage |
6 | 11 |
|
@@ -30,3 +35,64 @@ def emit(self, record: logging.LogRecord): |
30 | 35 | except Exception: |
31 | 36 | # Don't let logging errors crash the app |
32 | 37 | pass |
| 38 | + |
| 39 | + |
| 40 | +# A dispatcher is a callable that accepts (level, message) pairs |
| 41 | +DispatchLog = Callable[[str, str], None] |
| 42 | + |
| 43 | +LEVEL_PATTERNS: list[tuple[str, Pattern[str]]] = [ |
| 44 | + ("DEBUG", re.compile(r"^(DEBUG)[:\s-]+", re.I)), |
| 45 | + ("INFO", re.compile(r"^(INFO)[:\s-]+", re.I)), |
| 46 | + ("WARN", re.compile(r"^(WARNING|WARN)[:\s-]+", re.I)), |
| 47 | + ("ERROR", re.compile(r"^(ERROR|ERRO)[:\s-]+", re.I)), |
| 48 | +] |
| 49 | + |
| 50 | + |
| 51 | +def patch_textual_stderr(dispatch_log: DispatchLog) -> int: |
| 52 | + """Redirect subprocess stderr into a provided dispatcher. |
| 53 | +
|
| 54 | + Args: |
| 55 | + dispatch_log: Callable invoked with (level, message) for each stderr line. |
| 56 | + This will be called from a background thread, so the caller |
| 57 | + should use `App.call_from_thread` or equivalent. |
| 58 | +
|
| 59 | + Returns: |
| 60 | + int: The write file descriptor for stderr (pass to subprocesses). |
| 61 | + """ |
| 62 | + from textual.app import _PrintCapture |
| 63 | + |
| 64 | + read_fd, write_fd = os.pipe() |
| 65 | + |
| 66 | + # Patch fileno() so subprocesses can write to our pipe |
| 67 | + _PrintCapture.fileno = lambda self: write_fd # type: ignore[method-assign] |
| 68 | + |
| 69 | + def read_stderr_pipe() -> None: |
| 70 | + with os.fdopen(read_fd, "r", buffering=1) as pipe_reader: |
| 71 | + try: |
| 72 | + for raw in pipe_reader: |
| 73 | + text = raw.rstrip() |
| 74 | + level: str = "ERROR" |
| 75 | + message: str = text |
| 76 | + |
| 77 | + # Try to parse a known level prefix |
| 78 | + for lvl, pattern in LEVEL_PATTERNS: |
| 79 | + m = pattern.match(text) |
| 80 | + if m: |
| 81 | + level = lvl |
| 82 | + message = text[m.end() :] |
| 83 | + break |
| 84 | + |
| 85 | + dispatch_log(level, message) |
| 86 | + |
| 87 | + except Exception: |
| 88 | + # Never raise from thread |
| 89 | + pass |
| 90 | + |
| 91 | + thread = threading.Thread( |
| 92 | + target=read_stderr_pipe, |
| 93 | + daemon=True, |
| 94 | + name="stderr-reader", |
| 95 | + ) |
| 96 | + thread.start() |
| 97 | + |
| 98 | + return write_fd |
0 commit comments