chiark / gitweb /
b9699d58ae2c98df458c31a1daaec689325ad42e
[stgit] / stgit / commands / edit.py
1 """Patch editing command
2 """
3
4 __copyright__ = """
5 Copyright (C) 2007, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 from optparse import OptionParser, make_option
22 from email.Utils import formatdate
23
24 from stgit.commands.common import *
25 from stgit.utils import *
26 from stgit.out import *
27 from stgit import stack, git
28
29
30 help = 'edit a patch description or diff'
31 usage = """%prog [options] [<patch>]
32
33 Edit the description and author information of the given patch (or the
34 current patch if no patch name was given). With --diff, also edit the
35 diff.
36
37 The editor is invoked with the following contents:
38
39   From: A U Thor <author@example.com>
40   Date: creation date
41
42   Patch description
43
44 If --diff was specified, the diff appears at the bottom, after a
45 separator:
46
47   ---
48
49   Diff text
50
51 Command-line options can be used to modify specific information
52 without invoking the editor.
53
54 If the patch diff is edited but the patch application fails, the
55 rejected patch is stored in the .stgit-failed.patch file (and also in
56 .stgit-edit.{diff,txt}). The edited patch can be replaced with one of
57 these files using the '--file' and '--diff' options.
58 """
59
60 directory = DirectoryGotoToplevel()
61 options = [make_option('-d', '--diff',
62                        help = 'edit the patch diff',
63                        action = 'store_true'),
64            make_option('-O', '--diff-opts',
65                        help = 'options to pass to git-diff'),
66            make_option('--undo',
67                        help = 'revert the commit generated by the last edit',
68                        action = 'store_true'),
69            make_option('-a', '--annotate', metavar = 'NOTE',
70                        help = 'annotate the patch log entry'),
71            make_option('--author', metavar = '"NAME <EMAIL>"',
72                        help = 'replae the author details with "NAME <EMAIL>"'),
73            make_option('--authname',
74                        help = 'replace the author name with AUTHNAME'),
75            make_option('--authemail',
76                        help = 'replace the author e-mail with AUTHEMAIL'),
77            make_option('--authdate',
78                        help = 'replace the author date with AUTHDATE'),
79            make_option('--commname',
80                        help = 'replace the committer name with COMMNAME'),
81            make_option('--commemail',
82                        help = 'replace the committer e-mail with COMMEMAIL')
83            ] + make_sign_options() + make_message_options()
84
85 def __update_patch(pname, text, options):
86     """Update the current patch from the given text.
87     """
88     patch = crt_series.get_patch(pname)
89
90     bottom = patch.get_bottom()
91     top = patch.get_top()
92
93     message, author_name, author_email, author_date, diff = parse_patch(text)
94
95     out.start('Updating patch "%s"' % pname)
96
97     if options.diff:
98         git.switch(bottom)
99         try:
100             git.apply_patch(diff = diff)
101         except:
102             # avoid inconsistent repository state
103             git.switch(top)
104             raise
105
106     def c(a, b):
107         if a != None:
108             return a
109         return b
110     crt_series.refresh_patch(message = message,
111                              author_name = c(options.authname, author_name),
112                              author_email = c(options.authemail, author_email),
113                              author_date = c(options.authdate, author_date),
114                              committer_name = options.commname,
115                              committer_email = options.commemail,
116                              backup = True, sign_str = options.sign_str,
117                              log = 'edit', notes = options.annotate)
118
119     if crt_series.empty_patch(pname):
120         out.done('empty patch')
121     else:
122         out.done()
123
124 def __generate_file(pname, write_fn, options):
125     """Generate a file containing the description to edit
126     """
127     patch = crt_series.get_patch(pname)
128
129     if options.diff_opts:
130         if not options.diff:
131             raise CmdException, '--diff-opts only available with --diff'
132         diff_flags = options.diff_opts.split()
133     else:
134         diff_flags = []
135
136     # generate the file to be edited
137     descr = patch.get_description().strip()
138     authdate = patch.get_authdate()
139
140     tmpl = 'From: %(authname)s <%(authemail)s>\n'
141     if authdate:
142         tmpl += 'Date: %(authdate)s\n'
143     tmpl += '\n%(descr)s\n'
144
145     tmpl_dict = {
146         'descr': descr,
147         'authname': patch.get_authname(),
148         'authemail': patch.get_authemail(),
149         'authdate': patch.get_authdate()
150         }
151
152     if options.diff:
153         # add the patch diff to the edited file
154         bottom = patch.get_bottom()
155         top = patch.get_top()
156
157         tmpl += '---\n\n' \
158                 '%(diffstat)s\n' \
159                 '%(diff)s'
160
161         tmpl_dict['diffstat'] = git.diffstat(rev1 = bottom, rev2 = top)
162         tmpl_dict['diff'] = git.diff(rev1 = bottom, rev2 = top,
163                                      diff_flags = diff_flags)
164
165     for key in tmpl_dict:
166         # make empty strings if key is not available
167         if tmpl_dict[key] is None:
168             tmpl_dict[key] = ''
169
170     text = tmpl % tmpl_dict
171
172     # write the file to be edited
173     write_fn(text)
174
175 def __edit_update_patch(pname, options):
176     """Edit the given patch interactively.
177     """
178     if options.diff:
179         fname = '.stgit-edit.diff'
180     else:
181         fname = '.stgit-edit.txt'
182     def write_fn(text):
183         f = file(fname, 'w')
184         f.write(text)
185         f.close()
186
187     __generate_file(pname, write_fn, options)
188
189     # invoke the editor
190     call_editor(fname)
191
192     __update_patch(pname, file(fname).read(), options)
193
194 def func(parser, options, args):
195     """Edit the given patch or the current one.
196     """
197     crt_pname = crt_series.get_current()
198
199     if not args:
200         pname = crt_pname
201         if not pname:
202             raise CmdException, 'No patches applied'
203     elif len(args) == 1:
204         pname = args[0]
205         if crt_series.patch_unapplied(pname) or crt_series.patch_hidden(pname):
206             raise CmdException, 'Cannot edit unapplied or hidden patches'
207         elif not crt_series.patch_applied(pname):
208             raise CmdException, 'Unknown patch "%s"' % pname
209     else:
210         parser.error('incorrect number of arguments')
211
212     check_local_changes()
213     check_conflicts()
214     check_head_top_equal(crt_series)
215
216     if pname != crt_pname:
217         # Go to the patch to be edited
218         applied = crt_series.get_applied()
219         between = applied[:applied.index(pname):-1]
220         pop_patches(crt_series, between)
221
222     if options.author:
223         options.authname, options.authemail = name_email(options.author)
224
225     if options.undo:
226         out.start('Undoing the editing of "%s"' % pname)
227         crt_series.undo_refresh()
228         out.done()
229     elif options.save_template:
230         __generate_file(pname, options.save_template, options)
231     elif any([options.message, options.authname, options.authemail,
232               options.authdate, options.commname, options.commemail,
233               options.sign_str]):
234         out.start('Updating patch "%s"' % pname)
235         __update_patch(pname, options.message, options)
236         out.done()
237     else:
238         __edit_update_patch(pname, options)
239
240     if pname != crt_pname:
241         # Push the patches back
242         between.reverse()
243         push_patches(crt_series, between)