Add file-like pager: `click.get_pager_file()` (#1572)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Craig de Stigter · committed by GitHub · parent c5cced7 · Browse files · 7 files·+136 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Diff stats
7 files+136 added−72 removed
- other:+136 added−72 removed
Provenance
- Commit
c69643b- Tree
9335e09- Author
Craig de Stigter <craig@destigter.nz>- Committer
GitHub <noreply@github.com>- Parent
c5cced7
7 files changed+136 added−72 removed
modified:docs/api.md+4 added
71 unmodified lines72 .. autofunction:: echo_via_pager73 ```74 75 ```{eval-rst}76+.. autofunction:: get_pager_file77+```78+79+```{eval-rst}80 .. autofunction:: prompt81 ```82 83 ```{eval-rst}274 unmodified linesmodified:docs/utils.md+13 added
108 unmodified lines109 def less():110 click.echo_via_pager(_generate_output())111 ```112 113+For more complex programs, which can't easily use a simple generator, you114+can get access to a writable file-like object for the pager, and write to115+that instead:116+117+```{eval-rst}118+.. click:example::119+ @click.command()120+ def less():121+ with click.get_pager_file() as pager:122+ for idx in range(50000):123+ print(idx, file=pager)124+```125+126 ## Screen Clearing127 128 ```{versionadded} 2.0129 ```276 unmodified linesmodified:src/click/__init__.py+1 added
40 unmodified lines41 from .termui import clear as clear42 from .termui import confirm as confirm43 from .termui import echo_via_pager as echo_via_pager44 from .termui import edit as edit45+from .termui import get_pager_file as get_pager_file46 from .termui import getchar as getchar47 from .termui import launch as launch48 from .termui import pause as pause49 from .termui import progressbar as progressbar76 unmodified linesmodified:src/click/_compat.py+4 added
500 unmodified lines501 ) -> bool:502 if color is None:503 if stream is None:504 stream = sys.stdin505+ elif hasattr(stream, "color"):506+ # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,507+ # so we don't need to strip it here508+ return False509 return not isatty(stream) and not _is_jupyter_kernel_output(stream)510 return not color511 512 114 unmodified linesmodified:src/click/_termui_impl.py+90 added-68 removed
6 unmodified lines7 from __future__ import annotations8 9 import collections.abc as cabc10 import contextlib11+import io12 import math13 import os14 import shlex15 import sys7 unmodified lines23 from ._compat import _default_text_stdout24 from ._compat import CYGWIN25 from ._compat import get_best_encoding26 from ._compat import isatty26-from ._compat import open_stream27 from ._compat import strip_ansi28 from ._compat import term_len29 from ._compat import WIN30 from .exceptions import ClickException334 unmodified lines365 self.finish()366 self.render_progress()367 368 369-def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:369+class MaybeStripAnsi(io.TextIOWrapper):370+ def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):371+ super().__init__(stream, **kwargs)372+ self.color = color373+374+ def write(self, text: str) -> int:375+ if not self.color:376+ text = strip_ansi(text)377+ return super().write(text)378+379+380+def _pager_contextmanager(381+ color: bool | None = None,382+) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:383 """Decide what method to use for paging through text."""384 stdout = _default_text_stdout()385 386 # There are no standard streams attached to write to. For example,1 unmodified line388 if stdout is None:389 stdout = StringIO()390 391 if not isatty(sys.stdin) or not isatty(stdout):379- return _nullpager(stdout, generator, color)392+ return _nullpager(stdout, color)393 394 # Split using POSIX mode (the default) so that quote characters are395 # stripped from tokens and quoted Windows paths are preserved.396 # Non-POSIX mode retains quotes in tokens, and wrapping tokens397 # with shlex.quote re-introduces quoting issues on Windows.398 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))399 if pager_cmd_parts:400 if WIN:388- if _tempfilepager(generator, pager_cmd_parts, color):389- return390- elif _pipepager(generator, pager_cmd_parts, color):391- return401+ return _tempfilepager(pager_cmd_parts, color)402+ return _pipepager(pager_cmd_parts, color)403 404 if os.environ.get("TERM") in ("dumb", "emacs"):394- return _nullpager(stdout, generator, color)395- if (WIN or sys.platform.startswith("os2")) and _tempfilepager(396- generator, ["more"], color397- ):398- return399- if _pipepager(generator, ["less"], color):400- return405+ return _nullpager(stdout, color)406+ if WIN or sys.platform.startswith("os2"):407+ return _tempfilepager(["more"], color)408+ return _pipepager(["less"], color)409 402- import tempfile410 404- fd, filename = tempfile.mkstemp()405- os.close(fd)406- try:407- if _pipepager(generator, ["more"], color):408- return409- return _nullpager(stdout, generator, color)410- finally:411- os.unlink(filename)411+@contextlib.contextmanager412+def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:413+ """Context manager.414+ Yields a writable file-like object which can be used as an output pager.415+ .. versionadded:: 8.2416+ :param color: controls if the pager supports ANSI colors or not. The417+ default is autodetection.418+ """419+ with _pager_contextmanager(color=color) as (stream, encoding, color):420+ if not isinstance(stream, MaybeStripAnsi):421+ if hasattr(stream, "buffer"):422+ # Real TextIO with buffer - unwrap and wrap in MaybeStripAnsi423+ stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)424+ elif not getattr(stream, "encoding", None):425+ # BinaryIO - wrap directly in MaybeStripAnsi426+ stream = MaybeStripAnsi(stream, color=color, encoding=encoding)427+ else:428+ # StringIO - add .color attribute only, no ANSI stripping429+ stream.color = color # type: ignore[attr-defined]430+ try:431+ yield t.cast(t.TextIO, stream)432+ finally:433+ stream.flush()434 435 436+@contextlib.contextmanager437 def _pipepager(415- generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None416-) -> bool:438+ cmd_parts: list[str], color: bool | None = None439+) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:440 """Page through text by feeding it to another program.441 442 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list443 produced by :func:`shlex.split`. The command is resolved to an absolute2 unmodified lines446 447 Invoking a pager through this might support colors: if piping to448 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set449 automatically.427-428- Returns ``True`` if the command was found and executed, ``False``429- otherwise so another pager can be attempted.450 """451 # Split the command into the invoked CLI and its parameters.452 if not cmd_parts:453+ stdout = _default_text_stdout() or StringIO()454+ yield stdout, "utf-8", False433- return False455+ return456 457 import shutil458 459 cmd = cmd_parts[0]460 cmd_params = cmd_parts[1:]461 462 cmd_filepath = shutil.which(cmd)463 if not cmd_filepath:464+ stdout = _default_text_stdout() or StringIO()465+ yield stdout, "utf-8", False442- return False466+ return467 468 # Produces a normalized absolute path string.469 # multi-call binaries such as busybox derive their identity from the symlink470 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)14 unmodified lines485 color = True486 elif "r" in less_flags or "R" in less_flags:487 color = True488 489+ if color is None:490+ color = False491+492 c = subprocess.Popen(493 [str(cmd_path)] + cmd_params,494 shell=False,495 stdin=subprocess.PIPE,496 env=env,497 errors="replace",498 text=True,499 )473- assert c.stdin is not None500+ stdin = t.cast(t.BinaryIO, c.stdin)501+ encoding = get_best_encoding(stdin)502 try:475- for text in generator:476- if not color:477- text = strip_ansi(text)478-479- c.stdin.write(text)503+ yield stdin, encoding, color504 except BrokenPipeError:505 # In case the pager exited unexpectedly, ignore the broken pipe error.506 pass507 except Exception as e:5 unmodified lines513 raise e514 finally:515 # We must close stdin and wait for the pager to exit before we continue516 try:493- c.stdin.close()517+ stdin.close()518 # Close implies flush, so it might throw a BrokenPipeError if the pager519 # process exited already.520 except BrokenPipeError:521 pass13 unmodified lines535 pass536 else:537 break538 515- return True539 517-540+@contextlib.contextmanager541 def _tempfilepager(519- generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None520-) -> bool:542+ cmd_parts: list[str], color: bool | None = None543+) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:544 """Page through text by invoking a program on a temporary file.545 546 Used as the primary pager strategy on Windows (where piping to547 ``more`` adds spurious ``\\r\\n``), and as a fallback on other548 platforms. The command is resolved to an absolute path with549 :func:`shutil.which`.527-528- Returns ``True`` if the command was found and executed, ``False``529- otherwise so another pager can be attempted.550 """551 # Split the command into the invoked CLI and its parameters.552 if not cmd_parts:553+ stdout = _default_text_stdout() or StringIO()554+ yield stdout, "utf-8", False533- return False555+ return556 557 import shutil558+ import subprocess559 560 cmd = cmd_parts[0]561 562 cmd_filepath = shutil.which(cmd)563 if not cmd_filepath:564+ stdout = _default_text_stdout() or StringIO()565+ yield stdout, "utf-8", False541- return False566+ return567+568 # Produces a normalized absolute path string.569 # multi-call binaries such as busybox derive their identity from the symlink570 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)571 cmd_path = Path(cmd_filepath).absolute()572 547- import subprocess573 import tempfile574 550- fd, filename = tempfile.mkstemp()551- # TODO: This never terminates if the passed generator never terminates.552- text = "".join(generator)553- if not color:554- text = strip_ansi(text)575 encoding = get_best_encoding(sys.stdout)556- with open_stream(filename, "wb")[0] as f:557- f.write(text.encode(encoding))576+ if color is None:577+ color = False578+ # On Windows, NamedTemporaryFile cannot be opened by another process579+ # while Python still has it open, so we use delete=False and clean up manually580+ # rather than using a contextmanager here.581+ f = tempfile.NamedTemporaryFile(mode="wb", delete=False)582 try:559- subprocess.call([str(cmd_path), filename])560- except OSError:561- # Command not found562- pass583+ yield t.cast(t.BinaryIO, f), encoding, color584+ f.flush()585+ f.close()586+ subprocess.call([str(cmd_path), f.name])587 finally:564- os.close(fd)565- os.unlink(filename)588+ os.unlink(f.name)589 567- return True590 569-591+@contextlib.contextmanager592 def _nullpager(571- stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None572-) -> None:593+ stream: t.TextIO, color: bool | None = None594+) -> t.Iterator[tuple[t.TextIO, str, bool]]:595 """Simply print unformatted text. This is the ultimate fallback."""574- for text in generator:575- if not color:576- text = strip_ansi(text)577- stream.write(text)596+ encoding = get_best_encoding(stream)597+ if color is None:598+ color = False599+ yield stream, encoding, color600 601 602 class Editor:603 def __init__(288 unmodified linesmodified:src/click/termui.py+22 added-4 removed
276 unmodified lines277 raise Abort()278 return rv279 280 281+def get_pager_file(282+ color: bool | None = None,283+) -> t.ContextManager[t.TextIO]:284+ """Context manager.285+286+ Yields a writable file-like object which can be used as an output pager.287+288+ .. versionadded:: 8.2289+290+ :param color: controls if the pager supports ANSI colors or not. The291+ default is autodetection.292+ """293+ from ._termui_impl import get_pager_file294+295+ color = resolve_color_default(color)296+297+ return get_pager_file(color=color)298+299+300 def echo_via_pager(301 text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,302 color: bool | None = None,303 ) -> None:7 unmodified lines311 generator emitting the text to page.312 :param color: controls if the pager supports ANSI colors or not. The313 default is autodetection.314 """296- color = resolve_color_default(color)315 316 if inspect.isgeneratorfunction(text_or_generator):317 i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()318 elif isinstance(text_or_generator, str):3 unmodified lines322 323 # convert every element of i to a text type if necessary324 text_generator = (el if isinstance(el, str) else str(el) for el in i)325 308- from ._termui_impl import pager326+ with get_pager_file(color=color) as pager:327+ for text in itertools.chain(text_generator, "\n"):328+ pager.write(text)329 310- return pager(itertools.chain(text_generator, "\n"), color)330 312-331 @t.overload332 def progressbar(333 *,334 length: int,587 unmodified linesmodified:CHANGES.rst+2 added
256 unmodified lines257 - ``echo_via_pager`` will not ignore ``KeyboardInterrupt`` anymore. This258 allows the user to search for future output of the generator when259 using less and then aborting the program using ctrl-c.260 261+- Add ``click.get_pager_file`` for file-like access to an output262+ pager. :pr:`1572`263 - ``deprecated: bool | str`` can now be used on options and arguments. This264 previously was only available for ``Command``. The message can now also be265 customised by using a ``str`` instead of a ``bool``. :issue:`2263` :pr:`2271`266 1151 unmodified lines