]> git.ozlabs.org Git - patchwork/blob - patchwork/bin/parsemail.py
f2b10bd38ee9f0536745d0e624db5c2a8f7c726f
[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 this is a new patch, we defer setting comment.patch until
224         # patch has been saved by the caller
225         if patch:
226             comment = Comment(date = mail_date(mail),
227                     content = clean_content(commentbuf),
228                     headers = mail_headers(mail))
229
230         else:
231             cpatch = find_patch_for_comment(project, mail)
232             if not cpatch:
233                 return (None, None)
234             comment = Comment(patch = cpatch, date = mail_date(mail),
235                     content = clean_content(commentbuf),
236                     headers = mail_headers(mail))
237
238     return (patch, comment)
239
240 def find_patch_for_comment(project, mail):
241     # construct a list of possible reply message ids
242     refs = []
243     if 'In-Reply-To' in mail:
244         refs.append(mail.get('In-Reply-To'))
245
246     if 'References' in mail:
247         rs = mail.get('References').split()
248         rs.reverse()
249         for r in rs:
250             if r not in refs:
251                 refs.append(r)
252
253     for ref in refs:
254         patch = None
255
256         # first, check for a direct reply
257         try:
258             patch = Patch.objects.get(project = project, msgid = ref)
259             return patch
260         except Patch.DoesNotExist:
261             pass
262
263         # see if we have comments that refer to a patch
264         try:
265             comment = Comment.objects.get(patch__project = project, msgid = ref)
266             return comment.patch
267         except Comment.DoesNotExist:
268             pass
269
270
271     return None
272
273 split_re = re.compile('[,\s]+')
274
275 def split_prefixes(prefix):
276     """ Turn a prefix string into a list of prefix tokens """
277
278     matches = split_re.split(prefix)
279     return [ s for s in matches if s != '' ]
280
281 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
282 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
283
284 def clean_subject(subject, drop_prefixes = None):
285     """ Clean a Subject: header from an incoming patch.
286
287     Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
288     default, only [PATCH] is removed, and we keep any other bracketed data
289     in the subject. If drop_prefixes is provided, remove those too,
290     comparing case-insensitively."""
291
292
293     subject = clean_header(subject)
294
295     if drop_prefixes is None:
296         drop_prefixes = []
297     else:
298         drop_prefixes = [ s.lower() for s in drop_prefixes ]
299
300     drop_prefixes.append('patch')
301
302     # remove Re:, Fwd:, etc
303     subject = re_re.sub(' ', subject)
304
305     subject = normalise_space(subject)
306
307     prefixes = []
308
309     match = prefix_re.match(subject)
310
311     while match:
312         prefix_str = match.group(1)
313         prefixes += [ p for p in split_prefixes(prefix_str) \
314                         if p.lower() not in drop_prefixes]
315
316         subject = match.group(2)
317         match = prefix_re.match(subject)
318
319     subject = normalise_space(subject)
320
321     subject = subject.strip()
322     if prefixes:
323         subject = '[%s] %s' % (','.join(prefixes), subject)
324
325     return subject
326
327 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
328 def clean_content(str):
329     """ Try to remove signature (-- ) and list footer (_____) cruft """
330     str = sig_re.sub('', str)
331     return str.strip()
332
333 def get_state(state_name):
334     """ Return the state with the given name or the default State """
335     if state_name:
336         try:
337             return State.objects.get(name__iexact=state_name)
338         except State.DoesNotExist:
339             pass
340     return get_default_initial_patch_state()
341
342 def get_delegate(delegate_email):
343     """ Return the delegate with the given email or None """
344     if delegate_email:
345         try:
346             return User.objects.get(email__iexact=delegate_email)
347         except User.DoesNotExist:
348             pass
349     return None
350
351 def parse_mail(mail):
352
353     # some basic sanity checks
354     if 'From' not in mail:
355         return 0
356
357     if 'Subject' not in mail:
358         return 0
359
360     if 'Message-Id' not in mail:
361         return 0
362
363     hint = mail.get('X-Patchwork-Hint', '').lower()
364     if hint == 'ignore':
365         return 0;
366
367     project = find_project(mail)
368     if project is None:
369         print "no project found"
370         return 0
371
372     msgid = mail.get('Message-Id').strip()
373
374     (author, save_required) = find_author(mail)
375
376     (patch, comment) = find_content(project, mail)
377
378     if patch:
379         # we delay the saving until we know we have a patch.
380         if save_required:
381             author.save()
382             save_required = False
383         patch.submitter = author
384         patch.msgid = msgid
385         patch.project = project
386         patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
387         patch.delegate = get_delegate(
388                 mail.get('X-Patchwork-Delegate', '').strip())
389         try:
390             patch.save()
391         except Exception, ex:
392             print str(ex)
393
394     if comment:
395         if save_required:
396             author.save()
397         # we defer this assignment until we know that we have a saved patch
398         if patch:
399             comment.patch = patch
400         comment.submitter = author
401         comment.msgid = msgid
402         try:
403             comment.save()
404         except Exception, ex:
405             print str(ex)
406
407     return 0
408
409 def main(args):
410     django.setup()
411     mail = message_from_file(sys.stdin)
412     return parse_mail(mail)
413
414 if __name__ == '__main__':
415     sys.exit(main(sys.argv))