Skip to content
Myr

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

6 files+156 added−2 removed

modified:click/__init__.py+2 added-2 removed
31 unmodified lines
32 format_filename, get_app_dir3334# Terminal functions35from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36 progressbar, clear, style, unstyle, secho36 progressbar, clear, style, unstyle, secho, edit3738# Exceptions39from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort
24 unmodified lines
65 'get_app_dir',6667 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69 'progressbar', 'clear', 'style', 'unstyle', 'secho',69 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit',7071 # Exceptions72 'ClickException', 'UsageError', 'BadParameter', 'FileError',73 'Abort',
10 unmodified lines
modified:click/_termui_impl.py+76 added
14 unmodified lines
15import math16from ._compat import _default_text_stdout, range_type, PY2, isatty, \17 open_stream, strip_ansi18from .utils import echo19from .exceptions import ClickException202122if os.name == 'nt':23 BEFORE_BAR = '\r'
265 unmodified lines
289290def _nullpager(stream, text):291 """Simply print unformatted text. This is the ultimate fallback."""292 stream.write(strip_ansi(text))293294295class Editor(object):296297 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 = extension303304 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'317318 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))333334 def edit(self, text):335 import tempfile336337 if not text.endswith('\n'):338 text += '\n'339340 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)348349 f = os.fdopen(fd, 'wb')350 f.write(text)351 f.close()352 timestamp = os.path.getmtime(name)353354 self.edit_file(name)355356 if self.require_save \357 and os.path.getmtime(name) == timestamp:358 return None359360 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 lines
368 .. versionadded:: 2.0369 """370 text = style(text, **styles)371 return echo(text, file=file, nl=nl)372373374def 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.383384 If the editor cannot be opened a :exc:`UsageError` is raised.385386 Example usage::387388 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')393394 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.397398 :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 lines
51.. autofunction:: unstyle5253.. autofunction:: secho5455.. autofunction:: edit5657.. autofunction:: format_filename5859.. autofunction:: get_terminal_size60
101 unmodified lines
modified:docs/utils.rst+30 added
91 unmodified lines
92 import click93 click.clear()949596Launching Editors97-----------------9899.. versionadded:: 2.0100101Click supports launching editors automatically through :func:`edit`. This102is very useful for asking users for multi-line input. It will103automatically open the user's defined editor or fall back to a sensible104default. If the user closes the editor without saving the return value105will be `None` otherwise the entered text.106107Example usage::108109 import click110111 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')116117Alternatively the function can also be used to launch editors for files by118a specific filename. In that case the return value is always `None`.119120Example usage::121122 import click123 click.edit(filename='/etc/passwd')124125126Printing Filenames127------------------128129Because filenames might not be unicode, formatting them can be a bit
113 unmodified lines
modified:CHANGES+1 added
23 unmodified lines
24 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.2930Version 1.131-----------32
11 unmodified lines