]> git.ozlabs.org Git - patchwork/blob - patchwork/bin/parsemail.py
trivial: Remove Python < 2.5 code
[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 from email.header import Header, decode_header
30 from email.utils import parsedate_tz, mktime_tz
31
32 from patchwork.parser import parse_patch
33 from patchwork.models import Patch, Project, Person, Comment, State, \
34         get_default_initial_patch_state
35 import django
36 from django.contrib.auth.models import User
37
38 list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']
39
40 whitespace_re = re.compile('\s+')
41 def normalise_space(str):
42     return whitespace_re.sub(' ', str).strip()
43
44 def clean_header(header):
45     """ Decode (possibly non-ascii) headers """
46
47     def decode(fragment):
48         (frag_str, frag_encoding) = fragment
49         if frag_encoding:
50             return frag_str.decode(frag_encoding)
51         return frag_str.decode()
52
53     fragments = map(decode, decode_header(header))
54
55     return normalise_space(u' '.join(fragments))
56
57 def find_project(mail):
58     project = None
59     listid_res = [re.compile('.*<([^>]+)>.*', re.S),
60                   re.compile('^([\S]+)$', re.S)]
61
62     for header in list_id_headers:
63         if header in mail:
64
65             for listid_re in listid_res:
66                 match = listid_re.match(mail.get(header))
67                 if match:
68                     break
69
70             if not match:
71                 continue
72
73             listid = match.group(1)
74
75             try:
76                 project = Project.objects.get(listid = listid)
77                 break
78             except Project.DoesNotExist:
79                 pass
80
81     return project
82
83 def find_author(mail):
84
85     from_header = clean_header(mail.get('From'))
86     (name, email) = (None, None)
87
88     # tuple of (regex, fn)
89     #  - where fn returns a (name, email) tuple from the match groups resulting
90     #    from re.match().groups()
91     from_res = [
92         # for "Firstname Lastname" <example@example.com> style addresses
93        (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
94
95        # for example@example.com (Firstname Lastname) style addresses
96        (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
97
98        # everything else
99        (re.compile('(.*)'), (lambda g: (None, g[0]))),
100     ]
101
102     for regex, fn in from_res:
103         match = regex.match(from_header)
104         if match:
105             (name, email) = fn(match.groups())
106             break
107
108     if email is None:
109         raise Exception("Could not parse From: header")
110
111     email = email.strip()
112     if name is not None:
113         name = name.strip()
114
115     new_person = False
116
117     try:
118         person = Person.objects.get(email__iexact = email)
119     except Person.DoesNotExist:
120         person = Person(name = name, email = email)
121         new_person = True
122
123     return (person, new_person)
124
125 def mail_date(mail):
126     t = parsedate_tz(mail.get('Date', ''))
127     if not t:
128         return datetime.datetime.utcnow()
129     return datetime.datetime.utcfromtimestamp(mktime_tz(t))
130
131 def mail_headers(mail):
132     return reduce(operator.__concat__,
133             ['%s: %s\n' % (k, Header(v, header_name = k, \
134                     continuation_ws = '\t').encode()) \
135                 for (k, v) in mail.items()])
136
137 def find_pull_request(content):
138     git_re = re.compile('^The following changes since commit.*' +
139                         '^are available in the git repository at:\n'
140                         '^\s*([\S]+://[^\n]+)$',
141                            re.DOTALL | re.MULTILINE)
142     match = git_re.search(content)
143     if match:
144         return match.group(1)
145     return None
146
147 def try_decode(payload, charset):
148     try:
149         payload = unicode(payload, charset)
150     except UnicodeDecodeError:
151         return None
152     return payload
153
154 def find_content(project, mail):
155     patchbuf = None
156     commentbuf = ''
157     pullurl = None
158
159     for part in mail.walk():
160         if part.get_content_maintype() != 'text':
161             continue
162
163         payload = part.get_payload(decode=True)
164         subtype = part.get_content_subtype()
165
166         if not isinstance(payload, unicode):
167             charset = part.get_content_charset()
168
169             # Check that we have a charset that we understand. Otherwise,
170             # ignore it and fallback to our standard set.
171             if charset is not None:
172                 try:
173                     codec = codecs.lookup(charset)
174                 except LookupError:
175                     charset = None
176
177             # If there is no charset or if it is unknown, then try some common
178             # charsets before we fail.
179             if charset is None:
180                 try_charsets = ['utf-8', 'windows-1252', 'iso-8859-1']
181             else:
182                 try_charsets = [charset]
183
184             for cset in try_charsets:
185                 decoded_payload = try_decode(payload, cset)
186                 if decoded_payload is not None:
187                     break
188             payload = decoded_payload
189
190             # Could not find a valid decoded payload.  Fail.
191             if payload is None:
192                 return (None, None)
193
194         if subtype in ['x-patch', 'x-diff']:
195             patchbuf = payload
196
197         elif subtype == 'plain':
198             c = payload
199
200             if not patchbuf:
201                 (patchbuf, c) = parse_patch(payload)
202
203             if not pullurl:
204                 pullurl = find_pull_request(payload)
205
206             if c is not None:
207                 commentbuf += c.strip() + '\n'
208
209     patch = None
210     comment = None
211
212     if pullurl or patchbuf:
213         name = clean_subject(mail.get('Subject'), [project.linkname])
214         patch = Patch(name = name, pull_url = pullurl, content = patchbuf,
215                     date = mail_date(mail), headers = mail_headers(mail))
216
217     if commentbuf:
218         # If this is a new patch, we defer setting comment.patch until
219         # patch has been saved by the caller
220         if patch:
221             comment = Comment(date = mail_date(mail),
222                     content = clean_content(commentbuf),
223                     headers = mail_headers(mail))
224
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         # we defer this assignment until we know that we have a saved patch
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     django.setup()
406     mail = message_from_file(sys.stdin)
407     return parse_mail(mail)
408
409 if __name__ == '__main__':
410     sys.exit(main(sys.argv))