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