3 # Patchwork - automated patch tracking system
4 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
6 # This file is part of the Patchwork package.
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.
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.
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
27 from email import message_from_file
29 from email.header import Header, decode_header
30 from email.utils import parsedate_tz, mktime_tz
32 # Python 2.4 compatibility
33 from email.Header import Header, decode_header
34 from email.Utils import parsedate_tz, mktime_tz
36 from patchwork.parser import parse_patch
37 from patchwork.models import Patch, Project, Person, Comment
39 list_id_headers = ['List-ID', 'X-Mailing-List']
41 whitespace_re = re.compile('\s+')
42 def normalise_space(str):
43 return whitespace_re.sub(' ', str).strip()
45 def clean_header(header):
46 """ Decode (possibly non-ascii) headers """
49 (frag_str, frag_encoding) = fragment
51 return frag_str.decode(frag_encoding)
52 return frag_str.decode()
54 fragments = map(decode, decode_header(header))
56 return normalise_space(u' '.join(fragments))
58 def find_project(mail):
60 listid_res = [re.compile('.*<([^>]+)>.*', re.S),
61 re.compile('^([\S]+)$', re.S)]
63 for header in list_id_headers:
66 for listid_re in listid_res:
67 match = listid_re.match(mail.get(header))
74 listid = match.group(1)
77 project = Project.objects.get(listid = listid)
84 def find_author(mail):
86 from_header = clean_header(mail.get('From'))
87 (name, email) = (None, None)
89 # tuple of (regex, fn)
90 # - where fn returns a (name, email) tuple from the match groups resulting
91 # from re.match().groups()
93 # for "Firstname Lastname" <example@example.com> style addresses
94 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
96 # for example@example.com (Firstname Lastname) style addresses
97 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
100 (re.compile('(.*)'), (lambda g: (None, g[0]))),
103 for regex, fn in from_res:
104 match = regex.match(from_header)
106 (name, email) = fn(match.groups())
110 raise Exception("Could not parse From: header")
112 email = email.strip()
119 person = Person.objects.get(email__iexact = email)
120 except Person.DoesNotExist:
121 person = Person(name = name, email = email)
124 return (person, new_person)
127 t = parsedate_tz(mail.get('Date', ''))
129 return datetime.datetime.utcnow()
130 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
132 def mail_headers(mail):
133 return reduce(operator.__concat__,
134 ['%s: %s\n' % (k, Header(v, header_name = k, \
135 continuation_ws = '\t').encode()) \
136 for (k, v) in mail.items()])
138 def find_content(project, mail):
142 for part in mail.walk():
143 if part.get_content_maintype() != 'text':
146 payload = part.get_payload(decode=True)
147 charset = part.get_content_charset()
148 subtype = part.get_content_subtype()
150 # if we don't have a charset, assume utf-8
154 if not isinstance(payload, unicode):
155 payload = unicode(payload, charset)
157 if subtype in ['x-patch', 'x-diff']:
160 elif subtype == 'plain':
162 (patchbuf, c) = parse_patch(payload)
167 commentbuf += c.strip() + '\n'
174 name = clean_subject(mail.get('Subject'), [project.linkname])
175 patch = Patch(name = name, content = patchbuf,
176 date = mail_date(mail), headers = mail_headers(mail))
182 cpatch = find_patch_for_comment(project, mail)
185 comment = Comment(patch = cpatch, date = mail_date(mail),
186 content = clean_content(commentbuf),
187 headers = mail_headers(mail))
189 return (patch, comment)
191 def find_patch_for_comment(project, mail):
192 # construct a list of possible reply message ids
194 if 'In-Reply-To' in mail:
195 refs.append(mail.get('In-Reply-To'))
197 if 'References' in mail:
198 rs = mail.get('References').split()
207 # first, check for a direct reply
209 patch = Patch.objects.get(project = project, msgid = ref)
211 except Patch.DoesNotExist:
214 # see if we have comments that refer to a patch
216 comment = Comment.objects.get(patch__project = project, msgid = ref)
218 except Comment.DoesNotExist:
224 split_re = re.compile('[,\s]+')
226 def split_prefixes(prefix):
227 """ Turn a prefix string into a list of prefix tokens
229 >>> split_prefixes('PATCH')
231 >>> split_prefixes('PATCH,RFC')
233 >>> split_prefixes('')
235 >>> split_prefixes('PATCH,')
237 >>> split_prefixes('PATCH ')
239 >>> split_prefixes('PATCH,RFC')
241 >>> split_prefixes('PATCH 1/2')
244 matches = split_re.split(prefix)
245 return [ s for s in matches if s != '' ]
247 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
248 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
250 def clean_subject(subject, drop_prefixes = None):
251 """ Clean a Subject: header from an incoming patch.
253 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
254 default, only [PATCH] is removed, and we keep any other bracketed data
255 in the subject. If drop_prefixes is provided, remove those too,
256 comparing case-insensitively.
258 >>> clean_subject('meep')
260 >>> clean_subject('Re: meep')
262 >>> clean_subject('[PATCH] meep')
264 >>> clean_subject('[PATCH] meep \\n meep')
266 >>> clean_subject('[PATCH RFC] meep')
268 >>> clean_subject('[PATCH,RFC] meep')
270 >>> clean_subject('[PATCH,1/2] meep')
272 >>> clean_subject('[PATCH RFC 1/2] meep')
274 >>> clean_subject('[PATCH] [RFC] meep')
276 >>> clean_subject('[PATCH] [RFC,1/2] meep')
278 >>> clean_subject('[PATCH] [RFC] [1/2] meep')
280 >>> clean_subject('[PATCH] rewrite [a-z] regexes')
281 'rewrite [a-z] regexes'
282 >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
283 '[RFC] rewrite [a-z] regexes'
284 >>> clean_subject('[foo] [bar] meep', ['foo'])
286 >>> clean_subject('[FOO] [bar] meep', ['foo'])
290 if drop_prefixes is None:
293 drop_prefixes = [ s.lower() for s in drop_prefixes ]
295 drop_prefixes.append('patch')
297 # remove Re:, Fwd:, etc
298 subject = re_re.sub(' ', subject)
300 subject = normalise_space(subject)
304 match = prefix_re.match(subject)
307 prefix_str = match.group(1)
308 prefixes += [ p for p in split_prefixes(prefix_str) \
309 if p.lower() not in drop_prefixes]
311 subject = match.group(2)
312 match = prefix_re.match(subject)
314 subject = normalise_space(subject)
316 subject = subject.strip()
318 subject = '[%s] %s' % (','.join(prefixes), subject)
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)
328 def parse_mail(mail):
330 # some basic sanity checks
331 if 'From' not in mail:
334 if 'Subject' not in mail:
337 if 'Message-Id' not in mail:
340 hint = mail.get('X-Patchwork-Hint', '').lower()
344 project = find_project(mail)
346 print "no project found"
349 msgid = mail.get('Message-Id').strip()
351 (author, save_required) = find_author(mail)
353 (patch, comment) = find_content(project, mail)
356 # we delay the saving until we know we have a patch.
359 save_required = False
360 patch.submitter = author
362 patch.project = project
365 except Exception, ex:
371 # looks like the original constructor for Comment takes the pk
372 # when the Comment is created. reset it here.
374 comment.patch = patch
375 comment.submitter = author
376 comment.msgid = msgid
379 except Exception, ex:
385 mail = message_from_file(sys.stdin)
386 return parse_mail(mail)
388 if __name__ == '__main__':
389 sys.exit(main(sys.argv))