Added an edit function.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 895b1aa · Browse files · 6 files·+156 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+156 added−2 removed
- other:+156 added−2 removed
Provenance
- Commit
721e527- Tree
a3a3d82- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
895b1aa
6 files changed+156 added−2 removed
modified:click/__init__.py+2 added-2 removed
31 unmodified lines32 format_filename, get_app_dir33 34 # Terminal functions35 from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36- progressbar, clear, style, unstyle, secho36+ progressbar, clear, style, unstyle, secho, edit37 38 # Exceptions39 from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort24 unmodified lines65 'get_app_dir',66 67 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69- 'progressbar', 'clear', 'style', 'unstyle', 'secho',69+ 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit',70 71 # Exceptions72 'ClickException', 'UsageError', 'BadParameter', 'FileError',73 'Abort',10 unmodified linesmodified:click/_termui_impl.py+76 added
14 unmodified lines15 import math16 from ._compat import _default_text_stdout, range_type, PY2, isatty, \17 open_stream, strip_ansi18 from .utils import echo19+from .exceptions import ClickException20 21 22 if os.name == 'nt':23 BEFORE_BAR = '\r'265 unmodified lines289 290 def _nullpager(stream, text):291 """Simply print unformatted text. This is the ultimate fallback."""292 stream.write(strip_ansi(text))293+294+295+class Editor(object):296+297+ def __init__(self, editor=None, env=None, require_save=True,298+ extension='.txt'):299+ self.editor = editor300+ self.env = env301+ self.require_save = require_save302+ self.extension = extension303+304+ def get_editor(self):305+ if self.editor is not None:306+ return self.editor307+ for key in 'VISUAL', 'EDITOR':308+ rv = os.environ.get(key)309+ if rv:310+ return rv311+ if sys.platform.startswith('win'):312+ return 'notepad'313+ for editor in 'vim', 'nano':314+ if os.system('which %s &> /dev/null' % editor) == 0:315+ return editor316+ return 'vi'317+318+ def edit_file(self, filename):319+ import subprocess320+ editor = self.get_editor()321+ if self.env:322+ environ = os.environ.copy()323+ environ.update(self.env)324+ else:325+ environ = None326+ try:327+ c = subprocess.Popen([editor, filename], env=environ)328+ exit_code = c.wait()329+ if exit_code != 0:330+ raise ClickException('%s: Editing failed!' % editor)331+ except OSError as e:332+ raise ClickException('%s: Editing failed: %s' % (editor, e))333+334+ def edit(self, text):335+ import tempfile336+337+ if not text.endswith('\n'):338+ text += '\n'339+340+ fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)341+ try:342+ if sys.platform.startswith('win'):343+ encoding = 'utf-8-sig'344+ text = text.replace('\n', '\r\n')345+ else:346+ encoding = 'utf-8'347+ text = text.encode(encoding)348+349+ f = os.fdopen(fd, 'wb')350+ f.write(text)351+ f.close()352+ timestamp = os.path.getmtime(name)353+354+ self.edit_file(name)355+356+ if self.require_save \357+ and os.path.getmtime(name) == timestamp:358+ return None359+360+ f = open(name)361+ try:362+ rv = f.read()363+ finally:364+ f.close()365+ return rv.decode('utf-8-sig').replace('\r\n', '\n')366+ finally:367+ os.unlink(name)modified:click/termui.py+45 added
367 unmodified lines368 .. versionadded:: 2.0369 """370 text = style(text, **styles)371 return echo(text, file=file, nl=nl)372+373+374+def edit(text=None, editor=None, env=None, require_save=True,375+ extension='.txt', filename=None):376+ r"""Edits the given text in the defined editor. If an editor is given377+ (should be the full path to the executable but the regular operating378+ system search path is used for finding the executable) it overrides379+ the detected editor. Optionally some environment variables can be380+ used. If the editor is closed without changes `None` is returned. In381+ case a file is edited directly the return value is always `None` and382+ `require_save` and `extension` are ignored.383+384+ If the editor cannot be opened a :exc:`UsageError` is raised.385+386+ Example usage::387+388+ def get_commit_message():389+ MARKER = '# Everything below is ignored\n'390+ message = click.edit('\n\n' + MARKER)391+ if message is not None:392+ return message.split(MARKER, 1)[0].rstrip('\n')393+394+ Note for Windows: to simplify cross platform usage the newlines are395+ automatically converted from posix to windows and reverse. As such the396+ message here will have ``\n`` as newline markers.397+398+ :param text: the text to edit.399+ :param editor: optionally the editor to use. Defaults to automatic400+ detection.401+ :param env: environment variables to forward to the editor.402+ :param require_save: if this is true, then not saving in the editor403+ will make the return value become `None`.404+ :param extension: the extension to tell the editor about. This defaults405+ to utf-8 but changing this might change syntax406+ highlighting.407+ :param filename: if provided it will edit this file instead of the408+ provided text contents. It will not use a temporary409+ file as an indirection in that case.410+ """411+ from ._termui_impl import Editor412+ editor = Editor(editor=editor, env=env, require_save=require_save,413+ extension=extension)414+ if filename is None:415+ return editor.edit(text)416+ editor.edit_file(filename)modified:docs/api.rst+2 added
50 unmodified lines51 .. autofunction:: unstyle52 53 .. autofunction:: secho54 55+.. autofunction:: edit56+57 .. autofunction:: format_filename58 59 .. autofunction:: get_terminal_size60 101 unmodified linesmodified:docs/utils.rst+30 added
91 unmodified lines92 import click93 click.clear()94 95 96+Launching Editors97+-----------------98+99+.. versionadded:: 2.0100+101+Click supports launching editors automatically through :func:`edit`. This102+is very useful for asking users for multi-line input. It will103+automatically open the user's defined editor or fall back to a sensible104+default. If the user closes the editor without saving the return value105+will be `None` otherwise the entered text.106+107+Example usage::108+109+ import click110+111+ def get_commit_message():112+ MARKER = '# Everything below is ignored\n'113+ message = click.edit('\n\n' + MARKER)114+ if message is not None:115+ return message.split(MARKER, 1)[0].rstrip('\n')116+117+Alternatively the function can also be used to launch editors for files by118+a specific filename. In that case the return value is always `None`.119+120+Example usage::121+122+ import click123+ click.edit(filename='/etc/passwd')124+125+126 Printing Filenames127 ------------------128 129 Because filenames might not be unicode, formatting them can be a bit113 unmodified linesmodified:CHANGES+1 added
23 unmodified lines24 passed as second argument. There is legacy support for old callbacks25 which will warn but still execute the script.26 - Added :func:`style`, :func:`unstyle` and :func:`secho` for ANSI27 styles.28+- Added an :func:`edit` function that invokes the default editor.29 30 Version 1.131 -----------32 11 unmodified lines