Skip to content
Myr

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

2 files+134 added−59 removed

modified:src/click/_termui_impl.py+108 added-38 removed
8 unmodified lines
9import collections.abc as cabc10import contextlib11import math12import os13import shlex14import sys15import time16import typing as t17from gettext import gettext as _18from io import StringIO19from pathlib import Path20from shutil import which21from types import TracebackType2223from ._compat import _default_text_stdout24from ._compat import CYGWIN
352 unmodified lines
377 stdout = StringIO()378379 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:381382 # 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 return390391 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 return399400 import tempfile401402 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)410411402def _pipepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:403 """Page through text by feeding it to another program. Invoking a412def _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.417418 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:]426427 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.name433434 import subprocess435436 # Make a local copy of the environment to not affect the global one.437 env = dict(os.environ)438410 # 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 = True448421 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)462429 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 lines
473 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 pass
13 unmodified lines
495 pass496 else:497 break498499 return True500466def _tempfilepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:467 """Page through text by invoking a program on a temporary file."""501502def _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.506507 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]514515 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()520521 import subprocess522 import tempfile523524 fd, filename = tempfile.mkstemp()525 # TODO: This never terminates if the passed generator never terminates.
3 unmodified lines
529 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)540541 return True542543544def _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 lines
573 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"580581 def edit_files(self, filenames: cabc.Iterable[str]) -> None:
102 unmodified lines
684 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 127715716 try:717 if locate:718 url = os.path.dirname(_unquote_file(url)) or "."
121 unmodified lines
modified:tests/test_utils.py+26 added-21 removed
1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from functools import partial9from io import StringIO10from pathlib import Path11from tempfile import tempdir12from unittest.mock import patch1314import pytest1516import click._termui_impl
199 unmodified lines
216217218@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 the
42 unmodified lines
269 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 line
279 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 lines
314 expected_error=None,315 ),316 ],317)310def test_echo_via_pager(monkeypatch, capfd, test):311 pager_out_tmp = f"{tempdir}/pager_out.txt"312313 if os.path.exists(pager_out_tmp):314 os.remove(pager_out_tmp)315316 monkeypatch.setitem(os.environ, "PAGER", f"cat > {pager_out_tmp}")318def 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)321322 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_error327325 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()329330 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)341342 out, err = capfd.readouterr()343333 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()345346 assert (347 pager == expected_pager348 ), f"Unexpected pager output in test case '{test.description}'"
310 unmodified lines