Reconcile #1477 and #2775
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 46c32a1 · Browse files · 2 files·+134 added−59 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+134 added−59 removed
- tests:+26 added−21 removed
- other:+108 added−38 removed
Provenance
- Commit
43a7d70- Tree
55c1095- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
46c32a1
2 files changed+134 added−59 removed
modified:src/click/_termui_impl.py+108 added-38 removed
8 unmodified lines9 import collections.abc as cabc10 import contextlib11 import math12 import os13+import shlex14 import sys15 import time16 import typing as t17 from gettext import gettext as _18 from io import StringIO19+from pathlib import Path20+from shutil import which21 from types import TracebackType22 23 from ._compat import _default_text_stdout24 from ._compat import CYGWIN352 unmodified lines377 stdout = StringIO()378 379 if not isatty(sys.stdin) or not isatty(stdout):380 return _nullpager(stdout, generator, color)378- pager_cmd = (os.environ.get("PAGER", None) or "").strip()379- if pager_cmd:381+382+ # Split and normalize the pager command into parts.383+ pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)384+ if pager_cmd_parts:385 if WIN:381- return _tempfilepager(generator, pager_cmd, color)382- return _pipepager(generator, pager_cmd, color)386+ if _tempfilepager(generator, pager_cmd_parts, color):387+ return388+ elif _pipepager(generator, pager_cmd_parts, color):389+ return390+391 if os.environ.get("TERM") in ("dumb", "emacs"):392 return _nullpager(stdout, generator, color)385- if WIN or sys.platform.startswith("os2"):386- return _tempfilepager(generator, "more <", color)387- if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:388- return _pipepager(generator, "less", color)393+ if (WIN or sys.platform.startswith("os2")) and _tempfilepager(394+ generator, ["more"], color395+ ):396+ return397+ if _pipepager(generator, ["less"], color):398+ return399 400 import tempfile401 402 fd, filename = tempfile.mkstemp()403 os.close(fd)404 try:395- if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:396- return _pipepager(generator, "more", color)405+ if _pipepager(generator, ["more"], color):406+ return407 return _nullpager(stdout, generator, color)408 finally:409 os.unlink(filename)410 411 402-def _pipepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:403- """Page through text by feeding it to another program. Invoking a412+def _pipepager(413+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None414+) -> bool:415+ """Page through text by feeding it to another program. Invoking a416 pager through this might support colors.417+418+ Returns `True` if the command was found, `False` otherwise and thus another419+ pager should be attempted.420 """421+ # Split the command into the invoked CLI and its parameters.422+ if not cmd_parts:423+ return False424+ cmd = cmd_parts[0]425+ cmd_params = cmd_parts[1:]426+427+ cmd_filepath = which(cmd)428+ if not cmd_filepath:429+ return False430+ # Resolves symlinks and produces a normalized absolute path string.431+ cmd_path = Path(cmd_filepath).resolve()432+ cmd_name = cmd_path.name433+434 import subprocess435 436+ # Make a local copy of the environment to not affect the global one.437 env = dict(os.environ)438 410- # If we're piping to less we might support colors under the411- # condition that412- cmd_detail = cmd.rsplit("/", 1)[-1].split()413- if color is None and cmd_detail[0] == "less":414- less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"439+ # If we're piping to less and the user hasn't decided on colors, we enable440+ # them by default we find the -R flag in the command line arguments.441+ if color is None and cmd_name == "less":442+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"443 if not less_flags:444 env["LESS"] = "-R"445 color = True446 elif "r" in less_flags or "R" in less_flags:447 color = True448 421- c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)422- stdin = t.cast(t.BinaryIO, c.stdin)423- encoding = get_best_encoding(stdin)449+ c = subprocess.Popen(450+ [str(cmd_path)] + cmd_params,451+ shell=True,452+ stdin=subprocess.PIPE,453+ env=env,454+ errors="replace",455+ text=True,456+ )457+ assert c.stdin is not None458 try:459 for text in generator:460 if not color:461 text = strip_ansi(text)462 429- stdin.write(text.encode(encoding, "replace"))463+ c.stdin.write(text)464 except BrokenPipeError:465 # In case the pager exited unexpectedly, ignore the broken pipe error.466 pass467 except Exception as e:5 unmodified lines473 raise e474 finally:475 # We must close stdin and wait for the pager to exit before we continue476 try:443- stdin.close()477+ c.stdin.close()478 # Close implies flush, so it might throw a BrokenPipeError if the pager479 # process exited already.480 except BrokenPipeError:481 pass13 unmodified lines495 pass496 else:497 break498 499+ return True500 466-def _tempfilepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:467- """Page through text by invoking a program on a temporary file."""501+502+def _tempfilepager(503+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None504+) -> bool:505+ """Page through text by invoking a program on a temporary file.506+507+ Returns `True` if the command was found, `False` otherwise and thus another508+ pager should be attempted.509+ """510+ # Split the command into the invoked CLI and its parameters.511+ if not cmd_parts:512+ return False513+ cmd = cmd_parts[0]514+515+ cmd_filepath = which(cmd)516+ if not cmd_filepath:517+ return False518+ # Resolves symlinks and produces a normalized absolute path string.519+ cmd_path = Path(cmd_filepath).resolve()520+521+ import subprocess522 import tempfile523 524 fd, filename = tempfile.mkstemp()525 # TODO: This never terminates if the passed generator never terminates.3 unmodified lines529 encoding = get_best_encoding(sys.stdout)530 with open_stream(filename, "wb")[0] as f:531 f.write(text.encode(encoding))532 try:479- os.system(f'{cmd} "{filename}"')533+ subprocess.call([str(cmd_path), filename])534+ except OSError:535+ # Command not found536+ pass537 finally:538 os.close(fd)539 os.unlink(filename)540 541+ return True542 543+544 def _nullpager(545 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None546 ) -> None:547 """Simply print unformatted text. This is the ultimate fallback."""25 unmodified lines573 return rv574 if WIN:575 return "notepad"576 for editor in "sensible-editor", "vim", "nano":518- if os.system(f"which {editor} >/dev/null 2>&1") == 0:577+ if which(editor) is not None:578 return editor579 return "vi"580 581 def edit_files(self, filenames: cabc.Iterable[str]) -> None:102 unmodified lines684 finally:685 null.close()686 elif WIN:687 if locate:629- url = _unquote_file(url.replace('"', ""))630- args = f'explorer /select,"{url}"'688+ url = _unquote_file(url)689+ args = ["explorer", f"/select,{url}"]690 else:632- url = url.replace('"', "")633- wait_str = "/WAIT" if wait else ""634- args = f'start {wait_str} "" "{url}"'635- return os.system(args)691+ args = ["start"]692+ if wait:693+ args.append("/WAIT")694+ args.append("")695+ args.append(url)696+ try:697+ return subprocess.call(args)698+ except OSError:699+ # Command not found700+ return 127701 elif CYGWIN:702 if locate:638- url = os.path.dirname(_unquote_file(url).replace('"', ""))639- args = f'cygstart "{url}"'703+ url = _unquote_file(url)704+ args = ["cygstart", os.path.dirname(url)]705 else:641- url = url.replace('"', "")642- wait_str = "-w" if wait else ""643- args = f'cygstart {wait_str} "{url}"'644- return os.system(args)706+ args = ["cygstart"]707+ if wait:708+ args.append("-w")709+ args.append(url)710+ try:711+ return subprocess.call(args)712+ except OSError:713+ # Command not found714+ return 127715 716 try:717 if locate:718 url = os.path.dirname(_unquote_file(url)) or "."121 unmodified linesmodified:tests/test_utils.py+26 added-21 removed
1 import os2 import pathlib3 import stat4+import subprocess5 import sys6 from collections import namedtuple7+from contextlib import nullcontext8+from functools import partial9 from io import StringIO10+from pathlib import Path11 from tempfile import tempdir12+from unittest.mock import patch13 14 import pytest15 16 import click._termui_impl199 unmodified lines216 217 218 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")219 @pytest.mark.parametrize(220+ "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]221+)222+@pytest.mark.parametrize(223 "test",224 [225 # We need to pass a parameter function instead of a plain param226 # as pytest.mark.parametrize will reuse the parameters causing the42 unmodified lines269 description="Exception in generator function argument",270 test_input=lambda: _test_gen_func_fails,271 # Because generator throws early on, the pager did not have272 # a chance yet to write the file.265- expected_pager=None,273+ expected_pager="",274 expected_stdout="",275 expected_stderr="",276 expected_error=RuntimeError,277 ),1 unmodified line279 description="Exception in generator argument",280 test_input=lambda: _test_gen_func_fails,281 # Because generator throws early on, the pager did not have a282 # chance yet to write the file.275- expected_pager=None,283+ expected_pager="",284 expected_stdout="",285 expected_stderr="",286 expected_error=RuntimeError,287 ),26 unmodified lines314 expected_error=None,315 ),316 ],317 )310-def test_echo_via_pager(monkeypatch, capfd, test):311- pager_out_tmp = f"{tempdir}/pager_out.txt"312-313- if os.path.exists(pager_out_tmp):314- os.remove(pager_out_tmp)315-316- monkeypatch.setitem(os.environ, "PAGER", f"cat > {pager_out_tmp}")318+def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):319+ monkeypatch.setitem(os.environ, "PAGER", pager_cmd)320 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)321 322 test_input = test.test_input()323 expected_pager = test.expected_pager324 expected_stdout = test.expected_stdout325 expected_stderr = test.expected_stderr326 expected_error = test.expected_error327 325- if expected_error:326- with pytest.raises(expected_error):327- click.echo_via_pager(test_input)328- else:329- click.echo_via_pager(test_input)328+ check_raise = pytest.raises(expected_error) if expected_error else nullcontext()329 330+ pager_out_tmp = Path(tempdir) / "pager_out.txt"331+ pager_out_tmp.unlink(missing_ok=True)332+ with pager_out_tmp.open("w") as f:333+ force_subprocess_stdout = patch.object(334+ subprocess,335+ "Popen",336+ partial(subprocess.Popen, stdout=f),337+ )338+ with force_subprocess_stdout:339+ with check_raise:340+ click.echo_via_pager(test_input)341+342 out, err = capfd.readouterr()343 333- if os.path.exists(pager_out_tmp):334- with open(pager_out_tmp) as f:335- pager = f.read()336- else:337- # The pager process was not started or has been338- # terminated before it could finish writing339- pager = None344+ pager = pager_out_tmp.read_text()345 346 assert (347 pager == expected_pager348 ), f"Unexpected pager output in test case '{test.description}'"310 unmodified lines