Skip to content
Myr

Add support of `pathlib.Path` to `edit` (#3781)

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

authored by Rowlando13 · committed by GitHub · parents 2103e15, a1d8785 · 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

5 files+47 added−11 removed

modified:src/click/_termui_impl.py+1 added-1 removed
708 unmodified lines
709 if which(editor) is not None:710 return editor711 return "vi"712713 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 lines
modified:src/click/termui.py+19 added-8 removed
2 unmodified lines
3import collections.abc as cabc4import inspect5import io6import itertools7import os8import re9import sys10import typing as t11from contextlib import AbstractContextManager
825 unmodified lines
837 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: ...846847848def edit(
1 unmodified line
850 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 overrides
18 unmodified lines
880 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.890891 .. 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.894895 .. versionchanged:: 8.5.0896 ``filename`` accepts ``os.PathLike`` values in addition to strings.897898 """899 from ._termui_impl import Editor900901 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)902903 if filename is None:904 return ed.edit(text)905895 if isinstance(filename, str):906 if isinstance(filename, (str, os.PathLike)):907 filename = (filename,)908909 ed.edit_files(filenames=filename)910 return None
104 unmodified lines
added:tests/typing/typing_edit.py+10 added
1from pathlib import Path23from typing_extensions import assert_type45import click67# ``filename`` accepts a path or an iterable of paths.8assert_type(click.edit(filename="f.txt"), None)9assert_type(click.edit(filename=Path("f.txt")), None)10assert_type(click.edit(filename=["f.txt", Path("g.txt")]), None)
modified:tests/test_termui.py+15 added-2 removed
419 unmodified lines
420 with pytest.raises(exc):421 click.getchar()422423424@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")424@pytest.mark.skipif(WIN, reason="No sed on Windows.")425def test_fast_edit(runner):426 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")427 assert result == "aTest\nbTest\n"428429430@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")430@pytest.mark.skipif(WIN, reason="No sed on Windows.")431def 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 lines
447 # terminated by newline too.448 assert reopened_file.read() == "aTest\nbTest\n"449450451@pytest.mark.skipif(WIN, reason="No sed on Windows.")452@pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"])453def 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_path458459 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"462463464@pytest.mark.parametrize(465 ("editor_cmd", "filenames", "expected_args"),466 [467 pytest.param(
1517 unmodified lines
modified:CHANGES.md+2 added
87 unmodified lines
88 `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`9495## Version 8.4.29697Released 2026-06-24
1561 unmodified lines