models: wrap long lines
[git-cola.git] / cola / editpatch.py
blob339ca470cb9019bda8f9aff4e0c4c29da34dde41
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 textwrap.fill(
14 text,
15 width=80,
16 initial_indent=indent,
17 subsequent_indent=indent,
18 ) + '\n'
21 def strip_comments(context, text):
22 comment_char = prefs.comment_char(context)
23 return '\n'.join(
24 line for line in text.split('\n') if not line.startswith(comment_char)
28 def patch_edit_header(context, *, reverse, apply_to_worktree):
29 if apply_to_worktree:
30 header = N_(
31 "Edit the following patch, which will then be applied to the worktree to"
32 " revert the changes:"
34 else:
35 if reverse:
36 header = N_(
37 "Edit the following patch, which will then be applied to the staging"
38 " area to unstage the changes:"
40 else:
41 header = N_(
42 "Edit the following patch, which will then be applied to the staging"
43 " area to stage the changes:"
45 return wrap_comment(context, header)
48 def patch_edit_footer(context):
49 parts = [
50 '---',
51 N_(
52 "To avoid applying removal lines ('-'), change them to context lines (' ')."
54 N_("To avoid applying addition lines ('+'), delete them."),
55 N_("To abort applying this patch, remove all lines."),
56 N_("Lines starting with '%s' will be ignored.") % prefs.comment_char(context),
57 N_(
58 "It is not necessary to update the hunk header lines as they will be"
59 " regenerated automatically."
62 return ''.join(wrap_comment(context, part) for part in parts)
65 def edit_patch(patch, encoding, context, *, reverse, apply_to_worktree):
66 patch_file_path = utils.tmp_filename('edit', '.patch')
67 try:
68 content_parts = [
69 patch_edit_header(
70 context, reverse=reverse, apply_to_worktree=apply_to_worktree
72 patch.as_text(file_headers=False),
73 patch_edit_footer(context),
75 core.write(patch_file_path, ''.join(content_parts), encoding=encoding)
76 status, _, _ = core.run_command(
77 [*utils.shell_split(prefs.editor(context)), patch_file_path]
79 if status == 0:
80 patch_text = strip_comments(
81 context, core.read(patch_file_path, encoding=encoding)
83 else:
84 Interaction.log(
85 N_("Editor returned %s exit code. Not applying patch.") % status
87 patch_text = ''
88 return diffparse.Patch.parse(patch.filename, patch_text)
89 finally:
90 core.unlink(patch_file_path)