Merge branch 'stable'
[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 directory = DirectoryHasRepository()
48 options = [make_option('-m', '--mail',
49 help = 'import the patch from a standard e-mail file',
50 action = 'store_true'),
51 make_option('-M', '--mbox',
52 help = 'import a series of patches from an mbox file',
53 action = 'store_true'),
54 make_option('-s', '--series',
55 help = 'import a series of patches',
56 action = 'store_true'),
57 make_option('-u', '--url',
58 help = 'import a patch from a URL',
59 action = 'store_true'),
60 make_option('-n', '--name',
61 help = 'use NAME as the patch name'),
62 make_option('-t', '--strip',
63 help = 'strip numbering and extension from patch name',
64 action = 'store_true'),
65 make_option('-i', '--ignore',
66 help = 'ignore the applied patches in the series',
67 action = 'store_true'),
68 make_option('--replace',
69 help = 'replace the unapplied patches in the series',
70 action = 'store_true'),
71 make_option('-b', '--base',
72 help = 'use BASE instead of HEAD for file importing'),
73 make_option('-e', '--edit',
74 help = 'invoke an editor for the patch description',
75 action = 'store_true'),
76 make_option('-p', '--showpatch',
77 help = 'show the patch content in the editor buffer',
78 action = 'store_true'),
79 make_option('-a', '--author', metavar = '"NAME <EMAIL>"',
80 help = 'use "NAME <EMAIL>" as the author details'),
81 make_option('--authname',
82 help = 'use AUTHNAME as the author name'),
83 make_option('--authemail',
84 help = 'use AUTHEMAIL as the author e-mail'),
85 make_option('--authdate',
86 help = 'use AUTHDATE as the author date'),
87 make_option('--commname',
88 help = 'use COMMNAME as the committer name'),
89 make_option('--commemail',
90 help = 'use COMMEMAIL as the committer e-mail')
91 ] + make_sign_options()
92
93
94 def __strip_patch_name(name):
95 stripped = re.sub('^[0-9]+-(.*)$', '\g<1>', name)
96 stripped = re.sub('^(.*)\.(diff|patch)$', '\g<1>', stripped)
97
98 return stripped
99
100 def __replace_slashes_with_dashes(name):
101 stripped = name.replace('/', '-')
102
103 return stripped
104
105 def __create_patch(filename, message, author_name, author_email,
106 author_date, diff, options):
107 """Create a new patch on the stack
108 """
109 if options.name:
110 patch = options.name
111 elif filename:
112 patch = os.path.basename(filename)
113 else:
114 patch = ''
115 if options.strip:
116 patch = __strip_patch_name(patch)
117
118 if not patch:
119 if options.ignore or options.replace:
120 unacceptable_name = lambda name: False
121 else:
122 unacceptable_name = crt_series.patch_exists
123 patch = make_patch_name(message, unacceptable_name)
124 else:
125 # fix possible invalid characters in the patch name
126 patch = re.sub('[^\w.]+', '-', patch).strip('-')
127
128 if options.ignore and patch in crt_series.get_applied():
129 out.info('Ignoring already applied patch "%s"' % patch)
130 return
131 if options.replace and patch in crt_series.get_unapplied():
132 crt_series.delete_patch(patch, keep_log = True)
133
134 # refresh_patch() will invoke the editor in this case, with correct
135 # patch content
136 if not message:
137 can_edit = False
138
139 committer_name = committer_email = None
140
141 if options.author:
142 options.authname, options.authemail = name_email(options.author)
143
144 # override the automatically parsed settings
145 if options.authname:
146 author_name = options.authname
147 if options.authemail:
148 author_email = options.authemail
149 if options.authdate:
150 author_date = options.authdate
151 if options.commname:
152 committer_name = options.commname
153 if options.commemail:
154 committer_email = options.commemail
155
156 crt_series.new_patch(patch, message = message, can_edit = False,
157 author_name = author_name,
158 author_email = author_email,
159 author_date = author_date,
160 committer_name = committer_name,
161 committer_email = committer_email)
162
163 if not diff:
164 out.warn('No diff found, creating empty patch')
165 else:
166 out.start('Importing patch "%s"' % patch)
167 if options.base:
168 git.apply_patch(diff = diff,
169 base = git_id(crt_series, options.base))
170 else:
171 git.apply_patch(diff = diff)
172 crt_series.refresh_patch(edit = options.edit,
173 show_patch = options.showpatch,
174 sign_str = options.sign_str,
175 backup = False)
176 out.done()
177
178 def __mkpatchname(name, suffix):
179 if name.lower().endswith(suffix.lower()):
180 return name[:-len(suffix)]
181 return name
182
183 def __get_handle_and_name(filename):
184 """Return a file object and a patch name derived from filename
185 """
186 # see if it's a gzip'ed or bzip2'ed patch
187 import bz2, gzip
188 for copen, ext in [(gzip.open, '.gz'), (bz2.BZ2File, '.bz2')]:
189 try:
190 f = copen(filename)
191 f.read(1)
192 f.seek(0)
193 return (f, __mkpatchname(filename, ext))
194 except IOError, e:
195 pass
196
197 # plain old file...
198 return (open(filename), filename)
199
200 def __import_file(filename, options, patch = None):
201 """Import a patch from a file or standard input
202 """
203 pname = None
204 if filename:
205 (f, pname) = __get_handle_and_name(filename)
206 else:
207 f = sys.stdin
208
209 if patch:
210 pname = patch
211 elif not pname:
212 pname = filename
213
214 if options.mail:
215 try:
216 msg = email.message_from_file(f)
217 except Exception, ex:
218 raise CmdException, 'error parsing the e-mail file: %s' % str(ex)
219 message, author_name, author_email, author_date, diff = \
220 parse_mail(msg)
221 else:
222 message, author_name, author_email, author_date, diff = \
223 parse_patch(f.read())
224
225 if filename:
226 f.close()
227
228 __create_patch(pname, message, author_name, author_email,
229 author_date, diff, options)
230
231 def __import_series(filename, options):
232 """Import a series of patches
233 """
234 applied = crt_series.get_applied()
235
236 if filename:
237 f = file(filename)
238 patchdir = os.path.dirname(filename)
239 else:
240 f = sys.stdin
241 patchdir = ''
242
243 for line in f:
244 patch = re.sub('#.*$', '', line).strip()
245 if not patch:
246 continue
247 patchfile = os.path.join(patchdir, patch)
248 patch = __replace_slashes_with_dashes(patch);
249
250 __import_file(patchfile, options, patch)
251
252 if filename:
253 f.close()
254
255 def __import_mbox(filename, options):
256 """Import a series from an mbox file
257 """
258 if filename:
259 f = file(filename, 'rb')
260 else:
261 f = StringIO(sys.stdin.read())
262
263 try:
264 mbox = UnixMailbox(f, email.message_from_file)
265 except Exception, ex:
266 raise CmdException, 'error parsing the mbox file: %s' % str(ex)
267
268 for msg in mbox:
269 message, author_name, author_email, author_date, diff = \
270 parse_mail(msg)
271 __create_patch(None, message, author_name, author_email,
272 author_date, diff, options)
273
274 f.close()
275
276 def __import_url(url, options):
277 """Import a patch from a URL
278 """
279 import urllib
280 import tempfile
281
282 if not url:
283 parser.error('URL argument required')
284
285 patch = os.path.basename(urllib.unquote(url))
286 filename = os.path.join(tempfile.gettempdir(), patch)
287 urllib.urlretrieve(url, filename)
288 __import_file(filename, options)
289
290 def func(parser, options, args):
291 """Import a GNU diff file as a new patch
292 """
293 if len(args) > 1:
294 parser.error('incorrect number of arguments')
295
296 check_local_changes()
297 check_conflicts()
298 check_head_top_equal(crt_series)
299
300 if len(args) == 1:
301 filename = args[0]
302 else:
303 filename = None
304
305 if options.series:
306 __import_series(filename, options)
307 elif options.mbox:
308 __import_mbox(filename, options)
309 elif options.url:
310 __import_url(filename, options)
311 else:
312 __import_file(filename, options)
313
314 print_crt_patch(crt_series)