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 matches = split_re.split(prefix)
273 return [ s for s in matches if s != '' ]
275 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
276 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
278 def clean_subject(subject, drop_prefixes = None):
279 """ Clean a Subject: header from an incoming patch.
281 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
282 default, only [PATCH] is removed, and we keep any other bracketed data
283 in the subject. If drop_prefixes is provided, remove those too,
284 comparing case-insensitively."""
287 subject = clean_header(subject)
289 if drop_prefixes is None:
292 drop_prefixes = [ s.lower() for s in drop_prefixes ]
294 drop_prefixes.append('patch')
296 # remove Re:, Fwd:, etc
297 subject = re_re.sub(' ', subject)
299 subject = normalise_space(subject)
303 match = prefix_re.match(subject)
306 prefix_str = match.group(1)
307 prefixes += [ p for p in split_prefixes(prefix_str) \
308 if p.lower() not in drop_prefixes]
310 subject = match.group(2)
311 match = prefix_re.match(subject)
313 subject = normalise_space(subject)
315 subject = subject.strip()
317 subject = '[%s] %s' % (','.join(prefixes), subject)
321 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
322 def clean_content(str):
323 """ Try to remove signature (-- ) and list footer (_____) cruft """
324 str = sig_re.sub('', str)
327 def get_state(state_name):
328 """ Return the state with the given name or the default State """
331 return State.objects.get(name__iexact=state_name)
332 except State.DoesNotExist:
334 return get_default_initial_patch_state()
336 def get_delegate(delegate_email):
337 """ Return the delegate with the given email or None """
340 return User.objects.get(email__iexact=delegate_email)
341 except User.DoesNotExist:
345 def parse_mail(mail):
347 # some basic sanity checks
348 if 'From' not in mail:
351 if 'Subject' not in mail:
354 if 'Message-Id' not in mail:
357 hint = mail.get('X-Patchwork-Hint', '').lower()
361 project = find_project(mail)
363 print "no project found"
366 msgid = mail.get('Message-Id').strip()
368 (author, save_required) = find_author(mail)
370 (patch, comment) = find_content(project, mail)
373 # we delay the saving until we know we have a patch.
376 save_required = False
377 patch.submitter = author
379 patch.project = project
380 patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
381 patch.delegate = get_delegate(
382 mail.get('X-Patchwork-Delegate', '').strip())
385 except Exception, ex:
391 # looks like the original constructor for Comment takes the pk
392 # when the Comment is created. reset it here.
394 comment.patch = patch
395 comment.submitter = author
396 comment.msgid = msgid
399 except Exception, ex:
405 mail = message_from_file(sys.stdin)
406 return parse_mail(mail)
408 if __name__ == '__main__':
409 sys.exit(main(sys.argv))