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