Add patch editing command
[stgit] / stgit / commands / imprt.py
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License version 2 as
6 published by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 """
17
18 import sys, os, re, email
19 from mailbox import UnixMailbox
20 from StringIO import StringIO
21 from optparse import OptionParser, make_option
22
23 from stgit.commands.common import *
24 from stgit.utils import *
25 from stgit.out import *
26 from stgit import stack, git
27
28
29 help = 'import a GNU diff file as a new patch'
30 usage = """%prog [options] [<file>|<url>]
31
32 Create a new patch and apply the given GNU diff file (or the standard
33 input). By default, the file name is used as the patch name but this
34 can be overridden with the '--name' option. The patch can either be a
35 normal file with the description at the top or it can have standard
36 mail format, the Subject, From and Date headers being used for
37 generating the patch information. The command can also read series and
38 mbox files.
39
40 If a patch does not apply cleanly, the failed diff is written to the
41 .stgit-failed.patch file and an empty StGIT patch is added to the
42 stack.
43
44 The patch description has to be separated from the data with a '---'
45 line."""
46
47 options = [make_option('-m', '--mail',
48 help = 'import the patch from a standard e-mail file',
49 action = 'store_true'),
50 make_option('-M', '--mbox',
51 help = 'import a series of patches from an mbox file',
52 action = 'store_true'),
53 make_option('-s', '--series',
54 help = 'import a series of patches',
55 action = 'store_true'),
56 make_option('-u', '--url',
57 help = 'import a patch from a URL',
58 action = 'store_true'),
59 make_option('-n', '--name',
60 help = 'use NAME as the patch name'),
61 make_option('-t', '--strip',
62 help = 'strip numbering and extension from patch name',
63 action = 'store_true'),
64 make_option('-i', '--ignore',
65 help = 'ignore the applied patches in the series',
66 action = 'store_true'),
67 make_option('--replace',
68 help = 'replace the unapplied patches in the series',
69 action = 'store_true'),
70 make_option('-b', '--base',
71 help = 'use BASE instead of HEAD for file importing'),
72 make_option('-e', '--edit',
73 help = 'invoke an editor for the patch description',
74 action = 'store_true'),
75 make_option('-p', '--showpatch',
76 help = 'show the patch content in the editor buffer',
77 action = 'store_true'),
78 make_option('-a', '--author', metavar = '"NAME <EMAIL>"',
79 help = 'use "NAME <EMAIL>" as the author details'),
80 make_option('--authname',
81 help = 'use AUTHNAME as the author name'),
82 make_option('--authemail',
83 help = 'use AUTHEMAIL as the author e-mail'),
84 make_option('--authdate',
85 help = 'use AUTHDATE as the author date'),
86 make_option('--commname',
87 help = 'use COMMNAME as the committer name'),
88 make_option('--commemail',
89 help = 'use COMMEMAIL as the committer e-mail')
90 ] + make_sign_options()
91
92
93 def __strip_patch_name(name):
94 stripped = re.sub('^[0-9]+-(.*)$', '\g<1>', name)
95 stripped = re.sub('^(.*)\.(diff|patch)$', '\g<1>', stripped)
96
97 return stripped
98
99 def __replace_slashes_with_dashes(name):
100 stripped = name.replace('/', '-')
101
102 return stripped
103
104 def __create_patch(filename, message, author_name, author_email,
105 author_date, diff, options):
106 """Create a new patch on the stack
107 """
108 if options.name:
109 patch = options.name
110 elif filename:
111 patch = os.path.basename(filename)
112 else:
113 patch = ''
114 if options.strip:
115 patch = __strip_patch_name(patch)
116
117 if not patch:
118 if options.ignore or options.replace:
119 unacceptable_name = lambda name: False
120 else:
121 unacceptable_name = crt_series.patch_exists
122 patch = make_patch_name(message, unacceptable_name)
123 else:
124 # fix possible invalid characters in the patch name
125 patch = re.sub('[^\w.]+', '-', patch).strip('-')
126
127 if options.ignore and patch in crt_series.get_applied():
128 out.info('Ignoring already applied patch "%s"' % patch)
129 return
130 if options.replace and patch in crt_series.get_unapplied():
131 crt_series.delete_patch(patch)
132
133 # refresh_patch() will invoke the editor in this case, with correct
134 # patch content
135 if not message:
136 can_edit = False
137
138 committer_name = committer_email = None
139
140 if options.author:
141 options.authname, options.authemail = name_email(options.author)
142
143 # override the automatically parsed settings
144 if options.authname:
145 author_name = options.authname
146 if options.authemail:
147 author_email = options.authemail
148 if options.authdate:
149 author_date = options.authdate
150 if options.commname:
151 committer_name = options.commname
152 if options.commemail:
153 committer_email = options.commemail
154
155 crt_series.new_patch(patch, message = message, can_edit = False,
156 author_name = author_name,
157 author_email = author_email,
158 author_date = author_date,
159 committer_name = committer_name,
160 committer_email = committer_email)
161
162 if not diff:
163 out.warn('No diff found, creating empty patch')
164 else:
165 out.start('Importing patch "%s"' % patch)
166 if options.base:
167 git.apply_patch(diff = diff, base = git_id(options.base))
168 else:
169 git.apply_patch(diff = diff)
170 crt_series.refresh_patch(edit = options.edit,
171 show_patch = options.showpatch,
172 sign_str = options.sign_str)
173 out.done()
174
175 def __import_file(filename, options, patch = None):
176 """Import a patch from a file or standard input
177 """
178 if filename:
179 f = file(filename)
180 else:
181 f = sys.stdin
182
183 if options.mail:
184 try:
185 msg = email.message_from_file(f)
186 except Exception, ex:
187 raise CmdException, 'error parsing the e-mail file: %s' % str(ex)
188 message, author_name, author_email, author_date, diff = \
189 parse_mail(msg)
190 else:
191 message, author_name, author_email, author_date, diff = \
192 parse_patch(f)
193
194 if filename:
195 f.close()
196
197 if patch:
198 pname = patch
199 else:
200 pname = filename
201
202 __create_patch(pname, message, author_name, author_email,
203 author_date, diff, options)
204
205 def __import_series(filename, options):
206 """Import a series of patches
207 """
208 applied = crt_series.get_applied()
209
210 if filename:
211 f = file(filename)
212 patchdir = os.path.dirname(filename)
213 else:
214 f = sys.stdin
215 patchdir = ''
216
217 for line in f:
218 patch = re.sub('#.*$', '', line).strip()
219 if not patch:
220 continue
221 patchfile = os.path.join(patchdir, patch)
222 patch = __replace_slashes_with_dashes(patch);
223
224 __import_file(patchfile, options, patch)
225
226 if filename:
227 f.close()
228
229 def __import_mbox(filename, options):
230 """Import a series from an mbox file
231 """
232 if filename:
233 f = file(filename, 'rb')
234 else:
235 f = StringIO(sys.stdin.read())
236
237 try:
238 mbox = UnixMailbox(f, email.message_from_file)
239 except Exception, ex:
240 raise CmdException, 'error parsing the mbox file: %s' % str(ex)
241
242 for msg in mbox:
243 message, author_name, author_email, author_date, diff = \
244 parse_mail(msg)
245 __create_patch(None, message, author_name, author_email,
246 author_date, diff, options)
247
248 f.close()
249
250 def __import_url(url, options):
251 """Import a patch from a URL
252 """
253 import urllib
254 import tempfile
255
256 if not url:
257 parser.error('URL argument required')
258
259 patch = os.path.basename(urllib.unquote(url))
260 filename = os.path.join(tempfile.gettempdir(), patch)
261 urllib.urlretrieve(url, filename)
262 __import_file(filename, options)
263
264 def func(parser, options, args):
265 """Import a GNU diff file as a new patch
266 """
267 if len(args) > 1:
268 parser.error('incorrect number of arguments')
269
270 check_local_changes()
271 check_conflicts()
272 check_head_top_equal()
273
274 if len(args) == 1:
275 filename = args[0]
276 else:
277 filename = None
278
279 if options.series:
280 __import_series(filename, options)
281 elif options.mbox:
282 __import_mbox(filename, options)
283 elif options.url:
284 __import_url(filename, options)
285 else:
286 __import_file(filename, options)
287
288 print_crt_patch()