]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/models.py
Remove unused imports
[patchwork] / apps / patchwork / models.py
1 # Patchwork - automated patch tracking system
2 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
3 #
4 # This file is part of the Patchwork package.
5 #
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.
10 #
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.
15 #
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
19
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
25
26 import re
27 import datetime, time
28 import random
29
30 try:
31     from email.mime.nonmultipart import MIMENonMultipart
32     from email.encoders import encode_7or8bit
33     from email.parser import HeaderParser
34     import email.utils
35 except ImportError:
36     # Python 2.4 compatibility
37     from email.MIMENonMultipart import MIMENonMultipart
38     from email.Encoders import encode_7or8bit
39     from email.Parser import HeaderParser
40     import email.Utils
41     email.utils = email.Utils
42
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)
47
48     def __unicode__(self):
49         if self.name:
50             return u'%s <%s>' % (self.name, self.email)
51         else:
52             return self.email
53
54     def link_to_user(self, user):
55         self.name = user.get_profile().name()
56         self.user = user
57
58     class Meta:
59         verbose_name_plural = 'People'
60
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)
66
67     def __unicode__(self):
68         return self.name
69
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')
81
82     def name(self):
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
87
88     def contributor_projects(self):
89         submitters = Person.objects.filter(user = self.user)
90         return Project.objects \
91             .filter(id__in = \
92                     Patch.objects.filter(
93                         submitter__in = submitters) \
94                     .values('project_id').query)
95
96
97     def sync_person(self):
98         pass
99
100     def n_todo_patches(self):
101         return self.todo_patches().count()
102
103     def todo_patches(self, project = None):
104
105         # filter on project, if necessary
106         if project:
107             qs = Patch.objects.filter(project = project)
108         else:
109             qs = Patch.objects
110
111         qs = qs.filter(archived = False) \
112              .filter(delegate = self.user) \
113              .filter(state__in = \
114                      State.objects.filter(action_required = True) \
115                          .values('pk').query)
116         return qs
117
118     def save(self):
119         super(UserProfile, self).save()
120         people = Person.objects.filter(email = self.user.email)
121         if not people:
122             person = Person(email = self.user.email,
123                     name = self.name(), user = self.user)
124             person.save()
125         else:
126             for person in people:
127                  person.link_to_user(self.user)
128                  person.save()
129
130     def __unicode__(self):
131         return self.name()
132
133 class State(models.Model):
134     name = models.CharField(max_length = 100)
135     ordering = models.IntegerField(unique = True)
136     action_required = models.BooleanField(default = True)
137
138     def __unicode__(self):
139         return self.name
140
141     class Meta:
142         ordering = ['ordering']
143
144 class HashField(models.CharField):
145     __metaclass__ = models.SubfieldBase
146
147     def __init__(self, algorithm = 'sha1', *args, **kwargs):
148         self.algorithm = algorithm
149         try:
150             import hashlib
151             def _construct(string = ''):
152                 return hashlib.new(self.algorithm, string)
153             self.construct = _construct
154             self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
155         except ImportError:
156             modules = { 'sha1': 'sha', 'md5': 'md5'}
157
158             if algorithm not in modules.keys():
159                 raise NameError("Unknown algorithm '%s'" % algorithm)
160
161             self.construct = __import__(modules[algorithm]).new
162
163         self.n_bytes = len(self.construct().hexdigest())
164
165         kwargs['max_length'] = self.n_bytes
166         super(HashField, self).__init__(*args, **kwargs)
167
168     def db_type(self):
169         return 'char(%d)' % self.n_bytes
170
171 class PatchMbox(MIMENonMultipart):
172     patch_charset = 'utf-8'
173     def __init__(self, _text):
174         MIMENonMultipart.__init__(self, 'text', 'plain',
175                         **{'charset': self.patch_charset})
176         self.set_payload(_text.encode(self.patch_charset))
177         encode_7or8bit(self)
178
179 class Patch(models.Model):
180     project = models.ForeignKey(Project)
181     msgid = models.CharField(max_length=255)
182     name = models.CharField(max_length=255)
183     date = models.DateTimeField(default=datetime.datetime.now)
184     submitter = models.ForeignKey(Person)
185     delegate = models.ForeignKey(User, blank = True, null = True)
186     state = models.ForeignKey(State)
187     archived = models.BooleanField(default = False)
188     headers = models.TextField(blank = True)
189     content = models.TextField(null = True, blank = True)
190     pull_url = models.CharField(max_length=255, null = True, blank = True)
191     commit_ref = models.CharField(max_length=255, null = True, blank = True)
192     hash = HashField(null = True, blank = True)
193
194     def __unicode__(self):
195         return self.name
196
197     def comments(self):
198         return Comment.objects.filter(patch = self)
199
200     def save(self):
201         try:
202             s = self.state
203         except:
204             self.state = State.objects.get(ordering =  0)
205
206         if self.hash is None and self.content is not None:
207             self.hash = hash_patch(self.content).hexdigest()
208
209         super(Patch, self).save()
210
211     def is_editable(self, user):
212         if not user.is_authenticated():
213             return False
214
215         if self.submitter.user == user or self.delegate == user:
216             return True
217
218         profile = user.get_profile()
219         return self.project in user.get_profile().maintainer_projects.all()
220
221     def form(self):
222         f = PatchForm(instance = self, prefix = self.id)
223         return f
224
225     def filename(self):
226         fname_re = re.compile('[^-_A-Za-z0-9\.]+')
227         str = fname_re.sub('-', self.name)
228         return str.strip('-') + '.patch'
229
230     def mbox(self):
231         postscript_re = re.compile('\n-{2,3} ?\n')
232
233         comment = None
234         try:
235             comment = Comment.objects.get(patch = self, msgid = self.msgid)
236         except Exception:
237             pass
238
239         body = ''
240         if comment:
241             body = comment.content.strip() + "\n"
242
243         parts = postscript_re.split(body, 1)
244         if len(parts) == 2:
245             (body, postscript) = parts
246             body = body.strip() + "\n"
247             postscript = postscript.strip() + "\n"
248         else:
249             postscript = ''
250
251         responses = False
252         for comment in Comment.objects.filter(patch = self) \
253                 .exclude(msgid = self.msgid):
254             body += comment.patch_responses()
255
256         if body:
257             body += '\n'
258
259         if postscript:
260             body += '---\n' + postscript.strip() + '\n'
261
262         if self.content:
263             body += '\n' + self.content
264
265         mail = PatchMbox(body)
266         mail['Subject'] = self.name
267         mail['Date'] = email.utils.formatdate(
268                         time.mktime(self.date.utctimetuple()))
269         mail['From'] = unicode(self.submitter)
270         mail['X-Patchwork-Id'] = str(self.id)
271         mail['Message-Id'] = self.msgid
272         mail.set_unixfrom('From patchwork ' + self.date.ctime())
273
274
275         copied_headers = ['To', 'Cc']
276         orig_headers = HeaderParser().parsestr(str(self.headers))
277         for header in copied_headers:
278             if header in orig_headers:
279                 mail[header] = orig_headers[header]
280
281         return mail
282
283     @models.permalink
284     def get_absolute_url(self):
285         return ('patchwork.views.patch.patch', (), {'patch_id': self.id})
286
287     class Meta:
288         verbose_name_plural = 'Patches'
289         ordering = ['date']
290         unique_together = [('msgid', 'project')]
291
292 class Comment(models.Model):
293     patch = models.ForeignKey(Patch)
294     msgid = models.CharField(max_length=255)
295     submitter = models.ForeignKey(Person)
296     date = models.DateTimeField(default = datetime.datetime.now)
297     headers = models.TextField(blank = True)
298     content = models.TextField()
299
300     response_re = re.compile( \
301             '^(Tested|Reviewed|Acked|Signed-off|Nacked|Reported)-by: .*$',
302             re.M | re.I)
303
304     def patch_responses(self):
305         return ''.join([ match.group(0) + '\n' for match in \
306                                 self.response_re.finditer(self.content)])
307
308     class Meta:
309         ordering = ['date']
310         unique_together = [('msgid', 'patch')]
311
312 class Bundle(models.Model):
313     owner = models.ForeignKey(User)
314     project = models.ForeignKey(Project)
315     name = models.CharField(max_length = 50, null = False, blank = False)
316     patches = models.ManyToManyField(Patch, through = 'BundlePatch')
317     public = models.BooleanField(default = False)
318
319     def n_patches(self):
320         return self.patches.all().count()
321
322     def ordered_patches(self):
323         return self.patches.order_by('bundlepatch__order')
324
325     def append_patch(self, patch):
326         # todo: use the aggregate queries in django 1.1
327         orders = BundlePatch.objects.filter(bundle = self).order_by('-order') \
328                  .values('order')
329
330         if len(orders) > 0:
331             max_order = orders[0]['order']
332         else:
333             max_order = 0
334
335         # see if the patch is already in this bundle
336         if BundlePatch.objects.filter(bundle = self, patch = patch).count():
337             raise Exception("patch is already in bundle")
338
339         bp = BundlePatch.objects.create(bundle = self, patch = patch,
340                 order = max_order + 1)
341         bp.save()
342
343     class Meta:
344         unique_together = [('owner', 'name')]
345
346     def public_url(self):
347         if not self.public:
348             return None
349         site = Site.objects.get_current()
350         return 'http://%s%s' % (site.domain,
351                 reverse('patchwork.views.bundle.public',
352                         kwargs = {
353                                 'username': self.owner.username,
354                                 'bundlename': self.name
355                         }))
356
357     def mbox(self):
358         return '\n'.join([p.mbox().as_string(True) \
359                         for p in self.ordered_patches()])
360
361 class BundlePatch(models.Model):
362     patch = models.ForeignKey(Patch)
363     bundle = models.ForeignKey(Bundle)
364     order = models.IntegerField()
365
366     class Meta:
367         unique_together = [('bundle', 'patch')]
368         ordering = ['order']
369
370 class UserPersonConfirmation(models.Model):
371     user = models.ForeignKey(User)
372     email = models.CharField(max_length = 200)
373     key = HashField()
374     date = models.DateTimeField(default=datetime.datetime.now)
375     active = models.BooleanField(default = True)
376
377     def confirm(self):
378         if not self.active:
379             return
380         person = None
381         try:
382             person = Person.objects.get(email__iexact = self.email)
383         except Exception:
384             pass
385         if not person:
386             person = Person(email = self.email)
387
388         person.link_to_user(self.user)
389         person.save()
390         self.active = False
391         self.save()
392
393     def save(self):
394         max = 1 << 32
395         if self.key == '':
396             str = '%s%s%d' % (self.user, self.email, random.randint(0, max))
397             self.key = self._meta.get_field('key').construct(str).hexdigest()
398         super(UserPersonConfirmation, self).save()
399
400