Linux maintainer tooling and workflows
 help / color / mirror / Atom feed
From: "Clément Le Goffic" <clegoffic@baylibre.com>
To: "Kernel.org Tools" <tools@kernel.org>
Cc: "Konstantin Ryabitsev" <konstantin@linuxfoundation.org>,
	"Clément Le Goffic" <clegoffic@baylibre.com>
Subject: [PATCH b4 3/3] lore: stop a less pager quitting on output that fits one screen
Date: Fri, 25 Sep 2026 14:50:28 +0200	[thread overview]
Message-ID: <20260925-b4-lore-fixes-v1-3-103fd9507e67@baylibre.com> (raw)
In-Reply-To: <20260925-b4-lore-fixes-v1-0-103fd9507e67@baylibre.com>

view_in_pager() stripped F from LESS so the pager stays open on output
that fits one screen, but a core.pager of "less -FRSX" carries the flag
on the command line, where it beats the environment.  Anything b4 hands
the pager that is short enough to fit then flashed past and was gone
with the pager, which is the one case the stripping exists to prevent.

Append -+F instead when the pager is less: it reads its options left to
right and -+X resets one to its default, so this reaches the flag
whichever set it and however it was spelled, including the long
--quit-if-one-screen.  The environment is left to the pipeline case,
where the less inside "diff-highlight | less -RFX" is out of reach and
an -F written there still wins, as it did before.

Assisted-by: claude-fable-5
Signed-off-by: Clément Le Goffic <clegoffic@baylibre.com>
---
 src/b4/__init__.py         | 18 ++++++-----
 src/tests/test___init__.py | 78 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 89 insertions(+), 7 deletions(-)

diff --git a/src/b4/__init__.py b/src/b4/__init__.py
index f55e9d9e73aa..97caf4c8a00f 100644
--- a/src/b4/__init__.py
+++ b/src/b4/__init__.py
@@ -6783,24 +6783,28 @@ def view_in_pager(bdata: bytes, filehint: str = 'b4-view.txt') -> None:
         with open(temp_fpath, 'xb') as view_file:
             view_file.write(bdata)
 
-        # Strip -F (quit-if-one-screen) from LESS so the pager always
-        # stays open, even when the output fits on a single screen.
-        env = dict(os.environ)
-        env['LESS'] = env.get('LESS', 'FRX').replace('F', '')
         if '|' in pager:
             # Pager uses a pipeline (e.g. "diff-highlight | less -RFX"),
             # so we must use the shell to interpret it.  Feed data on
             # stdin since piped pagers read from the pipe, not from a
-            # file argument.
+            # file argument.  The less inside is out of reach, so F only
+            # comes off the environment here.
+            env = dict(os.environ)
+            env['LESS'] = env.get('LESS', 'FRX').replace('F', '')
             logger.debug('Running (shell): %s < %s', pager, temp_fpath)
             with open(temp_fpath, 'rb') as fh:
                 spop = subprocess.Popen(pager, shell=True, stdin=fh, env=env)
         else:
             sp = shlex.shlex(pager, posix=True)
             sp.whitespace_split = True
-            cmdargs = list(sp) + [temp_fpath]
+            cmdargs = list(sp)
+            if cmdargs and os.path.basename(cmdargs[0]) == 'less':
+                # less takes its options left to right, so -+F resets
+                # quit-if-one-screen whichever set it.
+                cmdargs.append('-+F')
+            cmdargs += [temp_fpath]
             logger.debug('Running %s', ' '.join(cmdargs))
-            spop = subprocess.Popen(cmdargs, env=env)
+            spop = subprocess.Popen(cmdargs)
         spop.wait()
 
 
diff --git a/src/tests/test___init__.py b/src/tests/test___init__.py
index 18de9ab0f114..d253af11a86c 100644
--- a/src/tests/test___init__.py
+++ b/src/tests/test___init__.py
@@ -1981,3 +1981,81 @@ class TestFakeAmGitlinkPreimage:
             ecode, entry = b4.git_run_command(repo, ['ls-tree', commit, 'sub'])
             assert ecode == 0
             assert entry.split()[:3] == ['160000', 'commit', gitlink]
