Adds support for editing multiple files (#2068)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yash Rathi · committed by GitHub · parent d791537 · Browse files · 4 files·+62 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Andreas Backx <andreas@backx.org>
Diff stats
4 files+62 added−6 removed
- tests:+15 added−0 removed
- other:+47 added−6 removed
Provenance
- Commit
0d69b6c- Tree
9105a1b- Author
Yash Rathi <57002207+yashrathi-git@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d791537
4 files changed+62 added−6 removed
modified:src/click/_termui_impl.py+7 added-3 removed
503 unmodified lines504 if os.system(f"which {editor} >/dev/null 2>&1") == 0:505 return editor506 return "vi"507 508- def edit_file(self, filename: str) -> None:508+ def edit_files(self, filenames: cabc.Iterable[str]) -> None:509 import subprocess510 511 editor = self.get_editor()512 environ: dict[str, str] | None = None1 unmodified line514 if self.env:515 environ = os.environ.copy()516 environ.update(self.env)517 518+ exc_filename = " ".join(f'"{filename}"' for filename in filenames)519+520 try:519- c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)521+ c = subprocess.Popen(522+ args=f"{editor} {exc_filename}", env=environ, shell=True523+ )524 exit_code = c.wait()525 if exit_code != 0:526 raise ClickException(527 _("{editor}: Editing failed").format(editor=editor)34 unmodified lines562 # Depending on the resolution, the exact value might not be563 # recorded, so get the new recorded value.564 timestamp = os.path.getmtime(name)565 562- self.edit_file(name)566+ self.edit_files((name,))567 568 if self.require_save and os.path.getmtime(name) == timestamp:569 return None570 178 unmodified linesmodified:src/click/termui.py+36 added-3 removed
641 unmodified lines642 643 return echo(message, file=file, nl=nl, err=err, color=color)644 645 646+@t.overload647 def edit(648+ text: t.AnyStr,649+ editor: str | None = None,650+ env: cabc.Mapping[str, str] | None = None,651+ require_save: bool = True,652+ extension: str = ".txt",653+) -> t.AnyStr: ...654+655+656+@t.overload657+def edit(658+ text: None = None,659+ editor: str | None = None,660+ env: cabc.Mapping[str, str] | None = None,661+ require_save: bool = True,662+ extension: str = ".txt",663+ filename: str | cabc.Iterable[str] | None = None,664+) -> None: ...665+666+667+def edit(668 text: t.AnyStr | None = None,669 editor: str | None = None,670 env: cabc.Mapping[str, str] | None = None,671 require_save: bool = True,672 extension: str = ".txt",652- filename: str | None = None,673+ filename: str | cabc.Iterable[str] | None = None,674 ) -> t.AnyStr | None:675 r"""Edits the given text in the defined editor. If an editor is given676 (should be the full path to the executable but the regular operating677 system search path is used for finding the executable) it overrides18 unmodified lines696 to `.txt` but changing this might change syntax697 highlighting.698 :param filename: if provided it will edit this file instead of the699 provided text contents. It will not use a temporary679- file as an indirection in that case.700+ file as an indirection in that case. If the editor supports701+ editing multiple files at once, a sequence of files may be702+ passed as well. Invoke `click.file` once per file instead703+ if multiple files cannot be managed at once or editing the704+ files serially is desired.705+706+ .. versionchanged:: 8.2.0707+ ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``708+ if the ``editor`` supports editing multiple files at once.709+710 """711 from ._termui_impl import Editor712 713 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)714 715 if filename is None:716 return ed.edit(text)717 718+ if isinstance(filename, str):719+ filename = (filename,)720+688- ed.edit_file(filename)721+ ed.edit_files(filenames=filename)722 return None723 724 725 def launch(url: str, wait: bool = False, locate: bool = False) -> int:101 unmodified linesmodified:tests/test_termui.py+15 added
1 import platform2+import tempfile3 import time4 5 import pytest6 373 unmodified lines380 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")381 assert result == "aTest\nbTest\n"382 383 384+@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")385+def test_edit(runner):386+ with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:387+ named_tempfile.write("a\nb")388+ named_tempfile.flush()389+390+ result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")391+ assert result is None392+393+ # We need ot reopen the file as it becomes unreadable after the edit.394+ with open(named_tempfile.name) as reopened_file:395+ assert reopened_file.read() == "aTest\nbTest"396+397+398 @pytest.mark.parametrize(399 ("prompt_required", "required", "args", "expect"),400 [401 (True, False, None, "prompt"),86 unmodified linesmodified:CHANGES.rst+4 added
60 unmodified lines61 :issue:`1489` :pr:`1489`62 - Contexts created during shell completion are closed properly, fixing63 ``ResourceWarning``s when using ``click.File``. :issue:`2644` :pr:`2800`64 :pr:`2767`65+- ``click.edit(filename)`` now supports passing an iterable of filenames in66+ case the editor supports editing multiple files at once. Its return type67+ is now also typed: ``AnyStr`` if ``text`` is passed, otherwise ``None``.68+ :issue:`2067` :pr:`2068`69 70 71 Version 8.1.872 -------------1118 unmodified lines