Close the pager temp file before unlinking it
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 150d107 · 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
Provenance
- Commit
1f9cd54- Tree
46053c3- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
150d107
3 files changed+69 added−3 removed
modified:src/click/_termui_impl.py+5 added
636 unmodified lines637 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)647 648 649 @contextlib.contextmanager309 unmodified linesmodified:tests/test_termui.py+59 added-3 removed
1 import contextlib2 import gc3 import io4+import os5 import platform6 import shlex7 import shutil8 import sys963 unmodified lines972 """Route ``get_pager_file`` through the ``_tempfilepager`` backend.973 974 That backend is only reachable on Windows, so the platform flag and the tty975 probes are faked to exercise it from any runner.976+977+ ``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)987 988 989 def _page_with_get_pager_file():990 with click.get_pager_file() as pager:52 unmodified lines1043 assert err == ""1044 assert out.replace("\r\n", "\n") == expected1045 1046 1047+@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1048+def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1049+ """An error while paging must not leave the temp file open at unlink time.1050+1051+ 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)1058+1059+ temp_files = []1060+ real_named_temporary_file = tempfile.NamedTemporaryFile1061+1062+ def record(*args, **kwargs):1063+ f = real_named_temporary_file(*args, **kwargs)1064+ temp_files.append(f)1065+ return f1066+1067+ monkeypatch.setattr(tempfile, "NamedTemporaryFile", record)1068+1069+ closed_at_unlink = []1070+ real_unlink = os.unlink1071+1072+ def spy_unlink(path, **kwargs):1073+ closed_at_unlink.append([f.closed for f in temp_files])1074+ return real_unlink(path, **kwargs)1075+1076+ monkeypatch.setattr(os, "unlink", spy_unlink)1077+1078+ 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()1089+1090+ 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+ )1095+1096+1097 def 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 linesmodified:CHANGES.md+5 added
72 unmodified lines73 - {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`82 83 ## Version 8.4.284 85 Released 2026-06-241561 unmodified lines