Skip to content
Myr

Resolve the pager command once, in `_pager_contextmanager` (#3776)

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

authored by Rowlando13 · committed by GitHub · parents f36d58b, 9835b0f · Browse files · 1 file+64 added−87 removed
This commit

State

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

Diff stats

1 file+64 added−87 removed

  • other:+64 added−87 removed

1 file+64 added−87 removed

modified:src/click/_termui_impl.py+64 added-87 removed
418 unmodified lines
419 def __getattr__(self, name: str) -> t.Any:420 return getattr(self._stream, name)421422423def _resolve_pager_command(cmd_parts: list[str]) -> tuple[Path, list[str]] | None:424 """Resolve a pager ``argv`` to an absolute command path and its parameters.425426 The command is looked up with :func:`shutil.which`, which the427 :mod:`subprocess` docs recommend on every platform for an unqualified name:428 https://docs.python.org/3/library/subprocess.html#popen-constructor429430 Returns ``None`` when there is no command to run or it is not on the path,431 leaving the caller to pick a fallback.432 """433 if not cmd_parts:434 return None435436 import shutil437438 cmd_filepath = shutil.which(cmd_parts[0])439440 if not cmd_filepath:441 return None442443 # Normalize to an absolute path without resolving symlinks: multi-call444 # binaries such as busybox derive their identity from the link they are445 # invoked through, so resolving less -> busybox makes them misbehave.446 # See https://github.com/pallets/click/issues/2943 and447 # https://github.com/pallets/click/pull/2944448 return Path(cmd_filepath).absolute(), cmd_parts[1:]449450451def _pager_contextmanager(452 color: bool | None = None,425) -> t.ContextManager[tuple[t.TextIO, bool]]:453) -> t.ContextManager[tuple[t.TextIO, bool | None]]:454 """Decide what method to use for paging through text."""455 stdout = _default_text_stdout()456457 # There are no standard streams attached to write to. For example,
8 unmodified lines
466 # stripped from tokens and quoted Windows paths are preserved.467 # Non-POSIX mode retains quotes in tokens, and wrapping tokens468 # with shlex.quote re-introduces quoting issues on Windows.469 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))470471 if pager_cmd_parts:443 if WIN:444 return _tempfilepager(pager_cmd_parts, color)445 return _pipepager(pager_cmd_parts, color)472 # Piping to `more` on Windows adds spurious \r\n, so it gets the temp473 # file strategy whatever the user asked for.474 use_tempfile = WIN475 else:476 if os.environ.get("TERM") in ("dumb", "emacs"):477 return _nullpager(stdout, color)478447 if os.environ.get("TERM") in ("dumb", "emacs"):479 use_tempfile = WIN or sys.platform.startswith("os2")480 pager_cmd_parts = ["more"] if use_tempfile else ["less"]481482 resolved = _resolve_pager_command(pager_cmd_parts)483484 if resolved is None:485 # Page through stdout, which _nullpager leaves open for its owner.486 return _nullpager(stdout, color)449 if WIN or sys.platform.startswith("os2"):450 return _tempfilepager(["more"], color)451 return _pipepager(["less"], color)487488 cmd_path, cmd_params = resolved489490 if use_tempfile:491 return _tempfilepager(cmd_path, color)492493 return _pipepager(cmd_path, cmd_params, color)494495496@contextlib.contextmanager497def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:498 """Context manager.499
5 unmodified lines
505 default is autodetection.506 """507 with _pager_contextmanager(color=color) as (stream, color):508 # 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)509 # do is strip ANSI styling when colors are disabled. A strategy yields510 # None when it has no opinion on colors, which settles as off here. The511 # wrapper does not close the stream: each strategy owns its stream's512 # lifecycle.513 writer = _PagerWriter(stream, color=bool(color))514 try:515 yield t.cast(t.TextIO, writer)516 finally:517 writer.flush()518519520@contextlib.contextmanager521def _pipepager(478 cmd_parts: list[str], color: bool | None = None479) -> t.Iterator[tuple[t.TextIO, bool]]:522 cmd_path: Path, cmd_params: list[str], color: bool | None = None523) -> t.Iterator[tuple[t.TextIO, bool | None]]:524 """Page through text by feeding it to another program.525482 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list483 produced by :func:`shlex.split`. The command is resolved to an absolute484 path with :func:`shutil.which` as recommended by the485 :mod:`subprocess` docs for Windows compatibility.526 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list.527528 Invoking a pager through this might support colors: if piping to529 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set530 automatically.531 """491 # Split the command into the invoked CLI and its parameters.492 if not cmd_parts:493 # No usable pager: fall back to stdout through _nullpager so it gets the494 # same borrowed-stream handling and the caller's stream is not closed.495 stdout = _default_text_stdout() or StringIO()496 with _nullpager(stdout, color) as rv:497 yield rv498 return499500 import shutil501502 cmd = cmd_parts[0]503 cmd_params = cmd_parts[1:]504505 cmd_filepath = shutil.which(cmd)506 if not cmd_filepath:507 # No usable pager: fall back to stdout through _nullpager so it gets the508 # same borrowed-stream handling and the caller's stream is not closed.509 stdout = _default_text_stdout() or StringIO()510 with _nullpager(stdout, color) as rv:511 yield rv512 return513514 # Produces a normalized absolute path string.515 # multi-call binaries such as busybox derive their identity from the symlink516 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)517 cmd_path = Path(cmd_filepath).absolute()518 cmd_name = cmd_path.name519532 import subprocess533534 # Make a local copy of the environment to not affect the global one.535 env = dict(os.environ)536537 # If we're piping to less and the user hasn't decided on colors, we enable538 # them by default we find the -R flag in the command line arguments.527 if color is None and cmd_name == "less":539 if color is None and cmd_path.name == "less":540 less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"541 if not less_flags:542 env["LESS"] = "-R"543 color = True544 elif "r" in less_flags or "R" in less_flags:545 color = True546535 if color is None:536 color = False537547 c = subprocess.Popen(548 [str(cmd_path)] + cmd_params,549 shell=False,550 stdin=subprocess.PIPE,
43 unmodified lines
594595596@contextlib.contextmanager597def _tempfilepager(589 cmd_parts: list[str], color: bool | None = None590) -> t.Iterator[tuple[t.TextIO, bool]]:598 cmd_path: Path, color: bool | None = None599) -> t.Iterator[tuple[t.TextIO, bool | None]]:600 """Page through text by invoking a program on a temporary file.601602 Used as the primary pager strategy on Windows (where piping to603 ``more`` adds spurious ``\\r\\n``), and as a fallback on other595 platforms. The command is resolved to an absolute path with596 :func:`shutil.which`.604 platforms. The command is invoked with the temporary file as its only605 argument: any parameters the user set in ``PAGER`` are not passed on.606 """598 # Split the command into the invoked CLI and its parameters.599 if not cmd_parts:600 # No usable pager: fall back to stdout through _nullpager so it gets the601 # same borrowed-stream handling and the caller's stream is not closed.602 stdout = _default_text_stdout() or StringIO()603 with _nullpager(stdout, color) as rv:604 yield rv605 return606607 import shutil607 import subprocess609610 cmd = cmd_parts[0]611612 cmd_filepath = shutil.which(cmd)613 if not cmd_filepath:614 # No usable pager: fall back to stdout through _nullpager so it gets the615 # same borrowed-stream handling and the caller's stream is not closed.616 stdout = _default_text_stdout() or StringIO()617 with _nullpager(stdout, color) as rv:618 yield rv619 return620621 # Produces a normalized absolute path string.622 # multi-call binaries such as busybox derive their identity from the symlink623 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)624 cmd_path = Path(cmd_filepath).absolute()625608 import tempfile609610 encoding = get_best_encoding(sys.stdout)629 if color is None:630 color = False611 # On Windows, NamedTemporaryFile cannot be opened by another process612 # while Python still has it open, so we use delete=False and clean up manually613 # rather than using a contextmanager here.614 f = tempfile.NamedTemporaryFile(
15 unmodified lines
630631@contextlib.contextmanager632def _nullpager(633 stream: t.TextIO, color: bool | None = None654) -> t.Iterator[tuple[t.TextIO, bool]]:634) -> t.Iterator[tuple[t.TextIO, bool | None]]:635 """Simply print unformatted text. This is the ultimate fallback.636637 The stream comes from elsewhere (typically ``sys.stdout``), so its lifecycle638 is left untouched: :class:`_PagerWriter` never closes what it wraps, and it639 is the only thing :func:`get_pager_file` hands to the caller.640 """661 if color is None:662 color = False663641 yield stream, color642643644class Editor:
289 unmodified lines