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