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
30 from email.utils import parsedate_tz, mktime_tz
32 # Python 2.4 compatibility
33 from email.Header import 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 def find_project(mail):
43 listid_re = re.compile('.*<([^>]+)>.*', re.S)
45 for header in list_id_headers:
47 match = listid_re.match(mail.get(header))
51 listid = match.group(1)
54 project = Project.objects.get(listid = listid)
61 def find_author(mail):
63 from_header = mail.get('From').strip()
64 (name, email) = (None, None)
66 # tuple of (regex, fn)
67 # - where fn returns a (name, email) tuple from the match groups resulting
68 # from re.match().groups()
70 # for "Firstname Lastname" <example@example.com> style addresses
71 (re.compile('"?(.*?)"?\s*<([^>]+)>'), (lambda g: (g[0], g[1]))),
73 # for example@example.com (Firstname Lastname) style addresses
74 (re.compile('"?(.*?)"?\s*\(([^\)]+)\)'), (lambda g: (g[1], g[0]))),
77 (re.compile('(.*)'), (lambda g: (None, g[0]))),
80 for regex, fn in from_res:
81 match = regex.match(from_header)
83 (name, email) = fn(match.groups())
87 raise Exception("Could not parse From: header")
96 person = Person.objects.get(email = email)
97 except Person.DoesNotExist:
98 person = Person(name = name, email = email)
101 return (person, new_person)
104 t = parsedate_tz(mail.get('Date', ''))
107 return datetime.datetime.utcnow()
108 return datetime.datetime.utcfromtimestamp(mktime_tz(t))
110 def mail_headers(mail):
111 return reduce(operator.__concat__,
112 ['%s: %s\n' % (k, Header(v, header_name = k, \
113 continuation_ws = '\t').encode()) \
114 for (k, v) in mail.items()])
116 def find_content(project, mail):
120 for part in mail.walk():
121 if part.get_content_maintype() != 'text':
124 #print "\t%s, %s" % \
125 # (part.get_content_subtype(), part.get_content_charset())
127 charset = part.get_content_charset()
129 charset = mail.get_charset()
133 payload = unicode(part.get_payload(decode=True), charset, "replace")
135 if part.get_content_subtype() == 'x-patch':
138 if part.get_content_subtype() == 'plain':
140 (patchbuf, c) = parse_patch(payload)
145 commentbuf += c.strip() + '\n'
152 name = clean_subject(mail.get('Subject'), [project.linkname])
153 patch = Patch(name = name, content = patchbuf,
154 date = mail_date(mail), headers = mail_headers(mail))
160 cpatch = find_patch_for_comment(mail)
163 comment = Comment(patch = cpatch, date = mail_date(mail),
164 content = clean_content(commentbuf),
165 headers = mail_headers(mail))
167 return (patch, comment)
169 def find_patch_for_comment(mail):
170 # construct a list of possible reply message ids
172 if 'In-Reply-To' in mail:
173 refs.append(mail.get('In-Reply-To'))
175 if 'References' in mail:
176 rs = mail.get('References').split()
185 # first, check for a direct reply
187 patch = Patch.objects.get(msgid = ref)
189 except Patch.DoesNotExist:
192 # see if we have comments that refer to a patch
194 comment = Comment.objects.get(msgid = ref)
196 except Comment.DoesNotExist:
202 split_re = re.compile('[,\s]+')
204 def split_prefixes(prefix):
205 """ Turn a prefix string into a list of prefix tokens
207 >>> split_prefixes('PATCH')
209 >>> split_prefixes('PATCH,RFC')
211 >>> split_prefixes('')
213 >>> split_prefixes('PATCH,')
215 >>> split_prefixes('PATCH ')
217 >>> split_prefixes('PATCH,RFC')
219 >>> split_prefixes('PATCH 1/2')
222 matches = split_re.split(prefix)
223 return [ s for s in matches if s != '' ]
225 re_re = re.compile('^(re|fwd?)[:\s]\s*', re.I)
226 prefix_re = re.compile('^\[([^\]]*)\]\s*(.*)$')
227 whitespace_re = re.compile('\s+')
229 def clean_subject(subject, drop_prefixes = None):
230 """ Clean a Subject: header from an incoming patch.
232 Removes Re: and Fwd: strings, as well as [PATCH]-style prefixes. By
233 default, only [PATCH] is removed, and we keep any other bracketed data
234 in the subject. If drop_prefixes is provided, remove those too,
235 comparing case-insensitively.
237 >>> clean_subject('meep')
239 >>> clean_subject('Re: meep')
241 >>> clean_subject('[PATCH] meep')
243 >>> clean_subject('[PATCH] meep \\n meep')
245 >>> clean_subject('[PATCH RFC] meep')
247 >>> clean_subject('[PATCH,RFC] meep')
249 >>> clean_subject('[PATCH,1/2] meep')
251 >>> clean_subject('[PATCH RFC 1/2] meep')
253 >>> clean_subject('[PATCH] [RFC] meep')
255 >>> clean_subject('[PATCH] [RFC,1/2] meep')
257 >>> clean_subject('[PATCH] [RFC] [1/2] meep')
259 >>> clean_subject('[PATCH] rewrite [a-z] regexes')
260 'rewrite [a-z] regexes'
261 >>> clean_subject('[PATCH] [RFC] rewrite [a-z] regexes')
262 '[RFC] rewrite [a-z] regexes'
263 >>> clean_subject('[foo] [bar] meep', ['foo'])
265 >>> clean_subject('[FOO] [bar] meep', ['foo'])
269 if drop_prefixes is None:
272 drop_prefixes = [ s.lower() for s in drop_prefixes ]
274 drop_prefixes.append('patch')
276 # remove Re:, Fwd:, etc
277 subject = re_re.sub(' ', subject)
279 # normalise whitespace
280 subject = whitespace_re.sub(' ', subject)
284 match = prefix_re.match(subject)
287 prefix_str = match.group(1)
288 prefixes += [ p for p in split_prefixes(prefix_str) \
289 if p.lower() not in drop_prefixes]
291 subject = match.group(2)
292 match = prefix_re.match(subject)
294 subject = whitespace_re.sub(' ', subject)
296 subject = subject.strip()
298 subject = '[%s] %s' % (','.join(prefixes), subject)
302 sig_re = re.compile('^(-{2,3} ?|_+)\n.*', re.S | re.M)
303 def clean_content(str):
304 str = sig_re.sub('', str)
308 mail = message_from_file(sys.stdin)
310 # some basic sanity checks
311 if 'From' not in mail:
314 if 'Subject' not in mail:
317 if 'Message-Id' not in mail:
320 hint = mail.get('X-Patchwork-Hint', '').lower()
324 project = find_project(mail)
326 print "no project found"
329 msgid = mail.get('Message-Id').strip()
331 (author, save_required) = find_author(mail)
333 (patch, comment) = find_content(project, mail)
336 # we delay the saving until we know we have a patch.
339 save_required = False
340 patch.submitter = author
342 patch.project = project
345 except Exception, ex:
351 # looks like the original constructor for Comment takes the pk
352 # when the Comment is created. reset it here.
354 comment.patch = patch
355 comment.submitter = author
356 comment.msgid = msgid
359 except Exception, ex:
364 if __name__ == '__main__':
365 sys.exit(main(sys.argv))