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
28 from email import message_from_file
30 from email.header import Header, decode_header
31 from email.utils import parsedate_tz, mktime_tz
33 # Python 2.4 compatibility
34 from email.Header import Header, decode_header
35 from email.Utils import parsedate_tz, mktime_tz
37 from patchwork.parser import parse_patch
38 from patchwork.models import Patch, Project, Person, Comment, State, \
39 get_default_initial_patch_state
40 from django.contrib.auth.models import User
42 list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']
44 whitespace_re = re.compile('\s+')
45 def normalise_space(str):
46 return whitespace_re.sub(' ', str).strip()
48 def clean_header(header):
49 """ Decode (possibly non-ascii) headers """
52 (frag_str, frag_encoding) = fragment
54 return frag_str.decode(frag_encoding)
55 return frag_str.decode()
57 fragments = map(decode, decode_header(header))
59 return normalise_space(u' '.join(fragments))
61 def find_project(mail):
63 listid_res = [re.compile('.*<([^>]+)>.*', re.S),
64 re.compile('^([\S]+)$', re.S)]
66 for header in list_id_headers:
69 for listid_re in listid_res:
70 match = listid_re.match(mail.get(header))
77 listid = match.group(1)
80 project = Project.objects.get(listid = listid)
87 def find_author(mail):
89 from_header = clean_header(mail.get('From'))
90 (name, email) = (None, None)
92 # tuple of (regex, fn)
93 # - where fn returns a (name, email) tuple from the match groups resulting
94 # from re.match().groups()
96 # for "Firstname Lastname" <example@example.com> style addresses
97 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
99 # for example@example.com (Firstname Lastname) style addresses
100 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
103 (re.compile('(.*)'), (lambda g: (None, g[0]))),
106 for regex, fn in from_res:
107 match = regex.match(from_header)
109 (name, email) = fn(match.groups())
113 raise Exception("Could not parse From: header")
115 email = email.strip()
122 person = Person.objects.get(email__iexact = email)
123 except Person.DoesNotExist:
124 person = Person(name = name, email = email)
127 return (person, new_person)
130 t = parsedate_tz(mail.get('Date', ''))
132 return datetime.datetime.utcnow()
133 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
135 def mail_headers(mail):
136 return reduce(operator.__concat__,
137 ['%s: %s\n' % (k, Header(v, header_name = k, \
138 continuation_ws = '\t').encode()) \
139 for (k, v) in mail.items()])
141 def find_pull_request(content):
142 git_re = re.compile('^The following changes since commit.*' +
143 '^are available in the git repository at:\n'
144 '^\s*([\S]+://[^\n]+)$',
145 re.DOTALL | re.MULTILINE)
146 match = git_re.search(content)
148 return match.group(1)
151 def try_decode(payload, charset):
153 payload = unicode(payload, charset)
154 except UnicodeDecodeError:
158 def find_content(project, mail):
163 for part in mail.walk():
164 if part.get_content_maintype() != 'text':
167 payload = part.get_payload(decode=True)
168 subtype = part.get_content_subtype()
170 if not isinstance(payload, unicode):
171 charset = part.get_content_charset()
173 # Check that we have a charset that we understand. Otherwise,
174 # ignore it and fallback to our standard set.
175 if charset is not None:
177 codec = codecs.lookup(charset)
181 # If there is no charset or if it is unknown, then try some common
182 # charsets before we fail.
184 try_charsets = ['utf-8', 'windows-1252', 'iso-8859-1']
186 try_charsets = [charset]
188 for cset in try_charsets:
189 decoded_payload = try_decode(payload, cset)
190 if decoded_payload is not None:
192 payload = decoded_payload
194 # Could not find a valid decoded payload. Fail.
198 if subtype in ['x-patch', 'x-diff']:
201 elif subtype == 'plain':
205 (patchbuf, c) = parse_patch(payload)
208 pullurl = find_pull_request(payload)
211 commentbuf += c.strip() + '\n'
216 if pullurl or patchbuf:
217 name = clean_subject(mail.get('Subject'), [project.linkname])
218 patch = Patch(name = name, pull_url = pullurl, content = patchbuf,
219 date = mail_date(mail), headers = mail_headers(mail))
225 cpatch = find_patch_for_comment(project, mail)
228 comment = Comment(patch = cpatch, date = mail_date(mail),
229 content = clean_content(commentbuf),
230 headers = mail_headers(mail))
232 return (patch, comment)
234 def find_patch_for_comment(project, mail):
235 # construct a list of possible reply message ids
237 if 'In-Reply-To' in mail:
238 refs.append(mail.get('In-Reply-To'))
240 if 'References' in mail:
241 rs = mail.get('References').split()
250 # first, check for a direct reply
252 patch = Patch.objects.get(project = project, msgid = ref)
254 except Patch.DoesNotExist:
257 # see if we have comments that refer to a patch
259 comment = Comment.objects.get(patch__project = project, msgid = ref)
261 except Comment.DoesNotExist:
267 split_re = re.compile('[,\s]+')
269 def split_prefixes(prefix):
270 """ Turn a prefix string into a list of prefix tokens
272 >>> split_prefixes('PATCH')
274 >>> split_prefixes('PATCH,RFC')
276 >>> split_prefixes('')
278 >>> split_prefixes('PATCH,')
280 >>> split_prefixes('PATCH ')
282 >>> split_prefixes('PATCH,RFC')
284 >>> split_prefixes('PATCH 1/2')
287 matches = split_re.split(prefix)
288 return [ s for s in matches if s != '' ]
290 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
291 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
293 def clean_subject(subject, drop_prefixes = None):
294 """ Clean a Subject: header from an incoming patch.
296 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
297 default, only [PATCH] is removed, and we keep any other bracketed data
298 in the subject. If drop_prefixes is provided, remove those too,
299 comparing case-insensitively.
301 >>> clean_subject('meep')
303 >>> clean_subject('Re: meep')
305 >>> clean_subject('[PATCH] meep')
307 >>> clean_subject('[PATCH] meep \\n meep')
309 >>> clean_subject('[PATCH RFC] meep')
311 >>> clean_subject('[PATCH,RFC] meep')
313 >>> clean_subject('[PATCH,1/2] meep')
315 >>> clean_subject('[PATCH RFC 1/2] meep')
317 >>> clean_subject('[PATCH] [RFC] meep')
319 >>> clean_subject('[PATCH] [RFC,1/2] meep')
321 >>> clean_subject('[PATCH] [RFC] [1/2] meep')
323 >>> clean_subject('[PATCH] rewrite [a-z] regexes')
324 'rewrite [a-z] regexes'
325 >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
326 '[RFC] rewrite [a-z] regexes'
327 >>> clean_subject('[foo] [bar] meep', ['foo'])
329 >>> clean_subject('[FOO] [bar] meep', ['foo'])
333 subject = clean_header(subject)
335 if drop_prefixes is None:
338 drop_prefixes = [ s.lower() for s in drop_prefixes ]
340 drop_prefixes.append('patch')
342 # remove Re:, Fwd:, etc
343 subject = re_re.sub(' ', subject)
345 subject = normalise_space(subject)
349 match = prefix_re.match(subject)
352 prefix_str = match.group(1)
353 prefixes += [ p for p in split_prefixes(prefix_str) \
354 if p.lower() not in drop_prefixes]
356 subject = match.group(2)
357 match = prefix_re.match(subject)
359 subject = normalise_space(subject)
361 subject = subject.strip()
363 subject = '[%s] %s' % (','.join(prefixes), subject)
367 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
368 def clean_content(str):
369 """ Try to remove signature (-- ) and list footer (_____) cruft """
370 str = sig_re.sub('', str)
373 def get_state(state_name):
374 """ Return the state with the given name or the default State """
377 return State.objects.get(name__iexact=state_name)
378 except State.DoesNotExist:
380 return get_default_initial_patch_state()
382 def get_delegate(delegate_email):
383 """ Return the delegate with the given email or None """
386 return User.objects.get(email__iexact=delegate_email)
387 except User.DoesNotExist:
391 def parse_mail(mail):
393 # some basic sanity checks
394 if 'From' not in mail:
397 if 'Subject' not in mail:
400 if 'Message-Id' not in mail:
403 hint = mail.get('X-Patchwork-Hint', '').lower()
407 project = find_project(mail)
409 print "no project found"
412 msgid = mail.get('Message-Id').strip()
414 (author, save_required) = find_author(mail)
416 (patch, comment) = find_content(project, mail)
419 # we delay the saving until we know we have a patch.
422 save_required = False
423 patch.submitter = author
425 patch.project = project
426 patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
427 patch.delegate = get_delegate(
428 mail.get('X-Patchwork-Delegate', '').strip())
431 except Exception, ex:
437 # looks like the original constructor for Comment takes the pk
438 # when the Comment is created. reset it here.
440 comment.patch = patch
441 comment.submitter = author
442 comment.msgid = msgid
445 except Exception, ex:
451 mail = message_from_file(sys.stdin)
452 return parse_mail(mail)
454 if __name__ == '__main__':
455 sys.exit(main(sys.argv))