]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/parsemail.py
[parser] Fix spacing for encoded headers
[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         #print "\t%s, %s" % \
141         #    (part.get_content_subtype(), part.get_content_charset())
142
143         charset = part.get_content_charset()
144         if not charset:
145             charset = mail.get_charset()
146         if not charset:
147             charset = 'utf-8'
148
149         payload = unicode(part.get_payload(decode=True), charset, "replace")
150
151         if part.get_content_subtype() == 'x-patch':
152             patchbuf = payload
153
154         if part.get_content_subtype() == 'plain':
155             if not patchbuf:
156                 (patchbuf, c) = parse_patch(payload)
157             else:
158                 c = payload
159
160             if c is not None:
161                 commentbuf += c.strip() + '\n'
162
163     patch = None
164     comment = None
165
166     if patchbuf:
167         mail_headers(mail)
168         name = clean_subject(mail.get('Subject'), [project.linkname])
169         patch = Patch(name = name, content = patchbuf,
170                     date = mail_date(mail), headers = mail_headers(mail))
171
172     if commentbuf:
173         if patch:
174             cpatch = patch
175         else:
176             cpatch = find_patch_for_comment(mail)
177             if not cpatch:
178                 return (None, None)
179         comment = Comment(patch = cpatch, date = mail_date(mail),
180                 content = clean_content(commentbuf),
181                 headers = mail_headers(mail))
182
183     return (patch, comment)
184
185 def find_patch_for_comment(mail):
186     # construct a list of possible reply message ids
187     refs = []
188     if 'In-Reply-To' in mail:
189         refs.append(mail.get('In-Reply-To'))
190
191     if 'References' in mail:
192         rs = mail.get('References').split()
193         rs.reverse()
194         for r in rs:
195             if r not in refs:
196                 refs.append(r)
197
198     for ref in refs:
199         patch = None
200
201         # first, check for a direct reply
202         try:
203             patch = Patch.objects.get(msgid = ref)
204             return patch
205         except Patch.DoesNotExist:
206             pass
207
208         # see if we have comments that refer to a patch
209         try:
210             comment = Comment.objects.get(msgid = ref)
211             return comment.patch
212         except Comment.DoesNotExist:
213             pass
214
215
216     return None
217
218 split_re = re.compile('[,\s]+')
219
220 def split_prefixes(prefix):
221     """ Turn a prefix string into a list of prefix tokens
222
223     >>> split_prefixes('PATCH')
224     ['PATCH']
225     >>> split_prefixes('PATCH,RFC')
226     ['PATCH', 'RFC']
227     >>> split_prefixes('')
228     []
229     >>> split_prefixes('PATCH,')
230     ['PATCH']
231     >>> split_prefixes('PATCH ')
232     ['PATCH']
233     >>> split_prefixes('PATCH,RFC')
234     ['PATCH', 'RFC']
235     >>> split_prefixes('PATCH 1/2')
236     ['PATCH', '1/2']
237     """
238     matches = split_re.split(prefix)
239     return [ s for s in matches if s != '' ]
240
241 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
242 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
243
244 def clean_subject(subject, drop_prefixes = None):
245     """ Clean a Subject: header from an incoming patch.
246
247     Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
248     default, only [PATCH] is removed, and we keep any other bracketed data
249     in the subject. If drop_prefixes is provided, remove those too,
250     comparing case-insensitively.
251
252     >>> clean_subject('meep')
253     'meep'
254     >>> clean_subject('Re: meep')
255     'meep'
256     >>> clean_subject('[PATCH] meep')
257     'meep'
258     >>> clean_subject('[PATCH] meep \\n meep')
259     'meep meep'
260     >>> clean_subject('[PATCH RFC] meep')
261     '[RFC] meep'
262     >>> clean_subject('[PATCH,RFC] meep')
263     '[RFC] meep'
264     >>> clean_subject('[PATCH,1/2] meep')
265     '[1/2] meep'
266     >>> clean_subject('[PATCH RFC 1/2] meep')
267     '[RFC,1/2] meep'
268     >>> clean_subject('[PATCH] [RFC] meep')
269     '[RFC] meep'
270     >>> clean_subject('[PATCH] [RFC,1/2] meep')
271     '[RFC,1/2] meep'
272     >>> clean_subject('[PATCH] [RFC] [1/2] meep')
273     '[RFC,1/2] meep'
274     >>> clean_subject('[PATCH] rewrite [a-z] regexes')
275     'rewrite [a-z] regexes'
276     >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
277     '[RFC] rewrite [a-z] regexes'
278     >>> clean_subject('[foo] [bar] meep', ['foo'])
279     '[bar] meep'
280     >>> clean_subject('[FOO] [bar] meep', ['foo'])
281     '[bar] meep'
282     """
283
284     if drop_prefixes is None:
285         drop_prefixes = []
286     else:
287         drop_prefixes = [ s.lower() for s in drop_prefixes ]
288
289     drop_prefixes.append('patch')
290
291     # remove Re:, Fwd:, etc
292     subject = re_re.sub(' ', subject)
293
294     subject = normalise_space(subject)
295
296     prefixes = []
297
298     match = prefix_re.match(subject)
299
300     while match:
301         prefix_str = match.group(1)
302         prefixes += [ p for p in split_prefixes(prefix_str) \
303                         if p.lower() not in drop_prefixes]
304
305         subject = match.group(2)
306         match = prefix_re.match(subject)
307
308     subject = normalise_space(subject)
309
310     subject = subject.strip()
311     if prefixes:
312         subject = '[%s] %s' % (','.join(prefixes), subject)
313
314     return subject
315
316 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
317 def clean_content(str):
318     """ Try to remove signature (-- ) and list footer (_____) cruft """
319     str = sig_re.sub('', str)
320     return str.strip()
321
322 def main(args):
323     mail = message_from_file(sys.stdin)
324
325     # some basic sanity checks
326     if 'From' not in mail:
327         return 0
328
329     if 'Subject' not in mail:
330         return 0
331
332     if 'Message-Id' not in mail:
333         return 0
334
335     hint = mail.get('X-Patchwork-Hint', '').lower()
336     if hint == 'ignore':
337         return 0;
338
339     project = find_project(mail)
340     if project is None:
341         print "no project found"
342         return 0
343
344     msgid = mail.get('Message-Id').strip()
345
346     (author, save_required) = find_author(mail)
347
348     (patch, comment) = find_content(project, mail)
349
350     if patch:
351         # we delay the saving until we know we have a patch.
352         if save_required:
353             author.save()
354             save_required = False
355         patch.submitter = author
356         patch.msgid = msgid
357         patch.project = project
358         try:
359             patch.save()
360         except Exception, ex:
361             print str(ex)
362
363     if comment:
364         if save_required:
365             author.save()
366         # looks like the original constructor for Comment takes the pk
367         # when the Comment is created. reset it here.
368         if patch:
369             comment.patch = patch
370         comment.submitter = author
371         comment.msgid = msgid
372         try:
373             comment.save()
374         except Exception, ex:
375             print str(ex)
376
377     return 0
378
379 if __name__ == '__main__':
380     sys.exit(main(sys.argv))