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