+
+
+class TestViewInPagerLessFlags:
+    """-F has to come off a "less" pager, and nothing else may change.
+
+    Output short enough to fit one screen -- a range-diff narrowed to a
+    single patch, say -- is exactly what quit-if-one-screen flashes past
+    the reader, and a core.pager of "less -FRSX" carries that flag where
+    the LESS environment cannot reach it.  less reads its options left to
+    right, so appending -+F resets it whatever spelling the pager used,
+    and nothing in the pager's own arguments is parsed or rewritten.
+    """
+
+    class _Spawned:
+        """Stands in for the pager process, which nobody is here to read."""
+
+        def wait(self) -> int:
+            return 0
+
+    @classmethod
+    def _spawned(cls, monkeypatch: pytest.MonkeyPatch, pager: str) -> List[str]:
+        """Return the argv view_in_pager() would have run."""
+        seen: List[Any] = list()
+        real_popen = b4.subprocess.Popen
+
+        def fake_popen(args: Any, **kwargs: Any) -> Any:
+            # b4 reads its config through Popen too, and those calls are the
+            # ones capturing stdout; the pager's own goes to the terminal.
+            if kwargs.get('stdout') is not None:
+                return real_popen(args, **kwargs)
+            seen.append(args)
+            return cls._Spawned()
+
+        monkeypatch.setenv('GIT_PAGER', pager)
+        monkeypatch.setattr(b4.subprocess, 'Popen', fake_popen)
+        b4.view_in_pager(b'short enough to fit one screen\n')
+        assert len(seen) == 1
+        argv = seen[0]
+        assert isinstance(argv, list)
+        assert argv[-1].endswith('b4-view.txt')
+        return [str(arg) for arg in argv[:-1]]
+
+    @pytest.mark.parametrize(
+        'pager,expected',
+        [
+            # A bundled cluster, on its own, and spelled out,
+            ('less -FRSX', ['less', '-FRSX', '-+F']),
+            ('less -F', ['less', '-F', '-+F']),
+            ('less -R -F -X', ['less', '-R', '-F', '-X', '-+F']),
+            ('/usr/bin/less -FRX', ['/usr/bin/less', '-FRX', '-+F']),
+            # the long form, which no amount of letter-splitting reaches,
+            (
+                'less --quit-if-one-screen',
+                ['less', '--quit-if-one-screen', '-+F'],
+            ),
+            # and a pager with no -F at all: -+F is a no-op there.
+            ('less -R', ['less', '-R', '-+F']),
+            # Only less is ours to touch,
+            ('most -F', ['most', '-F']),
+            # and its own arguments are left exactly as written: a prompt
+            # string whose text happens to contain an F,
+            ('less -R "-PsFile %f"', ['less', '-R', '-PsFile %f', '-+F']),
+            # a log file to write,
+            ('less -oFramelog.txt', ['less', '-oFramelog.txt', '-+F']),
+            # the pattern to open at,
+            ('less -pFoo', ['less', '-pFoo', '-+F']),
+            # and "+F" as the command to start with.
+            ('less +F', ['less', '+F', '-+F']),
+        ],
+    )
+    def test_less_is_told_to_reset_f(
+        self,
+        gitdir: str,
+        monkeypatch: pytest.MonkeyPatch,
+        pager: str,
+        expected: List[str],
+    ) -> None:
+        assert self._spawned(monkeypatch, pager) == expected

-- 
2.55.0


  parent reply	other threads:[~2026-09-25 12:50 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-09-25 12:50 [PATCH b4 0/3] lore: three fixes between a posted serie and the reader Clément Le Goffic
2026-09-25 12:50 ` [PATCH b4 1/3] lore: parse per-file modes in get_indexes Clément Le Goffic
2026-09-25 12:50 ` [PATCH b4 2/3] lore: fake-am series that touch submodule gitlinks Clément Le Goffic
2026-09-25 12:50 ` Clément Le Goffic [this message]
2026-10-05 10:09   ` [PATCH b4 3/3] lore: stop a less pager quitting on output that fits one screen Konstantin Ryabitsev
2026-10-05 12:37     ` Clément Le Goffic
2026-10-06  7:15       ` Konstantin Ryabitsev
2026-10-06  8:27         ` Clément Le Goffic
2026-10-05 10:09 ` [PATCH b4 0/3] lore: three fixes between a posted serie and the reader Konstantin Ryabitsev
2026-10-05 10:11 ` (subset) " Konstantin Ryabitsev

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260925-b4-lore-fixes-v1-3-103fd9507e67@baylibre.com \
    --to=clegoffic@baylibre.com \
    --cc=konstantin@linuxfoundation.org \
    --cc=tools@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox