Skip to content

Commit d42d800

Browse files
committed
Merge branch 'main' into consolidated_toolbar
# Conflicts: # cmd2/cmd2.py
2 parents 1baf4de + b3579d1 commit d42d800

4 files changed

Lines changed: 203 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
entries which are symbolic links to directories.
1919
- `find_editor()` now finds the `edit` editor on Windows. It was the preferred default editor
2020
there but could never be found because it was searched for without its `.exe` extension.
21+
- `ppaged()` now prints its output when the configured pager program cannot be run, for example
22+
where `less` is not installed. Previously only the shell's error was shown and the output was
23+
lost. A pager command which could not be run is not tried again while the application is
24+
running, so the shell's error is shown once for each pager command instead of every time.
2125
- A command which prints through a `cmd2` console of its own, such as a `Cmd2GeneralConsole`
2226
showing a Rich progress bar, no longer ends with a `BrokenPipeError` message when its output
2327
is piped to something that exits early, as `head` does. `cmd2` now ends the command quietly

‎cmd2/cmd2.py‎

Lines changed: 59 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,9 @@ def __init__(
674674
self.pager = "less -RXF"
675675
self.pager_chop = "less -SRXF"
676676

677+
# Pager commands which the shell could not run. Each is tried, and reported by the shell, only once.
678+
self._unrunnable_pagers: set[str] = set()
679+
677680
# This boolean flag stores whether cmd2 will allow clipboard related features
678681
self.allow_clipboard = allow_clipboard
679682

@@ -1966,6 +1969,31 @@ def pfeedback(
19661969
rich_print_kwargs=rich_print_kwargs,
19671970
)
19681971

1972+
@staticmethod
1973+
def _pager_failed_to_start(command: str, returncode: int) -> bool:
1974+
"""Return whether the shell could not run a pager at all, so that it showed nothing.
1975+
1976+
A pager which did run has had the output, whatever status it exited with.
1977+
1978+
:param command: the pager command given to the shell
1979+
:param returncode: the status the shell exited with
1980+
"""
1981+
if returncode == 0:
1982+
return False
1983+
if sys.platform.startswith("win"):
1984+
# cmd.exe exits with 1 for a command it cannot find, which a pager may also do for
1985+
# reasons of its own. Tell them apart by whether there is such a program.
1986+
import shlex
1987+
import shutil
1988+
1989+
try:
1990+
words = shlex.split(command, posix=False)
1991+
except ValueError:
1992+
return False
1993+
return bool(words) and shutil.which(words[0].strip('"')) is None
1994+
# What a POSIX shell exits with for a command it cannot find, or cannot execute.
1995+
return returncode in (126, 127)
1996+
19691997
def ppaged(
19701998
self,
19711999
*objects: Any,
@@ -1990,6 +2018,9 @@ def ppaged(
19902018
The pager takes over the terminal, so the bottom toolbar is hidden while it is open and
19912019
comes back when it exits.
19922020
2021+
If the pager program cannot be run, for example because it is not installed, the output
2022+
is printed without one. That pager command is not tried again while the application runs.
2023+
19932024
:param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
19942025
- truncated text is still accessible by scrolling with the right & left arrow keys
19952026
- chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
@@ -2015,11 +2046,12 @@ def ppaged(
20152046
# A pager application blocks, so only run one if not redirecting or running a script (either text or Python).
20162047
can_block = not (self._redirecting or self.in_pyscript() or self.in_script())
20172048

2018-
# Check if we are outputting to a pager.
2019-
if functional_terminal and can_block:
2020-
# Chopping overrides soft_wrap
2021-
if chop:
2022-
soft_wrap = True
2049+
pager = self.pager_chop if chop else self.pager
2050+
2051+
# Check if we are outputting to a pager. One which the shell could not run is not tried again.
2052+
if functional_terminal and can_block and pager not in self._unrunnable_pagers:
2053+
# Chopping overrides soft_wrap, but only for what the pager is given
2054+
pager_soft_wrap = soft_wrap or chop
20232055

20242056
# Generate the bytes to send to the pager
20252057
console = self._get_core_print_console(
@@ -2035,7 +2067,7 @@ def ppaged(
20352067
end=end,
20362068
style=style,
20372069
justify=justify,
2038-
soft_wrap=soft_wrap,
2070+
soft_wrap=pager_soft_wrap,
20392071
**(rich_print_kwargs if rich_print_kwargs is not None else {}),
20402072
)
20412073
# As for a pipe: the pager gets UTF-8, and on Windows the console is UTF-8 while it runs.
@@ -2047,7 +2079,7 @@ def ppaged(
20472079
import subprocess
20482080

20492081
pipe_proc = subprocess.Popen( # noqa: S602
2050-
self.pager_chop if chop else self.pager,
2082+
pager,
20512083
shell=True,
20522084
stdin=subprocess.PIPE,
20532085
stdout=self.stdout,
@@ -2072,19 +2104,26 @@ def ppaged(
20722104
except (OSError, termios.error):
20732105
pass
20742106

2075-
else:
2076-
self.poutput(
2077-
*objects,
2078-
sep=sep,
2079-
end=end,
2080-
style=style,
2081-
soft_wrap=soft_wrap,
2082-
justify=justify,
2083-
emoji=emoji,
2084-
markup=markup,
2085-
highlight=highlight,
2086-
rich_print_kwargs=rich_print_kwargs,
2087-
)
2107+
if not self._pager_failed_to_start(pager, pipe_proc.returncode):
2108+
return
2109+
2110+
# The shell has said why there is no pager. Remember that, so it is not asked every time.
2111+
# Nothing has been shown, so this once the objects are rendered a second time below.
2112+
self._unrunnable_pagers.add(pager)
2113+
2114+
# Nothing is paging the output, so print it.
2115+
self.poutput(
2116+
*objects,
2117+
sep=sep,
2118+
end=end,
2119+
style=style,
2120+
soft_wrap=soft_wrap,
2121+
justify=justify,
2122+
emoji=emoji,
2123+
markup=markup,
2124+
highlight=highlight,
2125+
rich_print_kwargs=rich_print_kwargs,
2126+
)
20882127

20892128
def ppretty(
20902129
self,

‎docs/features/os.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ is redirected or piped, `ppaged()` falls back to `poutput()`.
4949
While the [bottom toolbar](./prompt.md#bottom-toolbar) is running, a pager temporarily hides it,
5050
because the pager takes over the terminal. The toolbar comes back when the pager exits.
5151

52+
The pager is the command in `self.pager`, or `self.pager_chop` when chopping long lines: `less` on
53+
POSIX systems and `more` on Windows by default. If that program cannot be run, for example because
54+
it is not installed, the output is printed without paging. A pager command which could not be run is
55+
not tried again while the application is running. `self.pager` and `self.pager_chop` are separate
56+
commands, so the shell may report each of them once.
57+
5258
Alternatively, a terminal pager can be invoked directly using the ability to run shell commands with
5359
the `!` shortcut like so:
5460

‎tests/test_cmd2.py‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4210,6 +4210,140 @@ def utf8_console():
42104210
assert events == ["utf-8 console", "pager started", "pager exited", "restored"]
42114211

42124212

4213+
class FakeTerminal(io.TextIOWrapper):
4214+
"""A real file which says it is a terminal, so that a pager's shell can be given it to write to."""
4215+
4216+
def isatty(self) -> bool:
4217+
return True
4218+
4219+
4220+
@pytest.fixture
4221+
def paging_app(outsim_app, monkeypatch, tmp_path):
4222+
"""An application which will page, and whatever reaches its terminal."""
4223+
stdin_mock = mock.MagicMock()
4224+
stdin_mock.isatty.return_value = True
4225+
monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
4226+
if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
4227+
monkeypatch.setenv("TERM", "simulated")
4228+
with FakeTerminal((tmp_path / "terminal").open("w+b"), encoding="utf-8") as terminal:
4229+
monkeypatch.setattr(outsim_app, "stdout", terminal)
4230+
4231+
def shown() -> str:
4232+
terminal.flush()
4233+
terminal.seek(0)
4234+
return terminal.read()
4235+
4236+
yield outsim_app, shown
4237+
4238+
4239+
@pytest.mark.parametrize("chop", [True, False])
4240+
def test_ppaged_shows_the_output_when_the_pager_cannot_be_run(paging_app, capfd, chop) -> None:
4241+
"""A pager which is not installed must not cost the user the output.
4242+
4243+
The shell reports the missing program and exits. Nothing has been shown by then, and
4244+
without the pager there is nobody else to show it.
4245+
"""
4246+
app, shown = paging_app
4247+
app.pager = app.pager_chop = "cmd2-no-such-pager-program --some-option"
4248+
4249+
app.ppaged("first line\nsecond line", chop=chop)
4250+
4251+
assert shown() == "first line\nsecond line\n"
4252+
# The shell said why there was no pager.
4253+
assert "cmd2-no-such-pager-program" in capfd.readouterr().err
4254+
4255+
4256+
def test_ppaged_without_a_pager_wraps_as_the_caller_asked(paging_app) -> None:
4257+
"""Chopping turns soft wrap on for a pager to scroll sideways. With no pager, the caller's choice stands."""
4258+
app, shown = paging_app
4259+
app.pager_chop = "cmd2-no-such-pager-program"
4260+
4261+
app.ppaged("word " * 400, chop=True, soft_wrap=False)
4262+
4263+
assert len(shown().splitlines()) > 1
4264+
4265+
4266+
def test_ppaged_does_not_repeat_output_after_a_pager_which_ran_and_failed(paging_app) -> None:
4267+
"""Only a pager which could not be started is made up for: one which ran has had the output."""
4268+
app, shown = paging_app
4269+
app.pager = f'"{sys.executable}" -c "import sys; sys.stdin.read(); sys.exit(1)"'
4270+
4271+
app.ppaged("first line\nsecond line")
4272+
4273+
assert shown() == ""
4274+
4275+
4276+
class RendersOnce:
4277+
"""A renderable which only has its lines to give the first time it is rendered."""
4278+
4279+
def __init__(self, *lines: str) -> None:
4280+
self._lines = iter(lines)
4281+
4282+
def __rich_console__(self, console, options):
4283+
yield from self._lines
4284+
4285+
4286+
def test_ppaged_does_not_try_again_a_pager_which_cannot_be_run(paging_app, capfd) -> None:
4287+
"""The shell says once that there is no such pager, not every time something is paged.
4288+
4289+
From then on nothing is rendered for a pager either, only for poutput().
4290+
"""
4291+
app, shown = paging_app
4292+
app.pager = "cmd2-no-such-pager-program"
4293+
4294+
app.ppaged("first")
4295+
assert "cmd2-no-such-pager-program" in capfd.readouterr().err
4296+
4297+
with mock.patch("subprocess.Popen") as popen_mock:
4298+
app.ppaged(RendersOnce("second"))
4299+
4300+
popen_mock.assert_not_called()
4301+
assert capfd.readouterr().err == ""
4302+
assert shown() == "first\nsecond\n"
4303+
4304+
4305+
def test_ppaged_tries_another_pager_after_one_which_cannot_be_run(paging_app) -> None:
4306+
"""Only the command which could not be run is given up on, so setting a pager which works is enough."""
4307+
app, shown = paging_app
4308+
app.pager = "cmd2-no-such-pager-program"
4309+
app.ppaged("unpaged")
4310+
4311+
app.pager = f'"{sys.executable}" -c "import sys; sys.stdout.write(sys.stdin.read().upper())"'
4312+
app.ppaged("paged")
4313+
4314+
assert shown() == "unpaged\nPAGED\n"
4315+
4316+
4317+
@pytest.mark.parametrize(
4318+
("platform", "command", "returncode", "found", "expected"),
4319+
[
4320+
pytest.param("linux", "less -RXF", 127, True, True, id="a POSIX shell found no such command"),
4321+
pytest.param("linux", "less -RXF", 126, True, True, id="a POSIX shell could not execute it"),
4322+
pytest.param("linux", "less -RXF", 1, False, False, id="a POSIX pager failed by itself"),
4323+
pytest.param("linux", "less -RXF", 0, False, False, id="a POSIX pager succeeded"),
4324+
pytest.param("win32", "less -RXF", 1, False, True, id="cmd.exe found no such command"),
4325+
pytest.param("win32", '"C:\\Program Files\\less.exe" -R', 1, False, True, id="cmd.exe found no such quoted path"),
4326+
pytest.param("win32", "more", 1, True, False, id="a Windows pager failed by itself"),
4327+
pytest.param("win32", "less -RXF", 0, False, False, id="a Windows pager succeeded"),
4328+
pytest.param("win32", 'less "unbalanced', 1, False, False, id="a Windows command which cannot be taken apart"),
4329+
pytest.param("win32", "", 1, False, False, id="no Windows command at all"),
4330+
],
4331+
)
4332+
def test_pager_failed_to_start(monkeypatch, platform, command, returncode, found, expected) -> None:
4333+
looked_for = []
4334+
4335+
def which(program: str) -> str | None:
4336+
looked_for.append(program)
4337+
return program if found else None
4338+
4339+
monkeypatch.setattr(sys, "platform", platform)
4340+
monkeypatch.setattr("shutil.which", which)
4341+
4342+
assert cmd2.Cmd._pager_failed_to_start(command, returncode) is expected
4343+
# A quoted program is looked for by its name, not with its quotes.
4344+
assert all(not program.startswith('"') for program in looked_for)
4345+
4346+
42134347
def test_ppaged_no_pager(outsim_app) -> None:
42144348
"""Since we're not in a fully-functional terminal, ppaged() will just call poutput()."""
42154349
msg = "testing..."

0 commit comments

Comments
 (0)