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
29 from email.header import Header, decode_header
30 from email.utils import parsedate_tz, mktime_tz
32 from patchwork.parser import parse_patch
33 from patchwork.models import Patch, Project, Person, Comment, State, \
34 get_default_initial_patch_state
36 from django.contrib.auth.models import User
38 list_id_headers = ['List-ID', 'X-Mailing-List', 'X-list']
40 whitespace_re = re.compile('\s+')
41 def normalise_space(str):
42 return whitespace_re.sub(' ', str).strip()
44 def clean_header(header):
45 """ Decode (possibly non-ascii) headers """
48 (frag_str, frag_encoding) = fragment
50 return frag_str.decode(frag_encoding)
51 return frag_str.decode()
53 fragments = map(decode, decode_header(header))
55 return normalise_space(u' '.join(fragments))
57 def find_project(mail):
59 listid_res = [re.compile('.*<([^>]+)>.*', re.S),
60 re.compile('^([\S]+)$', re.S)]
62 for header in list_id_headers:
65 for listid_re in listid_res:
66 match = listid_re.match(mail.get(header))
73 listid = match.group(1)
76 project = Project.objects.get(listid = listid)
78 except Project.DoesNotExist:
83 def find_author(mail):
85 from_header = clean_header(mail.get('From'))
86 (name, email) = (None, None)
88 # tuple of (regex, fn)
89 # - where fn returns a (name, email) tuple from the match groups resulting
90 # from re.match().groups()
92 # for "Firstname Lastname" <example@example.com> style addresses
93 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
95 # for example@example.com (Firstname Lastname) style addresses
96 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
99 (re.compile('(.*)'), (lambda g: (None, g[0]))),
102 for regex, fn in from_res:
103 match = regex.match(from_header)
105 (name, email) = fn(match.groups())
109 raise Exception("Could not parse From: header")
111 email = email.strip()
118 person = Person.objects.get(email__iexact = email)
119 except Person.DoesNotExist:
120 person = Person(name = name, email = email)
123 return (person, new_person)
126 t = parsedate_tz(mail.get('Date', ''))
128 return datetime.datetime.utcnow()
129 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
131 def mail_headers(mail):
132 return reduce(operator.__concat__,
133 ['%s: %s\n' % (k, Header(v, header_name = k, \
134 continuation_ws = '\t').encode()) \
135 for (k, v) in mail.items()])
137 def find_pull_request(content):
138 git_re = re.compile('^The following changes since commit.*' +
139 '^are available in the git repository at:\n'
140 '^\s*([\S]+://[^\n]+)$',
141 re.DOTALL | re.MULTILINE)
142 match = git_re.search(content)
144 return match.group(1)
147 def try_decode(payload, charset):
149 payload = unicode(payload, charset)
150 except UnicodeDecodeError:
154 def find_content(project, mail):
159 for part in mail.walk():
160 if part.get_content_maintype() != 'text':
163 payload = part.get_payload(decode=True)
164 subtype = part.get_content_subtype()
166 if not isinstance(payload, unicode):
167 charset = part.get_content_charset()
169 # Check that we have a charset that we understand. Otherwise,
170 # ignore it and fallback to our standard set.
171 if charset is not None:
173 codec = codecs.lookup(charset)
177 # If there is no charset or if it is unknown, then try some common
178 # charsets before we fail.
180 try_charsets = ['utf-8', 'windows-1252', 'iso-8859-1']
182 try_charsets = [charset]
184 for cset in try_charsets:
185 decoded_payload = try_decode(payload, cset)
186 if decoded_payload is not None:
188 payload = decoded_payload
190 # Could not find a valid decoded payload. Fail.
194 if subtype in ['x-patch', 'x-diff']:
197 elif subtype == 'plain':
201 (patchbuf, c) = parse_patch(payload)
204 pullurl = find_pull_request(payload)
207 commentbuf += c.strip() + '\n'
212 if pullurl or patchbuf:
213 name = clean_subject(mail.get('Subject'), [project.linkname])
214 patch = Patch(name = name, pull_url = pullurl, content = patchbuf,
215 date = mail_date(mail), headers = mail_headers(mail))
218 # If this is a new patch, we defer setting comment.patch until
219 # patch has been saved by the caller
221 comment = Comment(date = mail_date(mail),
222 content = clean_content(commentbuf),
223 headers = mail_headers(mail))
226 cpatch = find_patch_for_comment(project, mail)
229 comment = Comment(patch = cpatch, date = mail_date(mail),
230 content = clean_content(commentbuf),
231 headers = mail_headers(mail))
233 return (patch, comment)
235 def find_patch_for_comment(project, mail):
236 # construct a list of possible reply message ids
238 if 'In-Reply-To' in mail:
239 refs.append(mail.get('In-Reply-To'))
241 if 'References' in mail:
242 rs = mail.get('References').split()
251 # first, check for a direct reply
253 patch = Patch.objects.get(project = project, msgid = ref)
255 except Patch.DoesNotExist:
258 # see if we have comments that refer to a patch
260 comment = Comment.objects.get(patch__project = project, msgid = ref)
262 except Comment.DoesNotExist:
268 split_re = re.compile('[,\s]+')
270 def split_prefixes(prefix):
271 """ Turn a prefix string into a list of prefix tokens """
273 matches = split_re.split(prefix)
274 return [ s for s in matches if s != '' ]
276 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
277 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
279 def clean_subject(subject, drop_prefixes = None):
280 """ Clean a Subject: header from an incoming patch.
282 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
283 default, only [PATCH] is removed, and we keep any other bracketed data
284 in the subject. If drop_prefixes is provided, remove those too,
285 comparing case-insensitively."""
288 subject = clean_header(subject)
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 get_state(state_name):
329 """ Return the state with the given name or the default State """
332 return State.objects.get(name__iexact=state_name)
333 except State.DoesNotExist:
335 return get_default_initial_patch_state()
337 def get_delegate(delegate_email):
338 """ Return the delegate with the given email or None """
341 return User.objects.get(email__iexact=delegate_email)
342 except User.DoesNotExist:
346 def parse_mail(mail):
348 # some basic sanity checks
349 if 'From' not in mail:
352 if 'Subject' not in mail:
355 if 'Message-Id' not in mail:
358 hint = mail.get('X-Patchwork-Hint', '').lower()
362 project = find_project(mail)
364 print "no project found"
367 msgid = mail.get('Message-Id').strip()
369 (author, save_required) = find_author(mail)
371 (patch, comment) = find_content(project, mail)
374 # we delay the saving until we know we have a patch.
377 save_required = False
378 patch.submitter = author
380 patch.project = project
381 patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
382 patch.delegate = get_delegate(
383 mail.get('X-Patchwork-Delegate', '').strip())
386 except Exception, ex:
392 # we defer this assignment until we know that we have a saved patch
394 comment.patch = patch
395 comment.submitter = author
396 comment.msgid = msgid
399 except Exception, ex:
406 mail = message_from_file(sys.stdin)
407 return parse_mail(mail)
409 if __name__ == '__main__':
410 sys.exit(main(sys.argv))