Skip to content
Myr

Forwards all user's parameters set in `PAGER`

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

Improve detection of raw mode by parsing the option tokens Fix detection of `less.exe` on Windows

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 61b69e9 · Browse files · 3 files+227 added−12 removed
This commit

State

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

Diff stats

3 files+227 added−12 removed

  • tests:+171 added−1 removed
  • other:+56 added−11 removed

3 files+227 added−12 removed

modified:src/click/_termui_impl.py+50 added-11 removed
486 unmodified lines
487488 cmd_path, cmd_params = resolved489490 if use_tempfile:491 return _tempfilepager(cmd_path, color)491 return _tempfilepager(cmd_path, cmd_params, color)492493 return _pipepager(cmd_path, cmd_params, color)494495
20 unmodified lines
516 finally:517 writer.flush()518519520def _less_uses_raw_mode(less_env: str, cmd_params: list[str]) -> bool:521 """Detect a raw-control-characters request in a ``less`` invocation.522523 Parses the tokens of the ``LESS`` environment variable and the command524 line: only short-option clusters (``-R``, ``-rX``, ``-XrY``) and the525 ``--raw-control-chars`` long option request raw mode. Filenames and526 long-option values may carry the letter ``r`` without being such a527 request.528 """529 try:530 env_tokens = shlex.split(less_env)531 except ValueError:532 # Unbalanced quotes make ``LESS`` unparsable: fall back to whitespace533 # splitting rather than failing the pager over it.534 env_tokens = less_env.split()535 tokens = env_tokens + cmd_params536537 for token in tokens:538 if token.startswith("--"):539 if token.casefold() == "--raw-control-chars":540 return True541 elif token.startswith("-") and len(token) > 1:542 if "r" in token[1:].casefold():543 return True544545 return False546547548@contextlib.contextmanager549def _pipepager(550 cmd_path: Path, cmd_params: list[str], color: bool | None = None551) -> t.Iterator[tuple[t.TextIO, bool | None]]:
10 unmodified lines
562 # Make a local copy of the environment to not affect the global one.563 env = dict(os.environ)564565 # 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.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:566 # them: either the invocation already requests raw control characters, or567 # ``LESS=-R`` is injected. Match on the stem so a resolved ``less.exe`` is568 # recognized like bare ``less``, case-insensitively on Windows since its569 # filesystems are. POSIX keeps an exact match.570 cmd_name = cmd_path.stem571 if WIN:572 # ``_pager_contextmanager`` currently routes every Windows invocation573 # to ``_tempfilepager``, so this branch is not reachable on Windows574 # today: it keeps the detection correct should that routing ever575 # change.576 cmd_name = cmd_name.casefold()577578 if color is None and cmd_name == "less":579 less_env = os.environ.get("LESS", "")580 if _less_uses_raw_mode(less_env, cmd_params):581 color = True582 elif not less_env and not cmd_params:583 env["LESS"] = "-R"584 color = True544 elif "r" in less_flags or "R" in less_flags:545 color = True585586 c = subprocess.Popen(587 [str(cmd_path)] + cmd_params,588 shell=False,
44 unmodified lines
633634635@contextlib.contextmanager636def _tempfilepager(598 cmd_path: Path, color: bool | None = None637 cmd_path: Path, cmd_params: list[str], color: bool | None = None638) -> t.Iterator[tuple[t.TextIO, bool | None]]:639 """Page through text by invoking a program on a temporary file.640641 Used as the primary pager strategy on Windows (where piping to642 ``more`` adds spurious ``\\r\\n``), and as a fallback on other604 platforms. The command is invoked with the temporary file as its only605 argument: any parameters the user set in ``PAGER`` are not passed on.643 platforms. The command is invoked with any parameters from ``PAGER``644 followed by the temporary file name.645 """646 import subprocess647 import tempfile648
7 unmodified lines
656 try:657 yield t.cast(t.TextIO, f), color658 f.flush()659 f.close()621 subprocess.call([str(cmd_path), f.name])660 subprocess.call([str(cmd_path), *cmd_params, f.name])661 finally:662 # An error raised while paging skips the close() above, and Windows663 # refuses to unlink a file the process still holds open. Closing here664 # keeps that PermissionError from replacing the original exception.
308 unmodified lines
modified:tests/test_termui.py+171 added-1 removed
1import contextlib2import gc3import io4import os5import pathlib6import platform7import shlex8import shutil9import subprocess10import sys11import tempfile12import time13from unittest.mock import patch
746 unmodified lines
760 assert err == ""761 assert out == expected762763764@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")765@pytest.mark.parametrize(766 ("pager_name", "expected_color"),767 [768 pytest.param("less", True, id="less"),769 pytest.param("less.exe", True, id="less.exe"),770 pytest.param("LESS.EXE", False, id="upper case stays unmatched on POSIX"),771 pytest.param("cat", False, id="not less"),772 ],773)774def test_pipepager_less_detection_matches_stem(775 monkeypatch, tmp_path, pager_name, expected_color776):777 """The ``less`` detection behind the ``LESS=-R`` auto-enable matches the778 command stem, so a ``less.exe`` resolved on Windows is recognized the same779 as a bare ``less``. POSIX keeps an exact, case-sensitive match.780 """781 fake_pager = tmp_path / pager_name782 fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")783 fake_pager.chmod(0o755)784785 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)786 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", str(fake_pager))787 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)788789 with click.get_pager_file() as pager:790 assert pager.color is expected_color791792793@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")794def test_pipepager_less_detection_case_insensitive_on_windows(monkeypatch, tmp_path):795 """Windows filesystems are case-insensitive, so ``which`` resolves796 whatever case the file carries: the ``less`` match casefolds there.797798 Runs ``_pipepager`` directly: faking ``WIN`` makes799 ``_pager_contextmanager`` route to the temp file strategy instead.800 """801 fake_pager = tmp_path / "LESS.EXE"802 fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")803 fake_pager.chmod(0o755)804805 monkeypatch.setattr(click._termui_impl, "WIN", True)806 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)807808 with click._termui_impl._pipepager(fake_pager, []) as (_, color):809 assert color is True810811812class _FakePagerProcess:813 """Stand-in for :class:`subprocess.Popen` recording argv and env without814 launching a process."""815816 def __init__(self, argv, *, env=None, **kwargs):817 self.argv = argv818 self.env = env819 self.returncode = 0820 self.stdin = io.StringIO()821822 def terminate(self):823 pass824825 def wait(self):826 return 0827828829@pytest.mark.parametrize(830 ("cmd_parts", "less_env", "expected_color", "expected_less"),831 [832 pytest.param(["less"], None, True, "-R", id="no flags: inject LESS=-R"),833 pytest.param(["less", "-R"], None, True, None, id="explicit -R"),834 pytest.param(["less", "-rX"], None, True, None, id="bundled short flags"),835 pytest.param(["less"], "-R", True, "-R", id="LESS env var"),836 pytest.param(837 ["less", "--RAW-CONTROL-CHARS"], None, True, None, id="long option"838 ),839 pytest.param(["less", "-X"], None, None, None, id="unrelated flag"),840 pytest.param(841 ["less"],842 "--prompt=resume",843 None,844 "--prompt=resume",845 id="long option with r substring",846 ),847 pytest.param(["less", "README.md"], None, None, None, id="filename with R"),848 pytest.param(849 ["less", "requirements.txt"], None, None, None, id="filename with r"850 ),851 pytest.param(852 ["less", "--", "README.md"],853 None,854 None,855 None,856 id="option terminator shields filenames",857 ),858 pytest.param(859 # The detection matches the bare long option: an ``r`` inside an860 # option value does not request raw mode.861 ["less", "--raw-control-chars=x"],862 None,863 None,864 None,865 id="long option with value",866 ),867 pytest.param(868 # Unbalanced quotes make shlex.split raise: the detection falls869 # back to whitespace splitting, which still finds the -R.870 ["less"],871 '-R "',872 True,873 '-R "',874 id="unparsable LESS",875 ),876 ],877)878def test_pipepager_less_raw_mode_detection(879 monkeypatch, cmd_parts, less_env, expected_color, expected_less880):881 """Raw-mode detection parses the option tokens from ``LESS`` and the882 command line. Filenames and unrelated options carrying the letter ``r``883 or ``R`` do not request raw mode, and ``_pipepager`` then reports no884 opinion (``None``) that :func:`get_pager_file` settles to off.885 {issue}`3416`886 """887 if less_env is None:888 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)889 else:890 monkeypatch.setitem(click._termui_impl.os.environ, "LESS", less_env)891892 processes: list[_FakePagerProcess] = []893894 def fake_popen(*args, **kwargs):895 process = _FakePagerProcess(*args, **kwargs)896 processes.append(process)897 return process898899 monkeypatch.setattr(subprocess, "Popen", fake_popen)900 # Popen is faked, so no real binary needs to exist behind the resolved901 # path: the stem is all the less detection reads from it.902 cmd_path = pathlib.Path("/tests/less")903904 with click._termui_impl._pipepager(cmd_path, cmd_parts[1:]) as (_, color):905 pass906907 assert color is expected_color908 (process,) = processes909 if expected_less is None:910 assert "LESS" not in process.env911 else:912 assert process.env["LESS"] == expected_less913914915def test_echo_via_pager_streams_each_write(monkeypatch):916 """Each write is flushed so a slow generator streams to the pager917 incrementally instead of buffering until the end (issues #3242, #2542).918 """
246 unmodified lines
1165 :func:`shlex.split` in POSIX mode, where a Windows path loses its1166 backslashes and splits on the space in ``C:\\Program Files``, leaving a1167 command that resolves to nothing. Click resolves the bare name itself.1168 """1169 cmd = shlex.split(pager_cmd)[0]1016 assert shutil.which(pager_cmd) is not None, f"{pager_cmd} not available"1170 assert shutil.which(cmd) is not None, f"{cmd} not available"1171 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1172 monkeypatch.setattr(click._termui_impl, "WIN", True)1173 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_cmd)1174
53 unmodified lines
1228 assert err == ""1229 assert out.replace("\r\n", "\n") == expected123012311232@pytest.mark.skipif(shutil.which("head") is None, reason="head not available")1233def test_tempfile_pager_passes_pager_params(monkeypatch, capfd):1234 """The temp file backend forwards ``PAGER`` parameters to the command.12351236 ``head -n 1`` renders one line out of two when the ``-n 1`` reaches the1237 command.1238 """1239 _force_tempfile_pager(monkeypatch, pager_cmd="head -n 1")12401241 click.echo_via_pager("line one\nline two\n")12421243 out, err = capfd.readouterr()1244 assert err == ""1245 assert out.replace("\r\n", "\n") == "line one\n"124612471248@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1249def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1250 """An error while paging must not leave the temp file open at unlink time.1251
720 unmodified lines
modified:CHANGES.md+6 added
81 unmodified lines
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.86- The temporary file pager backend forwards any parameters the user set in87 `PAGER` to the pager command instead of silently dropping them. On Windows,88 `PAGER="less -R"` now invokes `less -R` on the temporary file rather than89 bare `less`. {pr}`3777`90- Improve raw mode detection by parsing the option tokens. {issue}`3416`91 {pr}`3777`9293## Version 8.4.29495Released 2026-06-24
1561 unmodified lines