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
41 from django.contrib.auth.models import User
43 list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']
45 whitespace_re = re.compile('\s+')
46 def normalise_space(str):
47 return whitespace_re.sub(' ', str).strip()
49 def clean_header(header):
50 """ Decode (possibly non-ascii) headers """
53 (frag_str, frag_encoding) = fragment
55 return frag_str.decode(frag_encoding)
56 return frag_str.decode()
58 fragments = map(decode, decode_header(header))
60 return normalise_space(u' '.join(fragments))
62 def find_project(mail):
64 listid_res = [re.compile('.*<([^>]+)>.*', re.S),
65 re.compile('^([\S]+)$', re.S)]
67 for header in list_id_headers:
70 for listid_re in listid_res:
71 match = listid_re.match(mail.get(header))
78 listid = match.group(1)
81 project = Project.objects.get(listid = listid)
83 except Project.DoesNotExist:
88 def find_author(mail):
90 from_header = clean_header(mail.get('From'))
91 (name, email) = (None, None)
93 # tuple of (regex, fn)
94 # - where fn returns a (name, email) tuple from the match groups resulting
95 # from re.match().groups()
97 # for "Firstname Lastname" <example@example.com> style addresses
98 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
100 # for example@example.com (Firstname Lastname) style addresses
101 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
104 (re.compile('(.*)'), (lambda g: (None, g[0]))),
107 for regex, fn in from_res:
108 match = regex.match(from_header)
110 (name, email) = fn(match.groups())
114 raise Exception("Could not parse From: header")
116 email = email.strip()
123 person = Person.objects.get(email__iexact = email)
124 except Person.DoesNotExist:
125 person = Person(name = name, email = email)
128 return (person, new_person)
131 t = parsedate_tz(mail.get('Date', ''))
133 return datetime.datetime.utcnow()
134 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
136 def mail_headers(mail):
137 return reduce(operator.__concat__,
138 ['%s: %s\n' % (k, Header(v, header_name = k, \
139 continuation_ws = '\t').encode()) \
140 for (k, v) in mail.items()])
142 def find_pull_request(content):
143 git_re = re.compile('^The following changes since commit.*' +
144 '^are available in the git repository at:\n'
145 '^\s*([\S]+://[^\n]+)$',
146 re.DOTALL | re.MULTILINE)
147 match = git_re.search(content)
149 return match.group(1)
152 def try_decode(payload, charset):
154 payload = unicode(payload, charset)
155 except UnicodeDecodeError:
159 def find_content(project, mail):
164 for part in mail.walk():
165 if part.get_content_maintype() != 'text':
168 payload = part.get_payload(decode=True)
169 subtype = part.get_content_subtype()
171 if not isinstance(payload, unicode):
172 charset = part.get_content_charset()
174 # Check that we have a charset that we understand. Otherwise,
175 # ignore it and fallback to our standard set.
176 if charset is not None:
178 codec = codecs.lookup(charset)
182 # If there is no charset or if it is unknown, then try some common
183 # charsets before we fail.
185 try_charsets = ['utf-8', 'windows-1252', 'iso-8859-1']
187 try_charsets = [charset]
189 for cset in try_charsets:
190 decoded_payload = try_decode(payload, cset)
191 if decoded_payload is not None:
193 payload = decoded_payload
195 # Could not find a valid decoded payload. Fail.
199 if subtype in ['x-patch', 'x-diff']:
202 elif subtype == 'plain':
206 (patchbuf, c) = parse_patch(payload)
209 pullurl = find_pull_request(payload)
212 commentbuf += c.strip() + '\n'
217 if pullurl or patchbuf:
218 name = clean_subject(mail.get('Subject'), [project.linkname])
219 patch = Patch(name = name, pull_url = pullurl, content = patchbuf,
220 date = mail_date(mail), headers = mail_headers(mail))
223 # If this is a new patch, we defer setting comment.patch until
224 # patch has been saved by the caller
226 comment = Comment(date = mail_date(mail),
227 content = clean_content(commentbuf),
228 headers = mail_headers(mail))
231 cpatch = find_patch_for_comment(project, mail)
234 comment = Comment(patch = cpatch, date = mail_date(mail),
235 content = clean_content(commentbuf),
236 headers = mail_headers(mail))
238 return (patch, comment)
240 def find_patch_for_comment(project, mail):
241 # construct a list of possible reply message ids
243 if 'In-Reply-To' in mail:
244 refs.append(mail.get('In-Reply-To'))
246 if 'References' in mail:
247 rs = mail.get('References').split()
256 # first, check for a direct reply
258 patch = Patch.objects.get(project = project, msgid = ref)
260 except Patch.DoesNotExist:
263 # see if we have comments that refer to a patch
265 comment = Comment.objects.get(patch__project = project, msgid = ref)
267 except Comment.DoesNotExist:
273 split_re = re.compile('[,\s]+')
275 def split_prefixes(prefix):
276 """ Turn a prefix string into a list of prefix tokens """
278 matches = split_re.split(prefix)
279 return [ s for s in matches if s != '' ]
281 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
282 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
284 def clean_subject(subject, drop_prefixes = None):
285 """ Clean a Subject: header from an incoming patch.
287 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
288 default, only [PATCH] is removed, and we keep any other bracketed data
289 in the subject. If drop_prefixes is provided, remove those too,
290 comparing case-insensitively."""
293 subject = clean_header(subject)
295 if drop_prefixes is None:
298 drop_prefixes = [ s.lower() for s in drop_prefixes ]
300 drop_prefixes.append('patch')
302 # remove Re:, Fwd:, etc
303 subject = re_re.sub(' ', subject)
305 subject = normalise_space(subject)
309 match = prefix_re.match(subject)
312 prefix_str = match.group(1)
313 prefixes += [ p for p in split_prefixes(prefix_str) \
314 if p.lower() not in drop_prefixes]
316 subject = match.group(2)
317 match = prefix_re.match(subject)
319 subject = normalise_space(subject)
321 subject = subject.strip()
323 subject = '[%s] %s' % (','.join(prefixes), subject)
327 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
328 def clean_content(str):
329 """ Try to remove signature (-- ) and list footer (_____) cruft """
330 str = sig_re.sub('', str)
333 def get_state(state_name):
334 """ Return the state with the given name or the default State """
337 return State.objects.get(name__iexact=state_name)
338 except State.DoesNotExist:
340 return get_default_initial_patch_state()
342 def get_delegate(delegate_email):
343 """ Return the delegate with the given email or None """
346 return User.objects.get(email__iexact=delegate_email)
347 except User.DoesNotExist:
351 def parse_mail(mail):
353 # some basic sanity checks
354 if 'From' not in mail:
357 if 'Subject' not in mail:
360 if 'Message-Id' not in mail:
363 hint = mail.get('X-Patchwork-Hint', '').lower()
367 project = find_project(mail)
369 print "no project found"
372 msgid = mail.get('Message-Id').strip()
374 (author, save_required) = find_author(mail)
376 (patch, comment) = find_content(project, mail)
379 # we delay the saving until we know we have a patch.
382 save_required = False
383 patch.submitter = author
385 patch.project = project
386 patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
387 patch.delegate = get_delegate(
388 mail.get('X-Patchwork-Delegate', '').strip())
391 except Exception, ex:
397 # we defer this assignment until we know that we have a saved patch
399 comment.patch = patch
400 comment.submitter = author
401 comment.msgid = msgid
404 except Exception, ex:
411 mail = message_from_file(sys.stdin)
412 return parse_mail(mail)
414 if __name__ == '__main__':
415 sys.exit(main(sys.argv))