]> git.ozlabs.org Git - patchwork/blob - patchwork/bin/parsemail.py
parsemail: Don't catch all exceptions when a Project isn't found
[patchwork] / patchwork / bin / parsemail.py
1 #!/usr/bin/env python
2 #
3 # Patchwork - automated patch tracking system
4 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
5 #
6 # This file is part of the Patchwork package.
7 #
8 # Patchwork is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # Patchwork is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Patchwork; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22 import sys
23 import re
24 import datetime
25 import time
26 import operator
27 import codecs
28 from email import message_from_file
29 try:
30     from email.header import Header, decode_header
31     from email.utils import parsedate_tz, mktime_tz
32 except ImportError:
33     # Python 2.4 compatibility
34     from email.Header import Header, decode_header
35     from email.Utils import parsedate_tz, mktime_tz
36
37 from patchwork.parser import parse_patch
38 from patchwork.models import Patch, Project, Person, Comment, State, \
39         get_default_initial_patch_state
40 import django
41 from django.contrib.auth.models import User
42
43 list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']
44
45 whitespace_re = re.compile('\s+')
46 def normalise_space(str):
47     return whitespace_re.sub(' ', str).strip()
48
49 def clean_header(header):
50     """ Decode (possibly non-ascii) headers """
51
52     def decode(fragment):
53         (frag_str, frag_encoding) = fragment
54         if frag_encoding:
55             return frag_str.decode(frag_encoding)
56         return frag_str.decode()
57
58     fragments = map(decode, decode_header(header))
59
60     return normalise_space(u' '.join(fragments))
61
62 def find_project(mail):
63     project = None
64     listid_res = [re.compile('.*<([^>]+)>.*', re.S),
65                   re.compile('^([\S]+)$', re.S)]
66
67     for header in list_id_headers:
68         if header in mail:
69
70             for listid_re in listid_res:
71                 match = listid_re.match(mail.get(header))
72                 if match:
73                     break
74
75             if not match:
76                 continue
77
78             listid = match.group(1)
79
80             try:
81                 project = Project.objects.get(listid = listid)
82                 break
83             except Project.DoesNotExist:
84                 pass
85
86     return project
87
88 def find_author(mail):
89
90     from_header = clean_header(mail.get('From'))
91     (name, email) = (None, None)
92
93     # tuple of (regex, fn)
94     #  - where fn returns a (name, email) tuple from the match groups resulting
95     #    from re.match().groups()
96     from_res = [
97         # for "Firstname Lastname" <example@example.com> style addresses
98        (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
99
100        # for example@example.com (Firstname Lastname) style addresses
101        (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
102
103        # everything else
104        (re.compile('(.*)'), (lambda g: (None, g[0]))),
105     ]
106
107     for regex, fn in from_res:
108         match = regex.match(from_header)
109         if match:
110             (name, email) = fn(match.groups())
111             break
112
113     if email is None:
114         raise Exception("Could not parse From: header")
115
116     email = email.strip()
117     if name is not None:
118         name = name.strip()
119
120     new_person = False
121
122     try:
123         person = Person.objects.get(email__iexact = email)
124     except Person.DoesNotExist:
125         person = Person(name = name, email = email)
126         new_person = True
127
128     return (person, new_person)
129
130 def mail_date(mail):
131     t = parsedate_tz(mail.get('Date', ''))
132     if not t:
133         return datetime.datetime.utcnow()
134     return datetime.datetime.utcfromtimestamp(mktime_tz(t))
135
136 def mail_headers(mail):
137     return reduce(operator.__concat__,
138             ['%s: %s\n' % (k, Header(v, header_name = k, \
139                     continuation_ws = '\t').encode()) \
140                 for (k, v) in mail.items()])
141
142 def find_pull_request(content):
143     git_re = re.compile('^The following changes since commit.*' +
144                         '^are available in the git repository at:\n'
145                         '^\s*([\S]+://[^\n]+)$',
146                            re.DOTALL | re.MULTILINE)
147     match = git_re.search(content)
148     if match:
149         return match.group(1)
150     return None
151
152 def try_decode(payload, charset):
153     try:
154         payload = unicode(payload, charset)
155     except UnicodeDecodeError:
156         return None
157     return payload
158
159 def find_content(project, mail):
160     patchbuf = None
161     commentbuf = ''
162     pullurl = None
163
164     for part in mail.walk():
165         if part.get_content_maintype() != 'text':
166             continue
167
168         payload = part.get_payload(decode=True)
169         subtype = part.get_content_subtype()
170
171         if not isinstance(payload, unicode):
172             charset = part.get_content_charset()
173
174             # Check that we have a charset that we understand. Otherwise,
175             # ignore it and fallback to our standard set.
176             if charset is not None:
177                 try:
178                     codec = codecs.lookup(charset)
179                 except LookupError:
180                     charset = None
181
182             # If there is no charset or if it is unknown, then try some common
183             # charsets before we fail.
184             if charset is None:
185                 try_charsets = ['utf-8', 'windows-1252', 'iso-8859-1']
186             else:
187                 try_charsets = [charset]
188
189             for cset in try_charsets:
190                 decoded_payload = try_decode(payload, cset)
191                 if decoded_payload is not None:
192                     break
193             payload = decoded_payload
194
195             # Could not find a valid decoded payload.  Fail.
196             if payload is None:
197                 return (None, None)
198
199         if subtype in ['x-patch', 'x-diff']:
200             patchbuf = payload
201
202         elif subtype == 'plain':
203             c = payload
204
205             if not patchbuf:
206                 (patchbuf, c) = parse_patch(payload)
207
208             if not pullurl:
209                 pullurl = find_pull_request(payload)
210
211             if c is not None:
212                 commentbuf += c.strip() + '\n'
213
214     patch = None
215     comment = None
216
217     if pullurl or patchbuf:
218         name = clean_subject(mail.get('Subject'), [project.linkname])
219         patch = Patch(name = name, pull_url = pullurl, content = patchbuf,
220                     date = mail_date(mail), headers = mail_headers(mail))
221
222     if commentbuf:
223         if patch:
224             cpatch = patch
225         else:
226             cpatch = find_patch_for_comment(project, mail)
227             if not cpatch:
228                 return (None, None)
229         comment = Comment(patch = cpatch, date = mail_date(mail),
230                 content = clean_content(commentbuf),
231                 headers = mail_headers(mail))
232
233     return (patch, comment)
234
235 def find_patch_for_comment(project, mail):
236     # construct a list of possible reply message ids
237     refs = []
238     if 'In-Reply-To' in mail:
239         refs.append(mail.get('In-Reply-To'))
240
241     if 'References' in mail:
242         rs = mail.get('References').split()
243         rs.reverse()
244         for r in rs:
245             if r not in refs:
246                 refs.append(r)
247
248     for ref in refs:
249         patch = None
250
251         # first, check for a direct reply
252         try:
253             patch = Patch.objects.get(project = project, msgid = ref)
254             return patch
255         except Patch.DoesNotExist:
256             pass
257
258         # see if we have comments that refer to a patch
259         try:
260             comment = Comment.objects.get(patch__project = project, msgid = ref)
261             return comment.patch
262         except Comment.DoesNotExist:
263             pass
264
265
266     return None
267
268 split_re = re.compile('[,\s]+')
269
270 def split_prefixes(prefix):
271     """ Turn a prefix string into a list of prefix tokens """
272
273     matches = split_re.split(prefix)
274     return [ s for s in matches if s != '' ]
275
276 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
277 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
278
279 def clean_subject(subject, drop_prefixes = None):
280     """ Clean a Subject: header from an incoming patch.
281
282     Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
283     default, only [PATCH] is removed, and we keep any other bracketed data
284     in the subject. If drop_prefixes is provided, remove those too,
285     comparing case-insensitively."""
286
287
288     subject = clean_header(subject)
289
290     if drop_prefixes is None:
291         drop_prefixes = []
292     else:
293         drop_prefixes = [ s.lower() for s in drop_prefixes ]
294
295     drop_prefixes.append('patch')
296
297     # remove Re:, Fwd:, etc
298     subject = re_re.sub(' ', subject)
299
300     subject = normalise_space(subject)
301
302     prefixes = []
303
304     match = prefix_re.match(subject)
305
306     while match:
307         prefix_str = match.group(1)
308         prefixes += [ p for p in split_prefixes(prefix_str) \
309                         if p.lower() not in drop_prefixes]
310
311         subject = match.group(2)
312         match = prefix_re.match(subject)
313
314     subject = normalise_space(subject)
315
316     subject = subject.strip()
317     if prefixes:
318         subject = '[%s] %s' % (','.join(prefixes), subject)
319
320     return subject
321
322 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
323 def clean_content(str):
324     """ Try to remove signature (-- ) and list footer (_____) cruft """
325     str = sig_re.sub('', str)
326     return str.strip()
327
328 def get_state(state_name):
329     """ Return the state with the given name or the default State """
330     if state_name:
331         try:
332             return State.objects.get(name__iexact=state_name)
333         except State.DoesNotExist:
334             pass
335     return get_default_initial_patch_state()
336
337 def get_delegate(delegate_email):
338     """ Return the delegate with the given email or None """
339     if delegate_email:
340         try:
341             return User.objects.get(email__iexact=delegate_email)
342         except User.DoesNotExist:
343             pass
344     return None
345
346 def parse_mail(mail):
347
348     # some basic sanity checks
349     if 'From' not in mail:
350         return 0
351
352     if 'Subject' not in mail:
353         return 0
354
355     if 'Message-Id' not in mail:
356         return 0
357
358     hint = mail.get('X-Patchwork-Hint', '').lower()
359     if hint == 'ignore':
360         return 0;
361
362     project = find_project(mail)
363     if project is None:
364         print "no project found"
365         return 0
366
367     msgid = mail.get('Message-Id').strip()
368
369     (author, save_required) = find_author(mail)
370
371     (patch, comment) = find_content(project, mail)
372
373     if patch:
374         # we delay the saving until we know we have a patch.
375         if save_required:
376             author.save()
377             save_required = False
378         patch.submitter = author
379         patch.msgid = msgid
380         patch.project = project
381         patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
382         patch.delegate = get_delegate(
383                 mail.get('X-Patchwork-Delegate', '').strip())
384         try:
385             patch.save()
386         except Exception, ex:
387             print str(ex)
388
389     if comment:
390         if save_required:
391             author.save()
392         # looks like the original constructor for Comment takes the pk
393         # when the Comment is created. reset it here.
394         if patch:
395             comment.patch = patch
396         comment.submitter = author
397         comment.msgid = msgid
398         try:
399             comment.save()
400         except Exception, ex:
401             print str(ex)
402
403     return 0
404
405 def main(args):
406     django.setup()
407     mail = message_from_file(sys.stdin)
408     return parse_mail(mail)
409
410 if __name__ == '__main__':
411     sys.exit(main(sys.argv))