1 # Patchwork - automated patch tracking system
2 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
4 # This file is part of the Patchwork package.
6 # Patchwork is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # Patchwork is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Patchwork; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 from django.db import models
21 from django.contrib.auth.models import User
22 from django.core.urlresolvers import reverse
23 from django.contrib.sites.models import Site
24 from patchwork.parser import hash_patch
31 from email.mime.nonmultipart import MIMENonMultipart
32 from email.encoders import encode_7or8bit
33 from email.parser import HeaderParser
36 # Python 2.4 compatibility
37 from email.MIMENonMultipart import MIMENonMultipart
38 from email.Encoders import encode_7or8bit
39 from email.Parser import HeaderParser
41 email.utils = email.Utils
43 class Person(models.Model):
44 email = models.CharField(max_length=255, unique = True)
45 name = models.CharField(max_length=255, null = True, blank = True)
46 user = models.ForeignKey(User, null = True, blank = True)
48 def __unicode__(self):
50 return u'%s <%s>' % (self.name, self.email)
54 def link_to_user(self, user):
55 self.name = user.get_profile().name()
59 verbose_name_plural = 'People'
61 class Project(models.Model):
62 linkname = models.CharField(max_length=255, unique=True)
63 name = models.CharField(max_length=255, unique=True)
64 listid = models.CharField(max_length=255, unique=True)
65 listemail = models.CharField(max_length=200)
67 def __unicode__(self):
70 class UserProfile(models.Model):
71 user = models.ForeignKey(User, unique = True)
72 primary_project = models.ForeignKey(Project, null = True, blank = True)
73 maintainer_projects = models.ManyToManyField(Project,
74 related_name = 'maintainer_project')
75 send_email = models.BooleanField(default = False,
76 help_text = 'Selecting this option allows patchwork to send ' +
77 'email on your behalf')
78 patches_per_page = models.PositiveIntegerField(default = 100,
79 null = False, blank = False,
80 help_text = 'Number of patches to display per page')
83 if self.user.first_name or self.user.last_name:
84 names = filter(bool, [self.user.first_name, self.user.last_name])
85 return u' '.join(names)
86 return self.user.username
88 def contributor_projects(self):
89 submitters = Person.objects.filter(user = self.user)
90 return Project.objects \
93 submitter__in = submitters) \
94 .values('project_id').query)
97 def sync_person(self):
100 def n_todo_patches(self):
101 return self.todo_patches().count()
103 def todo_patches(self, project = None):
105 # filter on project, if necessary
107 qs = Patch.objects.filter(project = project)
111 qs = qs.filter(archived = False) \
112 .filter(delegate = self.user) \
113 .filter(state__in = \
114 State.objects.filter(action_required = True) \
119 super(UserProfile, self).save()
120 people = Person.objects.filter(email = self.user.email)
122 person = Person(email = self.user.email,
123 name = self.name(), user = self.user)
126 for person in people:
127 person.link_to_user(self.user)
130 def __unicode__(self):
133 def _user_created_callback(sender, created, instance, **kwargs):
136 profile = UserProfile(user = instance)
139 models.signals.post_save.connect(_user_created_callback, sender = User)
141 class State(models.Model):
142 name = models.CharField(max_length = 100)
143 ordering = models.IntegerField(unique = True)
144 action_required = models.BooleanField(default = True)
146 def __unicode__(self):
150 ordering = ['ordering']
152 class HashField(models.CharField):
153 __metaclass__ = models.SubfieldBase
155 def __init__(self, algorithm = 'sha1', *args, **kwargs):
156 self.algorithm = algorithm
159 def _construct(string = ''):
160 return hashlib.new(self.algorithm, string)
161 self.construct = _construct
162 self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
164 modules = { 'sha1': 'sha', 'md5': 'md5'}
166 if algorithm not in modules.keys():
167 raise NameError("Unknown algorithm '%s'" % algorithm)
169 self.construct = __import__(modules[algorithm]).new
171 self.n_bytes = len(self.construct().hexdigest())
173 kwargs['max_length'] = self.n_bytes
174 super(HashField, self).__init__(*args, **kwargs)
177 return 'char(%d)' % self.n_bytes
179 class PatchMbox(MIMENonMultipart):
180 patch_charset = 'utf-8'
181 def __init__(self, _text):
182 MIMENonMultipart.__init__(self, 'text', 'plain',
183 **{'charset': self.patch_charset})
184 self.set_payload(_text.encode(self.patch_charset))
187 class Patch(models.Model):
188 project = models.ForeignKey(Project)
189 msgid = models.CharField(max_length=255)
190 name = models.CharField(max_length=255)
191 date = models.DateTimeField(default=datetime.datetime.now)
192 submitter = models.ForeignKey(Person)
193 delegate = models.ForeignKey(User, blank = True, null = True)
194 state = models.ForeignKey(State)
195 archived = models.BooleanField(default = False)
196 headers = models.TextField(blank = True)
197 content = models.TextField(null = True, blank = True)
198 pull_url = models.CharField(max_length=255, null = True, blank = True)
199 commit_ref = models.CharField(max_length=255, null = True, blank = True)
200 hash = HashField(null = True, blank = True)
202 def __unicode__(self):
206 return Comment.objects.filter(patch = self)
212 self.state = State.objects.get(ordering = 0)
214 if self.hash is None and self.content is not None:
215 self.hash = hash_patch(self.content).hexdigest()
217 super(Patch, self).save()
219 def is_editable(self, user):
220 if not user.is_authenticated():
223 if self.submitter.user == user or self.delegate == user:
226 profile = user.get_profile()
227 return self.project in user.get_profile().maintainer_projects.all()
230 f = PatchForm(instance = self, prefix = self.id)
234 fname_re = re.compile('[^-_A-Za-z0-9\.]+')
235 str = fname_re.sub('-', self.name)
236 return str.strip('-') + '.patch'
239 postscript_re = re.compile('\n-{2,3} ?\n')
243 comment = Comment.objects.get(patch = self, msgid = self.msgid)
249 body = comment.content.strip() + "\n"
251 parts = postscript_re.split(body, 1)
253 (body, postscript) = parts
254 body = body.strip() + "\n"
255 postscript = postscript.strip() + "\n"
260 for comment in Comment.objects.filter(patch = self) \
261 .exclude(msgid = self.msgid):
262 body += comment.patch_responses()
268 body += '---\n' + postscript.strip() + '\n'
271 body += '\n' + self.content
273 mail = PatchMbox(body)
274 mail['Subject'] = self.name
275 mail['Date'] = email.utils.formatdate(
276 time.mktime(self.date.utctimetuple()))
277 mail['From'] = unicode(self.submitter)
278 mail['X-Patchwork-Id'] = str(self.id)
279 mail['Message-Id'] = self.msgid
280 mail.set_unixfrom('From patchwork ' + self.date.ctime())
283 copied_headers = ['To', 'Cc']
284 orig_headers = HeaderParser().parsestr(str(self.headers))
285 for header in copied_headers:
286 if header in orig_headers:
287 mail[header] = orig_headers[header]
292 def get_absolute_url(self):
293 return ('patchwork.views.patch.patch', (), {'patch_id': self.id})
296 verbose_name_plural = 'Patches'
298 unique_together = [('msgid', 'project')]
300 class Comment(models.Model):
301 patch = models.ForeignKey(Patch)
302 msgid = models.CharField(max_length=255)
303 submitter = models.ForeignKey(Person)
304 date = models.DateTimeField(default = datetime.datetime.now)
305 headers = models.TextField(blank = True)
306 content = models.TextField()
308 response_re = re.compile( \
309 '^(Tested|Reviewed|Acked|Signed-off|Nacked|Reported)-by: .*$',
312 def patch_responses(self):
313 return ''.join([ match.group(0) + '\n' for match in \
314 self.response_re.finditer(self.content)])
318 unique_together = [('msgid', 'patch')]
320 class Bundle(models.Model):
321 owner = models.ForeignKey(User)
322 project = models.ForeignKey(Project)
323 name = models.CharField(max_length = 50, null = False, blank = False)
324 patches = models.ManyToManyField(Patch, through = 'BundlePatch')
325 public = models.BooleanField(default = False)
328 return self.patches.all().count()
330 def ordered_patches(self):
331 return self.patches.order_by('bundlepatch__order')
333 def append_patch(self, patch):
334 # todo: use the aggregate queries in django 1.1
335 orders = BundlePatch.objects.filter(bundle = self).order_by('-order') \
339 max_order = orders[0]['order']
343 # see if the patch is already in this bundle
344 if BundlePatch.objects.filter(bundle = self, patch = patch).count():
345 raise Exception("patch is already in bundle")
347 bp = BundlePatch.objects.create(bundle = self, patch = patch,
348 order = max_order + 1)
352 unique_together = [('owner', 'name')]
354 def public_url(self):
357 site = Site.objects.get_current()
358 return 'http://%s%s' % (site.domain,
359 reverse('patchwork.views.bundle.public',
361 'username': self.owner.username,
362 'bundlename': self.name
366 return '\n'.join([p.mbox().as_string(True) \
367 for p in self.ordered_patches()])
369 class BundlePatch(models.Model):
370 patch = models.ForeignKey(Patch)
371 bundle = models.ForeignKey(Bundle)
372 order = models.IntegerField()
375 unique_together = [('bundle', 'patch')]
378 class UserPersonConfirmation(models.Model):
379 user = models.ForeignKey(User)
380 email = models.CharField(max_length = 200)
382 date = models.DateTimeField(default=datetime.datetime.now)
383 active = models.BooleanField(default = True)
390 person = Person.objects.get(email__iexact = self.email)
394 person = Person(email = self.email)
396 person.link_to_user(self.user)
404 str = '%s%s%d' % (self.user, self.email, random.randint(0, max))
405 self.key = self._meta.get_field('key').construct(str).hexdigest()
406 super(UserPersonConfirmation, self).save()