Skip to content
Myr

Refactor pager stream handling (#3767)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents cbd7a41, bc32a92 · Browse files · 5 files+112 added−79 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+112 added−79 removed

  • tests:+50 added−19 removed
  • other:+62 added−60 removed

5 files+112 added−79 removed

modified:src/click/_compat.py+1 added-1 removed
504 unmodified lines
505 if color is None:506 if stream is None:507 stream = sys.stdin508 elif hasattr(stream, "color"):509 # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,509 # ._termui_impl._PagerWriter handles stripping ansi itself,510 # so we don't need to strip it here511 return False512 return not isatty(stream) and not _is_jupyter_kernel_output(stream)513 return not color
77 unmodified lines
modified:src/click/_termui_impl.py+57 added-59 removed
6 unmodified lines
7from __future__ import annotations89import collections.abc as cabc10import contextlib11import io11import math12import os13import shlex14import sys
11 unmodified lines
26from ._compat import strip_ansi27from ._compat import term_len28from ._compat import WIN29from .exceptions import ClickException31from .utils import _KeepOpenFile30from .utils import echo3132V = t.TypeVar("V")333437class _BufferedTextPagerStream(t.Protocol):38 buffer: t.BinaryIO394041def _has_binary_buffer(42 stream: t.BinaryIO | t.TextIO,43) -> t.TypeGuard[_BufferedTextPagerStream]:44 # TextIO is wider than TextIOWrapper; text-only streams such as StringIO45 # are valid TextIO values but do not expose a binary buffer to wrap.46 return getattr(stream, "buffer", None) is not None474835if os.name == "nt":36 BEFORE_BAR = "\r"37 AFTER_BAR = "\n"38else:
340 unmodified lines
379 self.finish()380 self.render_progress()381382397class MaybeStripAnsi(io.TextIOWrapper):398 def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):399 super().__init__(stream, **kwargs)383class _PagerWriter:384 """Wrap a pager's output stream to strip ANSI styling when colors are385 disabled.386387 The wrapped stream is owned by the pager strategy that produced it, so this388 wrapper never closes it: ``_pipepager`` closes its pipe to signal EOF to the389 pager process, ``_tempfilepager`` closes and removes its temporary file, and390 ``_nullpager`` leaves an external stream such as ``sys.stdout`` untouched.391392 The ``color`` attribute lets :func:`click.echo` detect that ANSI stripping393 is handled here, so it doesn't strip a second time (see394 :func:`._compat.should_strip_ansi`).395 """396397 def __init__(self, stream: t.TextIO, color: bool) -> None:398 self._stream = stream399 self.color = color400401 def write(self, text: str) -> int:402 if not self.color:403 text = strip_ansi(text)405 return super().write(text)404405 return self._stream.write(text)406407 def writelines(self, lines: cabc.Iterable[str]) -> None:408 for line in lines:409 self.write(line)410411 def flush(self) -> None:412 self._stream.flush()413414 def close(self) -> None:415 # The pager strategy owns the stream's lifecycle. Flush pending output,416 # but never close the underlying stream from here.417 self._stream.flush()418419 def __getattr__(self, name: str) -> t.Any:420 return getattr(self._stream, name)421422423def _pager_contextmanager(424 color: bool | None = None,410) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:425) -> t.ContextManager[tuple[t.TextIO, bool]]:426 """Decide what method to use for paging through text."""427 stdout = _default_text_stdout()428429 # There are no standard streams attached to write to. For example,
31 unmodified lines
461462 :param color: controls if the pager supports ANSI colors or not. The463 default is autodetection.464 """450 with _pager_contextmanager(color=color) as (stream, encoding, color):451 # Split streams by capabilities rather than the abstract TextIO /452 # BinaryIO annotations: buffered text streams can be unwrapped to bytes,453 # while other streams are yielded as-is.454 wrapper: MaybeStripAnsi | None = None455 if _has_binary_buffer(stream):456 # Text stream backed by a binary buffer.457 wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)458 stream = wrapper465 with _pager_contextmanager(color=color) as (stream, color):466 # Every pager strategy yields a text stream, so the only thing left to467 # do is strip ANSI styling when colors are disabled. The wrapper does468 # not close the stream: each strategy owns its stream's lifecycle.469 writer = _PagerWriter(stream, color=color)470 try:460 # Narrow the BinaryIO | TextIO union that _pager_contextmanager461 # yields; the caller writes text to the pager.462 yield t.cast(t.TextIO, stream)471 yield t.cast(t.TextIO, writer)472 finally:464 try:465 stream.flush()473 writer.flush()466 finally:467 # Hand the binary buffer back to the pager that produced it468 # rather than letting this TextIOWrapper close it on garbage469 # collection. The pager owns the buffer's lifecycle: subprocess470 # pipes and temp files are closed by their own helpers, while a471 # borrowed stdout must stay open for the caller. detach() runs472 # even if flush() raised, so the buffer is never closed here.473 if wrapper is not None:474 wrapper.detach()474475476@contextlib.contextmanager477def _pipepager(478 cmd_parts: list[str], color: bool | None = None480) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:479) -> t.Iterator[tuple[t.TextIO, bool]]:480 """Page through text by feeding it to another program.481482 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list483 produced by :func:`shlex.split`. The command is resolved to an absolute
58 unmodified lines
542 env=env,543 errors="replace",544 text=True,545 )547 stdin = t.cast(t.BinaryIO, c.stdin)548 encoding = get_best_encoding(stdin)546 # With ``text=True``, ``c.stdin`` is already a text stream that encodes547 # writes for the pager process (honoring ``errors="replace"``).548 stdin = t.cast(t.TextIO, c.stdin)549 try:550 yield stdin, encoding, color550 yield stdin, color551 except BrokenPipeError:552 # In case the pager exited unexpectedly, ignore the broken pipe error.553 pass554 except Exception as e:
31 unmodified lines
586587@contextlib.contextmanager588def _tempfilepager(589 cmd_parts: list[str], color: bool | None = None590) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:590) -> t.Iterator[tuple[t.TextIO, bool]]:591 """Page through text by invoking a program on a temporary file.592593 Used as the primary pager strategy on Windows (where piping to594 ``more`` adds spurious ``\\r\\n``), and as a fallback on other
35 unmodified lines
630 color = False631 # On Windows, NamedTemporaryFile cannot be opened by another process632 # while Python still has it open, so we use delete=False and clean up manually633 # rather than using a contextmanager here.634 f = tempfile.NamedTemporaryFile(mode="w", delete=False)634 f = tempfile.NamedTemporaryFile(635 mode="w", encoding=encoding, errors="replace", delete=False636 )637 try:636 yield t.cast(t.BinaryIO, f), encoding, color638 yield t.cast(t.TextIO, f), color639 f.flush()640 f.close()641 subprocess.call([str(cmd_path), f.name])642 finally:
7 unmodified lines
650651@contextlib.contextmanager652def _nullpager(653 stream: t.TextIO, color: bool | None = None652) -> t.Iterator[tuple[t.TextIO, str, bool]]:653 """Simply print unformatted text. This is the ultimate fallback. Don't close the654 output stream in this case, since it's coming from elsewhere rather than our655 internal helpers.654) -> t.Iterator[tuple[t.TextIO, bool]]:655 """Simply print unformatted text. This is the ultimate fallback.656657 The stream is wrapped in :class:`~click.utils._KeepOpenFile` so that, as a658 borrowed stream, it is not closed by a ``with`` block. The wrapper that659 :func:`get_pager_file` builds around it is detached rather than closed.657 The stream comes from elsewhere (typically ``sys.stdout``), so its lifecycle658 is left untouched: :class:`_PagerWriter` never closes what it wraps, and it659 is the only thing :func:`get_pager_file` hands to the caller.660 """661 encoding = get_best_encoding(stream)662661 if color is None:662 color = False663666 yield _KeepOpenFile(stream), encoding, color # type: ignore[misc]664 yield stream, color665666667class Editor:668 def __init__(
288 unmodified lines
modified:tests/test_utils/test_echo_via_pager.py+3 added-3 removed
195 unmodified lines
196 the pager stream before propagating the exception.197198 The pager file content is intentionally NOT asserted: pipe-drain timing199 between click and the pager subprocess is outside click's control200 (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent200 (#2899, #3470). Spying on ``_PagerWriter.write`` records what click sent201 to the pager, which is deterministic regardless of scheduling.202 """203 monkeypatch.setitem(os.environ, "PAGER", "cat")204 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)205206 writes: list[str] = []207 real_write = click._termui_impl.MaybeStripAnsi.write207 real_write = click._termui_impl._PagerWriter.write208209 def spy(self, text):210 writes.append(text)211 return real_write(self, text)212213 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)213 monkeypatch.setattr(click._termui_impl._PagerWriter, "write", spy)214215 pager_out_tmp = tmp_path / "pager_out.txt"216 with (217 pager_out_tmp.open("w") as f,
42 unmodified lines
modified:tests/test_termui.py+47 added-16 removed
902 unmodified lines
903)904def test_get_pager_file_nullpager_wraps_textio_stream(905 monkeypatch, tmp_path, color, expected906):907 """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""907 """When paging falls back to a real text stream, ANSI styling is stripped or908 preserved according to ``color``."""909 pager_out = tmp_path / "pager_out.txt"910911 with pager_out.open("w", encoding="utf-8") as text_stream:912 monkeypatch.setattr(
9 unmodified lines
922 assert pager_out.read_text(encoding="utf-8") == expected923924925def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):925 """The no-stdout fallback should keep a text-only stream and set ``.color``."""926 """The no-stdout fallback keeps the text stream open and strips ANSI."""927928 stream = io.StringIO()929 monkeypatch.setattr(sys, "stdout", None)930 monkeypatch.setattr(click._termui_impl, "StringIO", lambda: stream)931 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)932932 styled_text = click.style("hello", fg="red")933933 with click.get_pager_file(color=False) as pager:935 pager.write(styled_text)934 pager.write(click.style("hello", fg="red"))935936 # The wrapper must not close a stream it does not own.937 assert not stream.closed938 # With colors disabled, ANSI styling is stripped.938 assert stream.getvalue() == styled_text939 assert stream.getvalue() == "hello"940941942def test_get_pager_file_flushes_stream_on_exception(monkeypatch):943 """Exceptions should still flush the yielded stream in ``finally``."""944945 class FlushableTextStream(io.StringIO):946 def __init__(self):947 super().__init__()947 self.color = None948 self.flush_calls = 0949950 def flush(self):951 self.flush_calls += 1
1 unmodified line
953 stream = FlushableTextStream()954955 @contextlib.contextmanager956 def pager_contextmanager(color=None):957 yield stream, "utf-8", color957 yield stream, False958959 monkeypatch.setattr(960 click._termui_impl, "_pager_contextmanager", pager_contextmanager961 )962963 with pytest.raises(RuntimeError, match="boom"):964 with click.get_pager_file() as pager:965 assert pager is stream965 pager.write("partial")966 raise RuntimeError("boom")967968 assert stream.flush_calls == 1969 assert stream.getvalue() == "partial"970971972def test_get_pager_file_close_does_not_close_borrowed_stream(monkeypatch):973 """Closing the yielded pager must not close a stream the caller owns.974975 ``_PagerWriter.close()`` flushes but deliberately stops there: each pager976 strategy owns its stream's lifecycle. This is the caller-driven half of977 ``test_get_pager_file_missing_pager_keeps_borrowed_stream_open``, which978 covers the same fallback but never calls ``close`` itself.979980 Wrapping the borrowed stream in :class:`~click.utils._KeepOpenFile` does not981 satisfy this: that proxy only covers a ``with`` block and passes an explicit982 ``close`` straight through. Only the writer's own ``close`` stops it.983 """984 stream = io.StringIO()985 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)986 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)987 # A tty plus a ``PAGER`` that doesn't resolve sends us through the988 # ``_pipepager`` (or ``_tempfilepager``) missing-binary fallback branch.989 monkeypatch.setitem(990 click._termui_impl.os.environ,991 "PAGER",992 "click-tests-nonexistent-pager-9b3f2",993 )994995 with click.get_pager_file() as pager:996 pager.write("hello\n")997 pager.close()998 assert not stream.closed9991000 assert not stream.closed1001 assert stream.getvalue() == "hello\n"100210031004def _force_tempfile_pager(monkeypatch, pager_cmd="cat"):1005 """Route ``get_pager_file`` through the ``_tempfilepager`` backend.10061007 That backend is only reachable on Windows, so the platform flag and the tty
30 unmodified lines
1038)1039def test_tempfile_pager_accepts_text(monkeypatch, capfd, page):1040 """The temp file backend must yield a text stream (issues #3731, #3740).10411009 ``_tempfilepager`` opens its temp file in binary mode and yields the1010 ``_TemporaryFileWrapper`` straight to ``get_pager_file``. That wrapper1011 exposes no ``.buffer``, so the ``_has_binary_buffer`` probe is False and no1012 ``MaybeStripAnsi`` wrapper is installed. The caller then writes ``str`` to a1013 binary handle and gets ``TypeError: a bytes-like object is required``.1042 Regression: a binary-mode temp file handed straight to ``get_pager_file``1043 left the caller writing ``str`` to a binary handle, which raises1044 ``TypeError: a bytes-like object is required``.1045 """1046 _force_tempfile_pager(monkeypatch)10471048 page()
13 unmodified lines
1062)1063def test_tempfile_pager_handles_ansi(monkeypatch, capfd, color, expected):1064 """The temp file backend honors ``color`` like the pipe backend does.10651035 ANSI stripping lives in ``MaybeStripAnsi``, which the binary temp file1036 never gets wrapped in, so ``color`` is silently ignored on this path.1066 Regression: a binary temp file got no ANSI-stripping wrapper, so ``color``1067 was silently ignored on this path.1068 """1069 _force_tempfile_pager(monkeypatch)10701071 click.echo_via_pager(click.style("hello", fg="red"), color=color)
730 unmodified lines
modified:CHANGES.md+4 added
77 unmodified lines
78 `PermissionError: [WinError 32]` on Windows. The temporary file backend79 unlinked its file without closing it first, and Windows refuses to remove a80 file the process still holds open, so the cleanup failure masked the real81 exception. {issue}`3731` {pr}`3764`82- The temporary file the pager writes to on Windows is opened with the encoding83 {func}`get_pager_file` picked for the output stream, and with84 `errors="replace"` to match the pipe backend. Any text stdout can encode85 reaches the pager.8687## Version 8.4.28889Released 2026-06-24
1561 unmodified lines