Skip to content
Myr

Add path normalization edge-cases, verify `shlex.split` behavior

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

Also move to Python comments details relevant to developers instead of docstrings Follow up to #3245

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 1339fd3 · Browse files · 2 files+119 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

2 files+119 added−32 removed

  • tests:+109 added−4 removed
  • other:+10 added−28 removed

2 files+119 added−32 removed

modified:src/click/_termui_impl.py+10 added-28 removed
365 unmodified lines
366 self.render_progress()367368369def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:370 """Decide what method to use for paging through text.371372 The ``PAGER`` environment variable is split into an ``argv`` list with373 :func:`shlex.split` in its default POSIX mode so that quotes are374 stripped from tokens and quoted Windows paths are preserved.375376 .. note::377 ``posix=False`` `was considered but rejected378 <https://github.com/pallets/click/pull/1477#issuecomment-620231711>`_379 because it retains quote characters in tokens. The380 :func:`shlex.quote` approach was also reverted in :pr:`1543`.381382 .. seealso::383 :issue:`1026`, :pr:`1477` and :pr:`2775`.384 """370 """Decide what method to use for paging through text."""371 stdout = _default_text_stdout()372373 # There are no standard streams attached to write to. For example,374 # pythonw on Windows.
2 unmodified lines
377378 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)380381 # Split using POSIX mode (the default) so that quote characters are382 # stripped from tokens and quoted Windows paths are preserved.383 # posix=False was rejected (PR #1477) because it retains quotes in384 # tokens, and the shlex.quote approach was also reverted (PR #1543).385 # See also: issue #1026, PR #2775.386 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))387 if pager_cmd_parts:388 if WIN:389 if _tempfilepager(generator, pager_cmd_parts, color):
37 unmodified lines
427 automatically.428429 Returns ``True`` if the command was found and executed, ``False``430 otherwise so another pager can be attempted.440441 .. seealso::442 :pr:`2775` improved error handling: :exc:`BrokenPipeError` is443 caught specifically, generator exceptions terminate the pager, and444 ``stdin.close()`` is always called in a ``finally`` block.431 """432 # Split the command into the invoked CLI and its parameters.433 if not cmd_parts:434 return False
173 unmodified lines
608 return editor609 return "vi"610611 def edit_files(self, filenames: cabc.Iterable[str]) -> None:626 """Open files in the user's editor.627628 The editor command is split into an ``argv`` list with629 :func:`shlex.split` in POSIX mode; see :func:`pager` for rationale.630631 .. seealso::632 :issue:`1026` and :pr:`1477`.633 """612 """Open files in the user's editor."""613 import shlex614 import subprocess615616 editor = self.get_editor()
3 unmodified lines
620 environ = os.environ.copy()621 environ.update(self.env)622623 try:624 # Split in POSIX mode (the default) for the same reasons as625 # in pager(): strips quotes from tokens and preserves quoted626 # Windows paths. See issue #1026, PR #1477.627 c = subprocess.Popen(628 args=shlex.split(editor) + list(filenames),629 env=environ,630 )
241 unmodified lines
modified:tests/test_termui.py+109 added-4 removed
1import platform2import shlex3import tempfile4import time5from unittest.mock import patch6
419 unmodified lines
426 pytest.param(427 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',428 ["f.txt"],429 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],429 id="quoted windows path with spaces (issue 1026)",430 id="quoted windows path with spaces",431 ),432 # PR #1477: pager/editor command with flags, like ``less -FRSX``.433 pytest.param(434 "less -FRSX",435 ["f.txt"],436 ["less", "-FRSX", "f.txt"],436 id="command with flags (pr 1477)",437 id="command with flags",438 ),439 # Issue #1026: quoted command with ``--wait`` flag.440 pytest.param(441 '"my command" --option value arg',442 ["f.txt"],443 ["my command", "--option", "value", "arg", "f.txt"],443 id="quoted command with args (issue 1026)",444 id="quoted command with args",445 ),446 # PR #1477: unquoted unix path.447 pytest.param(448 "/usr/bin/vim",
5 unmodified lines
454 pytest.param(455 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",456 ["f.txt"],457 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],457 id="escaped space in unix path (issue 1026)",458 id="escaped space in unix path",459 ),460 pytest.param(461 " vim ",462 ["f.txt"],463 ["vim", "f.txt"],464 id="leading and trailing whitespace",465 ),466 pytest.param(467 "vim\tf.txt",468 [],469 ["vim", "f.txt"],470 id="tab-separated tokens",471 ),472 pytest.param(473 "'/Applications/My Editor.app/Contents/MacOS/editor'",474 ["f.txt"],475 ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],476 id="single-quoted path with spaces",477 ),478 pytest.param(479 '"my editor" --wait --new-window',480 ["file 1.txt", "file 2.txt"],481 ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],482 id="quoted editor with multiple flags and filenames with spaces",483 ),484 pytest.param(485 "vim -u NONE -N",486 ["f.txt"],487 ["vim", "-u", "NONE", "-N", "f.txt"],488 id="multiple short flags",489 ),490 pytest.param(491 "editor",492 ['file"name.txt'],493 ["editor", 'file"name.txt'],494 id="filename with double quote",495 ),496 pytest.param(497 "editor",498 ["file'name.txt"],499 ["editor", "file'name.txt"],500 id="filename with single quote",501 ),502 ],503)504def test_editor_path_normalization(editor_cmd, filenames, expected_args):505 with patch("subprocess.Popen") as mock_popen:
57 unmodified lines
563 Editor(editor="nonexistent").edit_files(["f.txt"])564565566@pytest.mark.parametrize(567 ("pager_env", "expected_parts"),568 [569 # Simple commands.570 pytest.param("cat", ["cat"], id="simple command"),571 pytest.param("less", ["less"], id="less"),572 pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),573 # Whitespace handling.574 pytest.param("", [], id="empty string"),575 pytest.param(" ", [], id="whitespace only"),576 pytest.param(" less ", ["less"], id="leading and trailing spaces"),577 pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),578 # Quoted Windows paths: quotes are stripped in POSIX mode (the579 # default), preserving backslashes inside quoted tokens (issue #1026).580 pytest.param(581 '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',582 ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],583 id="quoted windows path with spaces",584 ),585 pytest.param(586 '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',587 ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],588 id="quoted windows path with flag",589 ),590 # Single-quoted path.591 pytest.param(592 "'/usr/local/bin/my pager'",593 ["/usr/local/bin/my pager"],594 id="single-quoted path with spaces",595 ),596 # Unix paths.597 pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),598 pytest.param(599 "/usr/bin/my\\ pager",600 ["/usr/bin/my pager"],601 id="escaped space in unix path",602 ),603 # PR #1477: POSIX mode (the default) eats unquoted backslashes.604 # On Windows, users must quote paths that contain backslashes.605 pytest.param(606 "C:\\path\\to\\exe /test other\\path",607 ["C:pathtoexe", "/test", "otherpath"],608 id="unquoted backslashes eaten in POSIX mode",609 ),610 ],611)612def test_pager_shlex_split(pager_env, expected_parts):613 """Verify shlex.split produces the expected argv for PAGER values.614615 Tests the splitting logic used by :func:`click._termui_impl.pager` to616 turn the ``PAGER`` environment variable into an ``argv`` list. See617 issue #1026, PR #1477, PR #1543, PR #2775.618 """619 assert shlex.split(pager_env) == expected_parts620621622def test_editor_unclosed_quote():623 """An unclosed quote in the editor command raises ValueError."""624 with pytest.raises(ValueError, match="No closing quotation"):625 Editor(editor='"unclosed').edit_files(["f.txt"])626627628@pytest.mark.parametrize(629 ("prompt_required", "required", "args", "expect"),630 [631 (True, False, None, "prompt"),632 (True, False, ["-v"], "Option '-v' requires an argument."),
301 unmodified lines