]> git.ozlabs.org Git - patchwork/blob - patchwork/bin/parsemail.py
tests: Remove old-style test runner module
[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     matches = split_re.split(prefix)
273     return [ s for s in matches if s != '' ]
274
275 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
276 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
277
278 def clean_subject(subject, drop_prefixes = None):
279     """ Clean a Subject: header from an incoming patch.
280
281     Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
282     default, only [PATCH] is removed, and we keep any other bracketed data
283     in the subject. If drop_prefixes is provided, remove those too,
284     comparing case-insensitively."""
285
286
287     subject = clean_header(subject)
288
289     if drop_prefixes is None:
290         drop_prefixes = []
291     else:
292         drop_prefixes = [ s.lower() for s in drop_prefixes ]
293
294     drop_prefixes.append('patch')
295
296     # remove Re:, Fwd:, etc
297     subject = re_re.sub(' ', subject)
298
299     subject = normalise_space(subject)
300
301     prefixes = []
302
303     match = prefix_re.match(subject)
304
305     while match:
306         prefix_str = match.group(1)
307         prefixes += [ p for p in split_prefixes(prefix_str) \
308                         if p.lower() not in drop_prefixes]
309
310         subject = match.group(2)
311         match = prefix_re.match(subject)
312
313     subject = normalise_space(subject)
314
315     subject = subject.strip()
316     if prefixes:
317         subject = '[%s] %s' % (','.join(prefixes), subject)
318
319     return subject
320
321 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
322 def clean_content(str):
323     """ Try to remove signature (-- ) and list footer (_____) cruft """
324     str = sig_re.sub('', str)
325     return str.strip()
326
327 def get_state(state_name):
328     """ Return the state with the given name or the default State """
329     if state_name:
330         try:
331             return State.objects.get(name__iexact=state_name)
332         except State.DoesNotExist:
333             pass
334     return get_default_initial_patch_state()
335
336 def get_delegate(delegate_email):
337     """ Return the delegate with the given email or None """
338     if delegate_email:
339         try:
340             return User.objects.get(email__iexact=delegate_email)
341         except User.DoesNotExist:
342             pass
343     return None
344
345 def parse_mail(mail):
346
347     # some basic sanity checks
348     if 'From' not in mail:
349         return 0
350
351     if 'Subject' not in mail:
352         return 0
353
354     if 'Message-Id' not in mail:
355         return 0
356
357     hint = mail.get('X-Patchwork-Hint', '').lower()
358     if hint == 'ignore':
359         return 0;
360
361     project = find_project(mail)
362     if project is None:
363         print "no project found"
364         return 0
365
366     msgid = mail.get('Message-Id').strip()
367
368     (author, save_required) = find_author(mail)
369
370     (patch, comment) = find_content(project, mail)
371
372     if patch:
373         # we delay the saving until we know we have a patch.
374         if save_required:
375             author.save()
376             save_required = False
377         patch.submitter = author
378         patch.msgid = msgid
379         patch.project = project
380         patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
381         patch.delegate = get_delegate(
382                 mail.get('X-Patchwork-Delegate', '').strip())
383         try:
384             patch.save()
385         except Exception, ex:
386             print str(ex)
387
388     if comment:
389         if save_required:
390             author.save()
391         # looks like the original constructor for Comment takes the pk
392         # when the Comment is created. reset it here.
393         if patch:
394             comment.patch = patch
395         comment.submitter = author
396         comment.msgid = msgid
397         try:
398             comment.save()
399         except Exception, ex:
400             print str(ex)
401
402     return 0
403
404 def main(args):
405     mail = message_from_file(sys.stdin)
406     return parse_mail(mail)
407
408 if __name__ == '__main__':
409     sys.exit(main(sys.argv))