88
99import collections .abc as cabc
1010import contextlib
11- import io
1211import math
1312import os
1413import shlex
2827from ._compat import term_len
2928from ._compat import WIN
3029from .exceptions import ClickException
31- from .utils import _KeepOpenFile
3230from .utils import echo
3331
3432V = t .TypeVar ("V" )
3533
3634
37- class _BufferedTextPagerStream (t .Protocol ):
38- buffer : t .BinaryIO
39-
40-
41- def _has_binary_buffer (
42- stream : t .BinaryIO | t .TextIO ,
43- ) -> t .TypeGuard [_BufferedTextPagerStream ]:
44- # TextIO is wider than TextIOWrapper; text-only streams such as StringIO
45- # are valid TextIO values but do not expose a binary buffer to wrap.
46- return getattr (stream , "buffer" , None ) is not None
47-
48-
4935if os .name == "nt" :
5036 BEFORE_BAR = "\r "
5137 AFTER_BAR = "\n "
@@ -394,20 +380,49 @@ def generator(self) -> cabc.Iterator[V]:
394380 self .render_progress ()
395381
396382
397- class MaybeStripAnsi (io .TextIOWrapper ):
398- def __init__ (self , stream : t .IO [bytes ], * , color : bool , ** kwargs : t .Any ):
399- super ().__init__ (stream , ** kwargs )
383+ class _PagerWriter :
384+ """Wrap a pager's output stream to strip ANSI styling when colors are
385+ disabled.
386+
387+ The wrapped stream is owned by the pager strategy that produced it, so this
388+ wrapper never closes it: ``_pipepager`` closes its pipe to signal EOF to the
389+ pager process, ``_tempfilepager`` closes and removes its temporary file, and
390+ ``_nullpager`` leaves an external stream such as ``sys.stdout`` untouched.
391+
392+ The ``color`` attribute lets :func:`click.echo` detect that ANSI stripping
393+ is handled here, so it doesn't strip a second time (see
394+ :func:`._compat.should_strip_ansi`).
395+ """
396+
397+ def __init__ (self , stream : t .TextIO , color : bool ) -> None :
398+ self ._stream = stream
400399 self .color = color
401400
402401 def write (self , text : str ) -> int :
403402 if not self .color :
404403 text = strip_ansi (text )
405- return super ().write (text )
404+
405+ return self ._stream .write (text )
406+
407+ def writelines (self , lines : cabc .Iterable [str ]) -> None :
408+ for line in lines :
409+ self .write (line )
410+
411+ def flush (self ) -> None :
412+ self ._stream .flush ()
413+
414+ 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 ()
418+
419+ def __getattr__ (self , name : str ) -> t .Any :
420+ return getattr (self ._stream , name )
406421
407422
408423def _pager_contextmanager (
409424 color : bool | None = None ,
410- ) -> t .ContextManager [tuple [t .BinaryIO | t . TextIO , str , bool ]]:
425+ ) -> t .ContextManager [tuple [t .TextIO , bool ]]:
411426 """Decide what method to use for paging through text."""
412427 stdout = _default_text_stdout ()
413428
@@ -447,37 +462,21 @@ def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, Non
447462 :param color: controls if the pager supports ANSI colors or not. The
448463 default is autodetection.
449464 """
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 = None
455- if _has_binary_buffer (stream ):
456- # Text stream backed by a binary buffer.
457- wrapper = MaybeStripAnsi (stream .buffer , color = color , encoding = encoding )
458- stream = wrapper
465+ with _pager_contextmanager (color = color ) as (stream , color ):
466+ # Every pager strategy yields a text stream, so the only thing left to
467+ # do is strip ANSI styling when colors are disabled. The wrapper does
468+ # not close the stream: each strategy owns its stream's lifecycle.
469+ writer = _PagerWriter (stream , color = color )
459470 try :
460- # Narrow the BinaryIO | TextIO union that _pager_contextmanager
461- # yields; the caller writes text to the pager.
462- yield t .cast (t .TextIO , stream )
471+ yield t .cast (t .TextIO , writer )
463472 finally :
464- try :
465- stream .flush ()
466- finally :
467- # Hand the binary buffer back to the pager that produced it
468- # rather than letting this TextIOWrapper close it on garbage
469- # collection. The pager owns the buffer's lifecycle: subprocess
470- # pipes and temp files are closed by their own helpers, while a
471- # borrowed stdout must stay open for the caller. detach() runs
472- # even if flush() raised, so the buffer is never closed here.
473- if wrapper is not None :
474- wrapper .detach ()
473+ writer .flush ()
475474
476475
477476@contextlib .contextmanager
478477def _pipepager (
479478 cmd_parts : list [str ], color : bool | None = None
480- ) -> t .Iterator [tuple [t .BinaryIO | t . TextIO , str , bool ]]:
479+ ) -> t .Iterator [tuple [t .TextIO , bool ]]:
481480 """Page through text by feeding it to another program.
482481
483482 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list
@@ -544,10 +543,11 @@ def _pipepager(
544543 errors = "replace" ,
545544 text = True ,
546545 )
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 encodes
547+ # writes for the pager process (honoring ``errors="replace"``).
548+ stdin = t .cast (t .TextIO , c .stdin )
549549 try :
550- yield stdin , encoding , color
550+ yield stdin , color
551551 except BrokenPipeError :
552552 # In case the pager exited unexpectedly, ignore the broken pipe error.
553553 pass
@@ -587,7 +587,7 @@ def _pipepager(
587587@contextlib .contextmanager
588588def _tempfilepager (
589589 cmd_parts : list [str ], color : bool | None = None
590- ) -> t .Iterator [tuple [t .BinaryIO | t . TextIO , str , bool ]]:
590+ ) -> t .Iterator [tuple [t .TextIO , bool ]]:
591591 """Page through text by invoking a program on a temporary file.
592592
593593 Used as the primary pager strategy on Windows (where piping to
@@ -631,9 +631,11 @@ def _tempfilepager(
631631 # On Windows, NamedTemporaryFile cannot be opened by another process
632632 # while Python still has it open, so we use delete=False and clean up manually
633633 # 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 = False
636+ )
635637 try :
636- yield t .cast (t .BinaryIO , f ), encoding , color
638+ yield t .cast (t .TextIO , f ), color
637639 f .flush ()
638640 f .close ()
639641 subprocess .call ([str (cmd_path ), f .name ])
@@ -649,21 +651,17 @@ def _tempfilepager(
649651@contextlib .contextmanager
650652def _nullpager (
651653 stream : t .TextIO , color : bool | None = None
652- ) -> t .Iterator [tuple [t .TextIO , str , bool ]]:
653- """Simply print unformatted text. This is the ultimate fallback. Don't close the
654- output stream in this case, since it's coming from elsewhere rather than our
655- internal helpers.
656-
657- The stream is wrapped in :class:`~click.utils._KeepOpenFile` so that, as a
658- borrowed stream, it is not closed by a ``with`` block. The wrapper that
659- :func:`get_pager_file` builds around it is detached rather than closed.
660- """
661- encoding = get_best_encoding (stream )
654+ ) -> t .Iterator [tuple [t .TextIO , bool ]]:
655+ """Simply print unformatted text. This is the ultimate fallback.
662656
657+ The stream comes from elsewhere (typically ``sys.stdout``), so its lifecycle
658+ is left untouched: :class:`_PagerWriter` never closes what it wraps, and it
659+ is the only thing :func:`get_pager_file` hands to the caller.
660+ """
663661 if color is None :
664662 color = False
665663
666- yield _KeepOpenFile ( stream ), encoding , color # type: ignore[misc]
664+ yield stream , color
667665
668666
669667class Editor :
0 commit comments