Merge pull request #1391 from davvid/macos/hotkeys
[git-cola.git] / cola / editpatch.py
blobb73ded0ab5a0f17bdfd76d5d8abe98c0bc8064d5
1 import textwrap
3 from . import core
4 from . import diffparse
5 from . import utils
6 from .i18n import N_
7 from .interaction import Interaction
8 from .models import prefs
11 def wrap_comment(context, text):
12 indent = prefs.comment_char(context) + ' '
13 return (
14 textwrap.fill(
15 text,
16 width=80,
17 initial_indent=indent,
18 subsequent_indent=indent,
20 + '\n'
24 def strip_comments(context, text):
25 comment_char = prefs.comment_char(context)
26 return '\n'.join(
27 line for line in text.split('\n') if not line.startswith(comment_char)
31 def patch_edit_header(context, *, reverse, apply_to_worktree):
32 if apply_to_worktree:
33 header = N_(
34 'Edit the following patch, which will then be applied to the worktree to'
35 ' revert the changes:'
37 else:
38 if reverse:
39 header = N_(
40 'Edit the following patch, which will then be applied to the staging'
41 ' area to unstage the changes:'
43 else:
44 header = N_(
45 'Edit the following patch, which will then be applied to the staging'
46 ' area to stage the changes:'
48 return wrap_comment(context, header)
51 def patch_edit_footer(context):
52 parts = [
53 '---',
54 N_(
55 "To avoid applying removal lines ('-'), change them to context lines (' ')."
57 N_("To avoid applying addition lines ('+'), delete them."),
58 N_('To abort applying this patch, remove all lines.'),
59 N_("Lines starting with '%s' will be ignored.") % prefs.comment_char(context),
60 N_(
61 'It is not necessary to update the hunk header lines as they will be'
62 ' regenerated automatically.'
65 return ''.join(wrap_comment(context, part) for part in parts)
68 def edit_patch(patch, encoding, context, *, reverse, apply_to_worktree):
69 patch_file_path = utils.tmp_filename('edit', '.patch')
70 try:
71 content_parts = [
72 patch_edit_header(
73 context, reverse=reverse, apply_to_worktree=apply_to_worktree
75 patch.as_text(file_headers=False),
76 patch_edit_footer(context),
78 core.write(patch_file_path, ''.join(content_parts), encoding=encoding)
79 status, _, _ = core.run_command(
80 [*utils.shell_split(prefs.editor(context)), patch_file_path]
82 if status == 0:
83 patch_text = strip_comments(
84 context, core.read(patch_file_path, encoding=encoding)
86 else:
87 Interaction.log(
88 N_('Editor returned %s exit code. Not applying patch.') % status
90 patch_text = ''
91 return diffparse.Patch.parse(patch.filename, patch_text)
92 finally:
93 core.unlink(patch_file_path)