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