Skip to content
Myr

Fix error reporting on Windows when an error is raised in the pager (#3764)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 150d107, 1f9cd54 · Browse files · 3 files+69 added−3 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+69 added−3 removed

  • tests:+59 added−3 removed
  • other:+10 added−0 removed

3 files+69 added−3 removed

modified:src/click/_termui_impl.py+5 added
636 unmodified lines
637 f.flush()638 f.close()639 subprocess.call([str(cmd_path), f.name])640 finally:641 # An error raised while paging skips the close() above, and Windows642 # refuses to unlink a file the process still holds open. Closing here643 # keeps that PermissionError from replacing the original exception.644 # close() is idempotent, so this is a no-op on the success path.645 f.close()646 os.unlink(f.name)647648649@contextlib.contextmanager
309 unmodified lines
modified:tests/test_termui.py+59 added-3 removed
1import contextlib2import gc3import io4import os5import platform6import shlex7import shutil8import sys
963 unmodified lines
972 """Route ``get_pager_file`` through the ``_tempfilepager`` backend.973974 That backend is only reachable on Windows, so the platform flag and the tty975 probes are faked to exercise it from any runner.976977 ``PAGER`` is set to the bare command name, not to the path978 :func:`shutil.which` resolves it to. ``pager()`` splits ``PAGER`` with979 :func:`shlex.split` in POSIX mode, where a Windows path loses its980 backslashes and splits on the space in ``C:\\Program Files``, leaving a981 command that resolves to nothing. Click resolves the bare name itself.982 """976 cmd_path = shutil.which(pager_cmd)977 assert cmd_path is not None, f"{pager_cmd} not available"983 assert shutil.which(pager_cmd) is not None, f"{pager_cmd} not available"984 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)985 monkeypatch.setattr(click._termui_impl, "WIN", True)980 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", cmd_path)986 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_cmd)987988989def _page_with_get_pager_file():990 with click.get_pager_file() as pager:
52 unmodified lines
1043 assert err == ""1044 assert out.replace("\r\n", "\n") == expected104510461047@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1048def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1049 """An error while paging must not leave the temp file open at unlink time.10501051 The ``f.close()`` on the success path sits after the ``yield``, so an1052 exception raised while the pager is open used to skip it and reach1053 ``finally: os.unlink(f.name)`` with the handle still open. Windows refuses1054 to unlink an open file, so ``PermissionError: [WinError 32]`` replaced the1055 original error and hid it (issue #3731).1056 """1057 _force_tempfile_pager(monkeypatch)10581059 temp_files = []1060 real_named_temporary_file = tempfile.NamedTemporaryFile10611062 def record(*args, **kwargs):1063 f = real_named_temporary_file(*args, **kwargs)1064 temp_files.append(f)1065 return f10661067 monkeypatch.setattr(tempfile, "NamedTemporaryFile", record)10681069 closed_at_unlink = []1070 real_unlink = os.unlink10711072 def spy_unlink(path, **kwargs):1073 closed_at_unlink.append([f.closed for f in temp_files])1074 return real_unlink(path, **kwargs)10751076 monkeypatch.setattr(os, "unlink", spy_unlink)10771078 try:1079 with pytest.raises(RuntimeError, match="boom"):1080 with click.get_pager_file():1081 raise RuntimeError("boom")1082 finally:1083 # Should this invariant regress, the assertion below reports it. Close1084 # the handle anyway so the leak does not also resurface as a1085 # ResourceWarning charged to an unrelated test.1086 for f in temp_files:1087 if not f.closed:1088 f.close()10891090 assert temp_files, "the temp file pager backend was not used"1091 assert closed_at_unlink == [[True]], (1092 "temp file still open when unlink ran; on Windows this raises "1093 "PermissionError [WinError 32] and masks the real error"1094 )109510961097def test_editor_unclosed_quote():1098 """An unclosed quote in the editor command raises ValueError."""1099 with pytest.raises(ValueError, match="No closing quotation"):1100 Editor(editor='"unclosed').edit_files(["f.txt"])
670 unmodified lines
modified:CHANGES.md+5 added
72 unmodified lines
73- {func}`progressbar` settles on its final position when `update_min_steps`74 does not divide the total. Steps below that threshold are applied when the75 bar finishes, so `show_pos` renders `20/20` rather than the last multiple76 it reached. {issue}`3571` {pr}`3769`77- An error raised while writing to the pager no longer gets replaced by78 `PermissionError: [WinError 32]` on Windows. The temporary file backend79 unlinked its file without closing it first, and Windows refuses to remove a80 file the process still holds open, so the cleanup failure masked the real81 exception. {issue}`3731` {pr}`3764`8283## Version 8.4.28485Released 2026-06-24
1561 unmodified lines