|
| 1 | +# Copyright 2025 Hathor Labs |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +IPython extension that adapts logging handlers to play nicely with the interactive prompt. |
| 17 | +
|
| 18 | +When loaded, all stream-based logging handlers are updated so their output is rendered |
| 19 | +through prompt_toolkit's ``run_in_terminal`` helper, which ensures log lines appear |
| 20 | +above the current input without corrupting the prompt. The original streams are restored |
| 21 | +when the extension is unloaded. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import io |
| 27 | +import logging |
| 28 | +import threading |
| 29 | +from contextlib import suppress |
| 30 | +from typing import Any, Callable, Iterable |
| 31 | + |
| 32 | +get_app_or_none: Callable[[], Any] | None = None |
| 33 | +pt_utils: Any | None = None |
| 34 | + |
| 35 | +try: |
| 36 | + from prompt_toolkit.application import get_app_or_none as _get_app_or_none |
| 37 | + from prompt_toolkit.shortcuts import utils as _pt_utils |
| 38 | +except ImportError: |
| 39 | + pass |
| 40 | +else: |
| 41 | + get_app_or_none = _get_app_or_none |
| 42 | + pt_utils = _pt_utils |
| 43 | + |
| 44 | +_original_streams: dict[logging.StreamHandler, Any] = {} |
| 45 | +_installed = False |
| 46 | + |
| 47 | + |
| 48 | +class PromptToolkitLogStream(io.TextIOBase): |
| 49 | + """Proxy stream that forwards writes through prompt_toolkit.""" |
| 50 | + |
| 51 | + def __init__(self, inner: Any): |
| 52 | + super().__init__() |
| 53 | + self._inner = inner |
| 54 | + self._encoding_override: str | None = None |
| 55 | + self._errors_override: str | None = None |
| 56 | + |
| 57 | + def _run_in_terminal(self, func: Callable[[], None]) -> None: |
| 58 | + if pt_utils is None: |
| 59 | + func() |
| 60 | + return |
| 61 | + |
| 62 | + app = get_app_or_none() if get_app_or_none is not None else None |
| 63 | + if app is None: |
| 64 | + func() |
| 65 | + return |
| 66 | + loop = getattr(app, 'loop', None) |
| 67 | + if loop is None: |
| 68 | + func() |
| 69 | + return |
| 70 | + |
| 71 | + event = threading.Event() |
| 72 | + handled = False |
| 73 | + |
| 74 | + def run_and_signal() -> None: |
| 75 | + nonlocal handled |
| 76 | + try: |
| 77 | + if not handled: |
| 78 | + pt_utils.run_in_terminal(func, in_executor=False) |
| 79 | + finally: |
| 80 | + handled = True |
| 81 | + event.set() |
| 82 | + |
| 83 | + loop.call_soon_threadsafe(run_and_signal) |
| 84 | + if not event.wait(timeout=5): |
| 85 | + handled = True |
| 86 | + func() |
| 87 | + |
| 88 | + def write(self, data: str) -> int: |
| 89 | + if not data: |
| 90 | + return 0 |
| 91 | + |
| 92 | + def _write() -> None: |
| 93 | + self._inner.write(data) |
| 94 | + |
| 95 | + self._run_in_terminal(_write) |
| 96 | + return len(data) |
| 97 | + |
| 98 | + def flush(self) -> None: |
| 99 | + def _flush() -> None: |
| 100 | + self._inner.flush() |
| 101 | + |
| 102 | + self._run_in_terminal(_flush) |
| 103 | + |
| 104 | + @property |
| 105 | + def encoding(self) -> str: |
| 106 | + if self._encoding_override is not None: |
| 107 | + return self._encoding_override |
| 108 | + return getattr(self._inner, 'encoding', 'utf-8') or 'utf-8' |
| 109 | + |
| 110 | + @encoding.setter |
| 111 | + def encoding(self, value: str) -> None: |
| 112 | + self._encoding_override = value |
| 113 | + |
| 114 | + @property |
| 115 | + def errors(self) -> str: |
| 116 | + if self._errors_override is not None: |
| 117 | + return self._errors_override |
| 118 | + return getattr(self._inner, 'errors', 'strict') or 'strict' |
| 119 | + |
| 120 | + @errors.setter |
| 121 | + def errors(self, value: str) -> None: |
| 122 | + self._errors_override = value |
| 123 | + |
| 124 | + def fileno(self) -> int: |
| 125 | + if hasattr(self._inner, 'fileno') and callable(getattr(self._inner, 'fileno')): |
| 126 | + return self._inner.fileno() |
| 127 | + raise io.UnsupportedOperation('fileno not available') |
| 128 | + |
| 129 | + def isatty(self) -> bool: |
| 130 | + if hasattr(self._inner, 'isatty') and callable(getattr(self._inner, 'isatty')): |
| 131 | + return self._inner.isatty() |
| 132 | + return False |
| 133 | + |
| 134 | + def close(self) -> None: |
| 135 | + # Do not close the underlying stream. |
| 136 | + pass |
| 137 | + |
| 138 | + @property |
| 139 | + def closed(self) -> bool: |
| 140 | + return False |
| 141 | + |
| 142 | + def readable(self) -> bool: |
| 143 | + return False |
| 144 | + |
| 145 | + def seekable(self) -> bool: |
| 146 | + return False |
| 147 | + |
| 148 | + def writable(self) -> bool: |
| 149 | + return True |
| 150 | + |
| 151 | + |
| 152 | +def _iter_stream_handlers() -> Iterable[logging.StreamHandler]: |
| 153 | + """Yield every stream handler currently registered.""" |
| 154 | + root = logging.getLogger() |
| 155 | + for handler in root.handlers: |
| 156 | + if isinstance(handler, logging.StreamHandler): |
| 157 | + yield handler |
| 158 | + |
| 159 | + for logger in logging.Logger.manager.loggerDict.values(): |
| 160 | + if isinstance(logger, logging.PlaceHolder): |
| 161 | + continue |
| 162 | + if not isinstance(logger, logging.Logger): |
| 163 | + continue |
| 164 | + for handler in logger.handlers: |
| 165 | + if isinstance(handler, logging.StreamHandler): |
| 166 | + yield handler |
| 167 | + |
| 168 | + |
| 169 | +def _install_prompt_toolkit_streams() -> None: |
| 170 | + if pt_utils is None: |
| 171 | + return |
| 172 | + |
| 173 | + for handler in _iter_stream_handlers(): |
| 174 | + current_stream = getattr(handler, 'stream', None) |
| 175 | + if current_stream is None or isinstance(current_stream, PromptToolkitLogStream): |
| 176 | + continue |
| 177 | + |
| 178 | + proxy = PromptToolkitLogStream(current_stream) |
| 179 | + _original_streams[handler] = current_stream |
| 180 | + handler.stream = proxy |
| 181 | + |
| 182 | + |
| 183 | +def load_ipython_extension(shell: Any) -> None: |
| 184 | + """Called by IPython when the extension is loaded.""" |
| 185 | + global _installed |
| 186 | + |
| 187 | + if pt_utils is None: |
| 188 | + shell.write_err('prompt_toolkit not available; logs will use standard output.\n') |
| 189 | + return |
| 190 | + |
| 191 | + if _installed: |
| 192 | + return |
| 193 | + |
| 194 | + _install_prompt_toolkit_streams() |
| 195 | + _installed = True |
| 196 | + |
| 197 | + |
| 198 | +def unload_ipython_extension(shell: Any) -> None: |
| 199 | + """Called by IPython when the extension is unloaded.""" |
| 200 | + restore_logging_streams() |
| 201 | + |
| 202 | + |
| 203 | +def restore_logging_streams() -> None: |
| 204 | + """Restore the original logging streams.""" |
| 205 | + global _installed |
| 206 | + for handler, stream in list(_original_streams.items()): |
| 207 | + with suppress(Exception): |
| 208 | + handler.stream = stream |
| 209 | + _original_streams.clear() |
| 210 | + _installed = False |
0 commit comments