Do not let the GC close a borrowed `stdout` (#3533)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents cd9bdd9, 051bb0f · Browse files · 4 files·+112 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+112 added−27 removed
- tests:+56 added−0 removed
- other:+56 added−27 removed
Provenance
- Commit
4df304c- Tree
a032e95- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
cd9bdd9- Parent 2
051bb0f
4 files changed+112 added−27 removed
modified:src/click/_termui_impl.py+40 added-27 removed
27 unmodified lines28 from ._compat import term_len29 from ._compat import WIN30 from .exceptions import ClickException31 from .utils import echo32+from .utils import KeepOpenFile33 34 V = t.TypeVar("V")35 36 404 unmodified lines441 """442 with _pager_contextmanager(color=color) as (stream, encoding, color):443 # Split streams by capabilities rather than the abstract TextIO /444 # BinaryIO annotations: buffered text streams can be unwrapped to bytes,444- # while text-only streams are yielded as-is.445+ # while other streams are yielded as-is.446+ wrapper: MaybeStripAnsi | None = None447 if _has_binary_buffer(stream):448 # Text stream backed by a binary buffer.447- stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)448- elif isinstance(stream, t.BinaryIO):449- # Binary stream450- stream = MaybeStripAnsi(stream, color=color, encoding=encoding)449+ wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)450+ stream = wrapper451 try:452- yield stream452+ # Narrow the BinaryIO | TextIO union that _pager_contextmanager453+ # yields; the caller writes text to the pager.454+ yield t.cast(t.TextIO, stream)455 finally:456+ try:454- stream.flush()457+ stream.flush()458+ finally:459+ # Hand the binary buffer back to the pager that produced it460+ # rather than letting this TextIOWrapper close it on garbage461+ # collection. The pager owns the buffer's lifecycle: subprocess462+ # pipes and temp files are closed by their own helpers, while a463+ # borrowed stdout must stay open for the caller. detach() runs464+ # even if flush() raised, so the buffer is never closed here.465+ if wrapper is not None:466+ wrapper.detach()467 468 469 @contextlib.contextmanager470 def _pipepager(11 unmodified lines482 automatically.483 """484 # Split the command into the invoked CLI and its parameters.485 if not cmd_parts:486+ # No usable pager: fall back to stdout through _nullpager so it gets the487+ # same borrowed-stream handling and the caller's stream is not closed.488 stdout = _default_text_stdout() or StringIO()475- yield stdout, "utf-8", False489+ with _nullpager(stdout, color) as rv:490+ yield rv491 return492 493 import shutil494 1 unmodified line496 cmd_params = cmd_parts[1:]497 498 cmd_filepath = shutil.which(cmd)499 if not cmd_filepath:500+ # No usable pager: fall back to stdout through _nullpager so it gets the501+ # same borrowed-stream handling and the caller's stream is not closed.502 stdout = _default_text_stdout() or StringIO()486- yield stdout, "utf-8", False503+ with _nullpager(stdout, color) as rv:504+ yield rv505 return506 507 # Produces a normalized absolute path string.508 # multi-call binaries such as busybox derive their identity from the symlink79 unmodified lines588 :func:`shutil.which`.589 """590 # Split the command into the invoked CLI and its parameters.591 if not cmd_parts:592+ # No usable pager: fall back to stdout through _nullpager so it gets the593+ # same borrowed-stream handling and the caller's stream is not closed.594 stdout = _default_text_stdout() or StringIO()575- yield stdout, "utf-8", False595+ with _nullpager(stdout, color) as rv:596+ yield rv597 return598 599 import shutil600 import subprocess1 unmodified line602 cmd = cmd_parts[0]603 604 cmd_filepath = shutil.which(cmd)605 if not cmd_filepath:606+ # No usable pager: fall back to stdout through _nullpager so it gets the607+ # same borrowed-stream handling and the caller's stream is not closed.608 stdout = _default_text_stdout() or StringIO()586- yield stdout, "utf-8", False609+ with _nullpager(stdout, color) as rv:610+ yield rv611 return612 613 # Produces a normalized absolute path string.614 # multi-call binaries such as busybox derive their identity from the symlink17 unmodified lines632 finally:633 os.unlink(f.name)634 635 612-class _SkipClose:613- def __init__(self, stream: t.IO[t.Any]) -> None:614- self.stream = stream615-616- def __getattr__(self, name: str) -> t.Any:617- return getattr(self.stream, name)618-619- @property620- def buffer(self) -> t.BinaryIO:621- return _SkipClose(self.stream.buffer) # type: ignore[attr-defined, return-value]622-623- def close(self) -> None:624- pass625-626-636 @contextlib.contextmanager637 def _nullpager(638 stream: t.TextIO, color: bool | None = None639 ) -> t.Iterator[tuple[t.TextIO, str, bool]]:640 """Simply print unformatted text. This is the ultimate fallback. Don't close the641 output stream in this case, since it's coming from elsewhere rather than our642 internal helpers.643+644+ The stream is wrapped in :class:`~click.utils.KeepOpenFile` so that, as a645+ borrowed stream, it is not closed by a ``with`` block. The wrapper that646+ :func:`get_pager_file` builds around it is detached rather than closed.647 """648 encoding = get_best_encoding(stream)649 650 if color is None:651 color = False652 640- yield _SkipClose(stream), encoding, color # type: ignore[misc]653+ yield KeepOpenFile(stream), encoding, color # type: ignore[misc]654 655 656 class Editor:657 def __init__(288 unmodified linesmodified:src/click/utils.py+12 added
203 unmodified lines204 return iter(self._f) # type: ignore205 206 207 class KeepOpenFile:208+ """Proxy a file object but keep it open across a ``with`` block.209+210+ Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that211+ leaving a ``with`` block does not close it, as used by :func:`open_file`212+ for the ``-`` filename. The caller stays responsible for the file: an213+ explicit :meth:`close` still passes through to the wrapped object.214+215+ Dunder methods are proxied explicitly: implicit special-method lookups216+ bypass :meth:`__getattr__`, because Python resolves them on the type rather217+ than the instance.218+ """219+220 _file: t.IO[t.Any]221 222 def __init__(self, file: t.IO[t.Any]) -> None:223 self._file = file430 unmodified linesmodified:tests/test_termui.py+56 added
1 import contextlib2+import gc3 import io4 import platform5 import shlex6 import shutil799 unmodified lines806 807 assert pager_out.read_text(encoding="utf-8") == "hello\n"808 809 810+def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):811+ """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).812+813+ The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path;814+ the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when815+ ``PAGER`` resolves to nothing) used to close the borrowed stream too.816+ """817+ buffer = io.BytesIO()818+ stream = io.TextIOWrapper(buffer, encoding="utf-8")819+820+ monkeypatch.setitem(821+ click._termui_impl.os.environ,822+ "PAGER",823+ "click-tests-nonexistent-pager-9b3f2",824+ )825+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)826+ monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)827+828+ with click.get_pager_file() as pager:829+ pager.write("hello\n")830+831+ # Drop the wrapper reference and force finalization: the old bug closed the832+ # borrowed buffer when the TextIOWrapper built by get_pager_file was833+ # garbage-collected.834+ del pager835+ gc.collect()836+837+ assert not buffer.closed838+ assert not stream.closed839+ assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"840+841+842+def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):843+ """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.844+845+ Regression for issue #3449 via the pager fallback: a tty with ``PAGER``846+ pointing at a missing binary used to close the runner's stdout, breaking847+ ``CliRunner.invoke``.848+ """849+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)850+ monkeypatch.setitem(851+ click._termui_impl.os.environ,852+ "PAGER",853+ "click-tests-nonexistent-pager-9b3f2",854+ )855+856+ @click.command()857+ def cli():858+ click.echo_via_pager("Hello, Click!")859+860+ result = runner.invoke(cli)861+ assert not result.exception862+ assert result.output == "Hello, Click!\n"863+864+865 @pytest.mark.parametrize(866 ("color", "expected"),867 [868 pytest.param(False, "hello\n", id="strip ansi"),694 unmodified linesmodified:CHANGES.rst+4 added
15 unmodified lines16 :issue:`3059` :pr:`3507`17 - ``echo_via_pager`` flushes after each write, so passing a generator streams18 output to the pager incrementally instead of staying hidden until the pipe19 buffer fills. :issue:`3242` :issue:`2542` :pr:`3534`20+- ``echo_via_pager`` and ``get_pager_file`` no longer close a borrowed stdout21+ stream when no external pager runs, completing the partial22+ ``I/O operation on closed file`` fix from :pr:`3482`. :issue:`3449`23+ :pr:`3533`24 25 26 Version 8.4.127 -------------1478 unmodified lines