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