Add support of `pathlib.Path` to `edit`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes #2869
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 2103e15 · Browse files · 5 files·+47 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+47 added−11 removed
- tests:+25 added−2 removed
- other:+22 added−9 removed
Provenance
- Commit
a1d8785- Tree
5492745- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
2103e15
5 files changed+47 added−11 removed
modified:src/click/_termui_impl.py+1 added-1 removed
708 unmodified lines709 if which(editor) is not None:710 return editor711 return "vi"712 713- def edit_files(self, filenames: cabc.Iterable[str]) -> None:713+ def edit_files(self, filenames: cabc.Iterable[str | os.PathLike[str]]) -> None:714 """Open files in the user's editor."""715 import shlex716 import subprocess717 255 unmodified linesmodified:src/click/termui.py+19 added-8 removed
2 unmodified lines3 import collections.abc as cabc4 import inspect5 import io6 import itertools7+import os8 import re9 import sys10 import typing as t11 from contextlib import AbstractContextManager825 unmodified lines837 editor: str | None = None,838 env: cabc.Mapping[str, str] | None = None,839 require_save: bool = True,840 extension: str = ".txt",840- filename: str | cabc.Iterable[str] | None = None,841+ filename: str842+ | os.PathLike[str]843+ | cabc.Iterable[str | os.PathLike[str]]844+ | None = None,845 ) -> None: ...846 847 848 def edit(1 unmodified line850 editor: str | None = None,851 env: cabc.Mapping[str, str] | None = None,852 require_save: bool = True,853 extension: str = ".txt",850- filename: str | cabc.Iterable[str] | None = None,854+ filename: str855+ | os.PathLike[str]856+ | cabc.Iterable[str | os.PathLike[str]]857+ | None = None,858 ) -> str | bytes | bytearray | None:859 r"""Edits the given text in the defined editor. If an editor is given860 (should be the full path to the executable but the regular operating861 system search path is used for finding the executable) it overrides18 unmodified lines880 to `.txt` but changing this might change syntax881 highlighting.882 :param filename: if provided it will edit this file instead of the883 provided text contents. It will not use a temporary877- file as an indirection in that case. If the editor supports878- editing multiple files at once, a sequence of files may be879- passed as well. Invoke `click.file` once per file instead880- if multiple files cannot be managed at once or editing the881- files serially is desired.884+ file as an indirection in that case. It accepts a path885+ or any iterable of paths. If the editor supports886+ editing multiple files at once, a sequence of files may887+ be passed as well. Invoke `click.file` once per file888+ instead if multiple files cannot be managed at once or889+ editing the files serially is desired.890 891 .. versionchanged:: 8.2.0892 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``893 if the ``editor`` supports editing multiple files at once.894 895+ .. versionchanged:: 8.5.0896+ ``filename`` accepts ``os.PathLike`` values in addition to strings.897+898 """899 from ._termui_impl import Editor900 901 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)902 903 if filename is None:904 return ed.edit(text)905 895- if isinstance(filename, str):906+ if isinstance(filename, (str, os.PathLike)):907 filename = (filename,)908 909 ed.edit_files(filenames=filename)910 return None104 unmodified linesadded:tests/typing/typing_edit.py+10 added
1+from pathlib import Path2+3+from typing_extensions import assert_type4+5+import click6+7+# ``filename`` accepts a path or an iterable of paths.8+assert_type(click.edit(filename="f.txt"), None)9+assert_type(click.edit(filename=Path("f.txt")), None)10+assert_type(click.edit(filename=["f.txt", Path("g.txt")]), None)modified:tests/test_termui.py+15 added-2 removed
419 unmodified lines420 with pytest.raises(exc):421 click.getchar()422 423 424-@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")424+@pytest.mark.skipif(WIN, reason="No sed on Windows.")425 def test_fast_edit(runner):426 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")427 assert result == "aTest\nbTest\n"428 429 430-@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")430+@pytest.mark.skipif(WIN, reason="No sed on Windows.")431 def test_edit(runner):432 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:433 named_tempfile.write("a\nb\n")434 named_tempfile.flush()12 unmodified lines447 # terminated by newline too.448 assert reopened_file.read() == "aTest\nbTest\n"449 450 451+@pytest.mark.skipif(WIN, reason="No sed on Windows.")452+@pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"])453+def test_edit_pathlib(runner, tmp_path, use_iterable):454+ """Issue #2869: ``filename`` accepts ``os.PathLike`` values."""455+ file_path = tmp_path / "file.txt"456+ file_path.write_text("a\nb\n", encoding="UTF-8")457+ filename = [file_path] if use_iterable else file_path458+459+ result = click.edit(filename=filename, editor="sed -i~ 's/$/Test/'")460+ assert result is None461+ assert file_path.read_text(encoding="UTF-8") == "aTest\nbTest\n"462+463+464 @pytest.mark.parametrize(465 ("editor_cmd", "filenames", "expected_args"),466 [467 pytest.param(1517 unmodified linesmodified:CHANGES.md+2 added
87 unmodified lines88 `PAGER="less -R"` now invokes `less -R` on the temporary file rather than89 bare `less`. {pr}`3777`90 - Improve raw mode detection by parsing the option tokens. {issue}`3416`91 {pr}`3777`92+- {func}`edit` accepts `os.PathLike` values for `filename`, in addition to93+ strings. {issue}`2869` {pr}`3781`94 95 ## Version 8.4.296 97 Released 2026-06-241561 unmodified lines