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_re = re.compile('.*<([^>]+)>.*', re.S)
62 for header in list_id_headers:
64 match = listid_re.match(mail.get(header))
68 listid = match.group(1)
71 project = Project.objects.get(listid = listid)
78 def find_author(mail):
80 from_header = clean_header(mail.get('From'))
81 (name, email) = (None, None)
83 # tuple of (regex, fn)
84 # - where fn returns a (name, email) tuple from the match groups resulting
85 # from re.match().groups()
87 # for "Firstname Lastname" <example@example.com> style addresses
88 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
90 # for example@example.com (Firstname Lastname) style addresses
91 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
94 (re.compile('(.*)'), (lambda g: (None, g[0]))),
97 for regex, fn in from_res:
98 match = regex.match(from_header)
100 (name, email) = fn(match.groups())
104 raise Exception("Could not parse From: header")
106 email = email.strip()
113 person = Person.objects.get(email__iexact = email)
114 except Person.DoesNotExist:
115 person = Person(name = name, email = email)
118 return (person, new_person)
121 t = parsedate_tz(mail.get('Date', ''))
123 return datetime.datetime.utcnow()
124 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
126 def mail_headers(mail):
127 return reduce(operator.__concat__,
128 ['%s: %s\n' % (k, Header(v, header_name = k, \
129 continuation_ws = '\t').encode()) \
130 for (k, v) in mail.items()])
132 def find_content(project, mail):
136 for part in mail.walk():
137 if part.get_content_maintype() != 'text':
140 payload = part.get_payload(decode=True)
142 if part.get_content_subtype() == 'x-patch':
145 if part.get_content_subtype() == 'plain':
147 (patchbuf, c) = parse_patch(payload)
152 commentbuf += c.strip() + '\n'
159 name = clean_subject(mail.get('Subject'), [project.linkname])
160 patch = Patch(name = name, content = patchbuf,
161 date = mail_date(mail), headers = mail_headers(mail))
167 cpatch = find_patch_for_comment(mail)
170 comment = Comment(patch = cpatch, date = mail_date(mail),
171 content = clean_content(commentbuf),
172 headers = mail_headers(mail))
174 return (patch, comment)
176 def find_patch_for_comment(mail):
177 # construct a list of possible reply message ids
179 if 'In-Reply-To' in mail:
180 refs.append(mail.get('In-Reply-To'))
182 if 'References' in mail:
183 rs = mail.get('References').split()
192 # first, check for a direct reply
194 patch = Patch.objects.get(msgid = ref)
196 except Patch.DoesNotExist:
199 # see if we have comments that refer to a patch
201 comment = Comment.objects.get(msgid = ref)
203 except Comment.DoesNotExist:
209 split_re = re.compile('[,\s]+')
211 def split_prefixes(prefix):
212 """ Turn a prefix string into a list of prefix tokens
214 >>> split_prefixes('PATCH')
216 >>> split_prefixes('PATCH,RFC')
218 >>> split_prefixes('')
220 >>> split_prefixes('PATCH,')
222 >>> split_prefixes('PATCH ')
224 >>> split_prefixes('PATCH,RFC')
226 >>> split_prefixes('PATCH 1/2')
229 matches = split_re.split(prefix)
230 return [ s for s in matches if s != '' ]
232 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
233 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
235 def clean_subject(subject, drop_prefixes = None):
236 """ Clean a Subject: header from an incoming patch.
238 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
239 default, only [PATCH] is removed, and we keep any other bracketed data
240 in the subject. If drop_prefixes is provided, remove those too,
241 comparing case-insensitively.
243 >>> clean_subject('meep')
245 >>> clean_subject('Re: meep')
247 >>> clean_subject('[PATCH] meep')
249 >>> clean_subject('[PATCH] meep \\n meep')
251 >>> clean_subject('[PATCH RFC] meep')
253 >>> clean_subject('[PATCH,RFC] meep')
255 >>> clean_subject('[PATCH,1/2] meep')
257 >>> clean_subject('[PATCH RFC 1/2] meep')
259 >>> clean_subject('[PATCH] [RFC] meep')
261 >>> clean_subject('[PATCH] [RFC,1/2] meep')
263 >>> clean_subject('[PATCH] [RFC] [1/2] meep')
265 >>> clean_subject('[PATCH] rewrite [a-z] regexes')
266 'rewrite [a-z] regexes'
267 >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
268 '[RFC] rewrite [a-z] regexes'
269 >>> clean_subject('[foo] [bar] meep', ['foo'])
271 >>> clean_subject('[FOO] [bar] meep', ['foo'])
275 if drop_prefixes is None:
278 drop_prefixes = [ s.lower() for s in drop_prefixes ]
280 drop_prefixes.append('patch')
282 # remove Re:, Fwd:, etc
283 subject = re_re.sub(' ', subject)
285 subject = normalise_space(subject)
289 match = prefix_re.match(subject)
292 prefix_str = match.group(1)
293 prefixes += [ p for p in split_prefixes(prefix_str) \
294 if p.lower() not in drop_prefixes]
296 subject = match.group(2)
297 match = prefix_re.match(subject)
299 subject = normalise_space(subject)
301 subject = subject.strip()
303 subject = '[%s] %s' % (','.join(prefixes), subject)
307 sig_re = re.compile('^(-- |_+)\n.*', re.S | re.M)
308 def clean_content(str):
309 """ Try to remove signature (-- ) and list footer (_____) cruft """
310 str = sig_re.sub('', str)
314 mail = message_from_file(sys.stdin)
316 # some basic sanity checks
317 if 'From' not in mail:
320 if 'Subject' not in mail:
323 if 'Message-Id' not in mail:
326 hint = mail.get('X-Patchwork-Hint', '').lower()
330 project = find_project(mail)
332 print "no project found"
335 msgid = mail.get('Message-Id').strip()
337 (author, save_required) = find_author(mail)
339 (patch, comment) = find_content(project, mail)
342 # we delay the saving until we know we have a patch.
345 save_required = False
346 patch.submitter = author
348 patch.project = project
351 except Exception, ex:
357 # looks like the original constructor for Comment takes the pk
358 # when the Comment is created. reset it here.
360 comment.patch = patch
361 comment.submitter = author
362 comment.msgid = msgid
365 except Exception, ex:
370 if __name__ == '__main__':
371 sys.exit(main(sys.argv))