Improve echo_via_pager behaviour in face of errors (#2775)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Steffen Neubauer · committed by GitHub · parent 2cabbe3 · Browse files · 3 files·+197 added−32 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+197 added−32 removed
- tests:+157 added−15 removed
- other:+40 added−17 removed
Provenance
- Commit
3b06e0b- Tree
206b92c- Author
Steffen Neubauer <stefreak@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
2cabbe3
3 files changed+197 added−32 removed
modified:src/click/_termui_impl.py+31 added-17 removed
425 unmodified lines426 if not color:427 text = strip_ansi(text)428 429 stdin.write(text.encode(encoding, "replace"))430- except (OSError, KeyboardInterrupt):430+ except BrokenPipeError:431+ # In case the pager exited unexpectedly, ignore the broken pipe error.432 pass432- else:433- stdin.close()434-435- # Less doesn't respect ^C, but catches it for its own UI purposes (aborting436- # search or other commands inside less).437- #438- # That means when the user hits ^C, the parent process (click) terminates,439- # but less is still alive, paging the output and messing up the terminal.440- #441- # If the user wants to make the pager exit on ^C, they should set442- # `LESS='-K'`. It's not our decision to make.443- while True:433+ except Exception as e:434+ # In case there is an exception we want to close the pager immediately435+ # and let the caller handle it.436+ # Otherwise the pager will keep running, and the user may not notice437+ # the error message, or worse yet it may leave the terminal in a broken state.438+ c.terminate()439+ raise e440+ finally:441+ # We must close stdin and wait for the pager to exit before we continue442 try:445- c.wait()446- except KeyboardInterrupt:443+ stdin.close()444+ # Close implies flush, so it might throw a BrokenPipeError if the pager445+ # process exited already.446+ except BrokenPipeError:447 pass448- else:449- break448 449+ # Less doesn't respect ^C, but catches it for its own UI purposes (aborting450+ # search or other commands inside less).451+ #452+ # That means when the user hits ^C, the parent process (click) terminates,453+ # but less is still alive, paging the output and messing up the terminal.454+ #455+ # If the user wants to make the pager exit on ^C, they should set456+ # `LESS='-K'`. It's not our decision to make.457+ while True:458+ try:459+ c.wait()460+ except KeyboardInterrupt:461+ pass462+ else:463+ break464 465+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."""468 import tempfile469 293 unmodified linesmodified:tests/test_utils.py+157 added-15 removed
1 import os2 import pathlib3 import stat4 import sys5+from collections import namedtuple6 from io import StringIO7+from tempfile import tempdir8 9 import pytest10 11 import click._termui_impl168 unmodified lines180 yield "c"181 yield "abc"182 183 184+def _test_gen_func_fails():185+ yield "test"186+ raise RuntimeError("This is a test.")187+188+189+def _test_gen_func_echo(file=None):190+ yield "test"191+ click.echo("hello", file=file)192+ yield "test"193+194+195+def _test_simulate_keyboard_interrupt(file=None):196+ yield "output_before_keyboard_interrupt"197+ raise KeyboardInterrupt()198+199+200+EchoViaPagerTest = namedtuple(201+ "EchoViaPagerTest",202+ (203+ "description",204+ "test_input",205+ "expected_pager",206+ "expected_stdout",207+ "expected_stderr",208+ "expected_error",209+ ),210+)211+212+213 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")183-@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])214 @pytest.mark.parametrize(215 "test",216 [187- # We need lambda here, because pytest will188- # reuse the parameters, and then the generators189- # are already used and will not yield anymore190- ("just text\n", lambda: "just text"),191- ("iterable\n", lambda: ["itera", "ble"]),192- ("abcabc\n", lambda: _test_gen_func),193- ("abcabc\n", lambda: _test_gen_func()),194- ("012345\n", lambda: (c for c in range(6))),217+ # We need to pass a parameter function instead of a plain param218+ # as pytest.mark.parametrize will reuse the parameters causing the219+ # generators to be used up so they will not yield anymore220+ EchoViaPagerTest(221+ description="Plain string argument",222+ test_input=lambda: "just text",223+ expected_pager="just text\n",224+ expected_stdout="",225+ expected_stderr="",226+ expected_error=None,227+ ),228+ EchoViaPagerTest(229+ description="Iterable argument",230+ test_input=lambda: ["itera", "ble"],231+ expected_pager="iterable\n",232+ expected_stdout="",233+ expected_stderr="",234+ expected_error=None,235+ ),236+ EchoViaPagerTest(237+ description="Generator function argument",238+ test_input=lambda: _test_gen_func,239+ expected_pager="abcabc\n",240+ expected_stdout="",241+ expected_stderr="",242+ expected_error=None,243+ ),244+ EchoViaPagerTest(245+ description="String generator argument",246+ test_input=lambda: _test_gen_func(),247+ expected_pager="abcabc\n",248+ expected_stdout="",249+ expected_stderr="",250+ expected_error=None,251+ ),252+ EchoViaPagerTest(253+ description="Number generator expression argument",254+ test_input=lambda: (c for c in range(6)),255+ expected_pager="012345\n",256+ expected_stdout="",257+ expected_stderr="",258+ expected_error=None,259+ ),260+ EchoViaPagerTest(261+ description="Exception in generator function argument",262+ test_input=lambda: _test_gen_func_fails,263+ # Because generator throws early on, the pager did not have264+ # a chance yet to write the file.265+ expected_pager=None,266+ expected_stdout="",267+ expected_stderr="",268+ expected_error=RuntimeError,269+ ),270+ EchoViaPagerTest(271+ description="Exception in generator argument",272+ test_input=lambda: _test_gen_func_fails,273+ # Because generator throws early on, the pager did not have a274+ # chance yet to write the file.275+ expected_pager=None,276+ expected_stdout="",277+ expected_stderr="",278+ expected_error=RuntimeError,279+ ),280+ EchoViaPagerTest(281+ description="Keyboard interrupt should not terminate the pager",282+ test_input=lambda: _test_simulate_keyboard_interrupt(),283+ # Due to the keyboard interrupt during pager execution, click program284+ # should abort, but the pager should stay open.285+ # This allows users to cancel the program and search in the pager286+ # output, before they decide to terminate the pager.287+ expected_pager="output_before_keyboard_interrupt",288+ expected_stdout="",289+ expected_stderr="",290+ expected_error=KeyboardInterrupt,291+ ),292+ EchoViaPagerTest(293+ description="Writing to stdout during generator execution",294+ test_input=lambda: _test_gen_func_echo(),295+ expected_pager="testtest\n",296+ expected_stdout="hello\n",297+ expected_stderr="",298+ expected_error=None,299+ ),300+ EchoViaPagerTest(301+ description="Writing to stderr during generator execution",302+ test_input=lambda: _test_gen_func_echo(file=sys.stderr),303+ expected_pager="testtest\n",304+ expected_stdout="",305+ expected_stderr="hello\n",306+ expected_error=None,307+ ),308 ],309 )197-def test_echo_via_pager(monkeypatch, capfd, cat, test):198- monkeypatch.setitem(os.environ, "PAGER", cat)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}")317 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)318 201- expected_output = test[0]202- test_input = test[1]()319+ test_input = test.test_input()320+ expected_pager = test.expected_pager321+ expected_stdout = test.expected_stdout322+ expected_stderr = test.expected_stderr323+ expected_error = test.expected_error324 325+ if expected_error:326+ with pytest.raises(expected_error):204- click.echo_via_pager(test_input)327+ click.echo_via_pager(test_input)328+ else:329+ click.echo_via_pager(test_input)330 331 out, err = capfd.readouterr()207- assert out == expected_output332 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 = None340 341+ assert (342+ pager == expected_pager343+ ), f"Unexpected pager output in test case '{test.description}'"344+ assert (345+ out == expected_stdout346+ ), f"Unexpected stdout in test case '{test.description}'"347+ assert (348+ err == expected_stderr349+ ), f"Unexpected stderr in test case '{test.description}'"350+351+352 def test_echo_color_flag(monkeypatch, capfd):353 isatty = True354 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)355 298 unmodified linesmodified:CHANGES.rst+9 added
66 unmodified lines67 is now also typed: ``AnyStr`` if ``text`` is passed, otherwise ``None``.68 :issue:`2067` :pr:`2068`69 - Specialized typing of ``progressbar(length=...)`` as ``ProgressBar[int]``.70 :pr:`2630`71+- Improve ``echo_via_pager`` behaviour in face of errors.72+ :issue:`2674`73 74+ - Terminate the pager in case a generator passed to ``echo_via_pager``75+ raises an exception.76+ - Ensure to always close the pipe to the pager process and wait for it77+ to terminate.78+ - ``echo_via_pager`` will not ignore ``KeyboardInterrupt`` anymore. This79+ allows the user to search for future output of the generator when80+ using less and then aborting the program using ctrl-c.81 82 Version 8.1.883 -------------84 1117 unmodified lines