style
[redakcja.git] / apps / dvcs / models.py
1 # -*- coding: utf-8 -*-
2 from datetime import datetime
3 import os.path
4
5 from django.contrib.auth.models import User
6 from django.core.files.base import ContentFile
7 from django.db import models, transaction
8 from django.db.models.base import ModelBase
9 from django.utils.translation import ugettext_lazy as _
10 from mercurial import simplemerge
11
12 from django.conf import settings
13 from dvcs.signals import post_commit, post_publishable
14 from dvcs.storage import GzipFileSystemStorage
15
16
17 class Tag(models.Model):
18     """A tag (e.g. document stage) which can be applied to a Change."""
19     name = models.CharField(_('name'), max_length=64)
20     slug = models.SlugField(_('slug'), unique=True, max_length=64, null=True, blank=True)
21     ordering = models.IntegerField(_('ordering'))
22
23     _object_cache = {}
24
25     class Meta:
26         abstract = True
27         ordering = ['ordering']
28         verbose_name = _("tag")
29         verbose_name_plural = _("tags")
30
31     def __unicode__(self):
32         return self.name
33
34     @classmethod
35     def get(cls, slug):
36         if slug in cls._object_cache:
37             return cls._object_cache[slug]
38         else:
39             obj = cls.objects.get(slug=slug)
40             cls._object_cache[slug] = obj
41             return obj
42
43     @staticmethod
44     def listener_changed(sender, instance, **kwargs):
45         sender._object_cache = {}
46
47     def get_next(self):
48         """
49             Returns the next tag - stage to work on.
50             Returns None for the last stage.
51         """
52         try:
53             return type(self).objects.filter(ordering__gt=self.ordering)[0]
54         except IndexError:
55             return None
56
57 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
58
59
60 def data_upload_to(instance, filename):
61     return "%d/%d" % (instance.tree.pk, instance.pk)
62
63
64 class Change(models.Model):
65     """
66         Single document change related to previous change. The "parent"
67         argument points to the version against which this change has been
68         recorded. Initial text will have a null parent.
69
70         Data file contains a gzipped text of the document.
71     """
72     author = models.ForeignKey(User, null=True, blank=True, verbose_name=_('author'))
73     author_name = models.CharField(
74         _('author name'), max_length=128,
75         null=True, blank=True,
76         help_text=_("Used if author is not set."))
77     author_email = models.CharField(
78         _('author email'), max_length=128,
79         null=True, blank=True,
80         help_text=_("Used if author is not set."))
81     revision = models.IntegerField(_('revision'), db_index=True)
82
83     parent = models.ForeignKey(
84         'self',
85         null=True, blank=True, default=None,
86         verbose_name=_('parent'), related_name="children")
87
88     merge_parent = models.ForeignKey(
89         'self',
90         null=True, blank=True, default=None,
91         verbose_name=_('merge parent'),
92         related_name="merge_children")
93
94     description = models.TextField(_('description'), blank=True, default='')
95     created_at = models.DateTimeField(editable=False, db_index=True, default=datetime.now)
96     publishable = models.BooleanField(_('publishable'), default=False)
97
98     class Meta:
99         abstract = True
100         ordering = ('created_at',)
101         unique_together = ['tree', 'revision']
102         verbose_name = _("change")
103         verbose_name_plural = _("changes")
104
105     def __unicode__(self):
106         return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
107
108     def author_str(self):
109         if self.author:
110             return "%s %s <%s>" % (
111                 self.author.first_name,
112                 self.author.last_name,
113                 self.author.email)
114         else:
115             return "%s <%s>" % (
116                 self.author_name,
117                 self.author_email
118                 )
119
120     def save(self, *args, **kwargs):
121         """
122             take the next available revision number if none yet
123         """
124         if self.revision is None:
125             tree_rev = self.tree.revision()
126             if tree_rev is None:
127                 self.revision = 1
128             else:
129                 self.revision = tree_rev + 1
130         return super(Change, self).save(*args, **kwargs)
131
132     def materialize(self):
133         f = self.data.storage.open(self.data)
134         text = f.read()
135         f.close()
136         return unicode(text, 'utf-8')
137
138     def merge_with(self, other, author=None, author_name=None, author_email=None, description=u"Automatic merge."):
139         """Performs an automatic merge after straying commits."""
140         assert self.tree_id == other.tree_id  # same tree
141         if other.parent_id == self.pk:
142             # immediate child - fast forward
143             return other
144
145         local = self.materialize().encode('utf-8')
146         base = other.parent.materialize().encode('utf-8')
147         remote = other.materialize().encode('utf-8')
148
149         merge = simplemerge.Merge3Text(base, local, remote)
150         result = ''.join(merge.merge_lines())
151         merge_node = self.children.create(
152                     merge_parent=other, tree=self.tree,
153                     author=author,
154                     author_name=author_name,
155                     author_email=author_email,
156                     description=description)
157         merge_node.data.save('', ContentFile(result))
158         return merge_node
159
160     def revert(self, **kwargs):
161         """ commit this version of a doc as new head """
162         self.tree.commit(text=self.materialize(), **kwargs)
163
164     def set_publishable(self, publishable):
165         self.publishable = publishable
166         self.save()
167         post_publishable.send(sender=self, publishable=publishable)
168
169
170 def create_tag_model(model):
171     name = model.__name__ + 'Tag'
172
173     class Meta(Tag.Meta):
174         app_label = model._meta.app_label
175
176     if hasattr(model, 'TagMeta'):
177         for attr, value in model.TagMeta.__dict__.items():
178             setattr(Meta, attr, value)
179
180     attrs = {
181         '__module__': model.__module__,
182         'Meta': Meta,
183     }
184     return type(name, (Tag,), attrs)
185
186
187 def create_change_model(model):
188     name = model.__name__ + 'Change'
189     repo = GzipFileSystemStorage(location=model.REPO_PATH)
190
191     class Meta(Change.Meta):
192         app_label = model._meta.app_label
193
194     attrs = {
195         '__module__': model.__module__,
196         'tree': models.ForeignKey(model, related_name='change_set', verbose_name=_('document')),
197         'tags': models.ManyToManyField(model.tag_model, verbose_name=_('tags'), related_name='change_set'),
198         'data': models.FileField(_('data'), upload_to=data_upload_to, storage=repo),
199         'Meta': Meta,
200     }
201     return type(name, (Change,), attrs)
202
203
204 class DocumentMeta(ModelBase):
205     """Metaclass for Document models."""
206     def __new__(mcs, name, bases, attrs):
207
208         model = super(DocumentMeta, mcs).__new__(mcs, name, bases, attrs)
209         if not model._meta.abstract:
210             # create a real Tag object and `stage' fk
211             model.tag_model = create_tag_model(model)
212             models.ForeignKey(
213                 model.tag_model, verbose_name=_('stage'),
214                 null=True, blank=True).contribute_to_class(model, 'stage')
215
216             # create real Change model and `head' fk
217             model.change_model = create_change_model(model)
218
219             models.ForeignKey(
220                 model.change_model,
221                 null=True, blank=True, default=None,
222                 verbose_name=_('head'),
223                 help_text=_("This document's current head."),
224                 editable=False).contribute_to_class(model, 'head')
225
226             models.ForeignKey(
227                 User, null=True, blank=True, editable=False,
228                 verbose_name=_('creator'), related_name="created_%s" % name.lower()
229                 ).contribute_to_class(model, 'creator')
230
231         return model
232
233
234 class Document(models.Model):
235     """File in repository. Subclass it to use version control in your app."""
236
237     __metaclass__ = DocumentMeta
238
239     # default repository path
240     REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
241
242     user = models.ForeignKey(
243         User, null=True, blank=True,
244         verbose_name=_('user'), help_text=_('Work assignment.'))
245
246     class Meta:
247         abstract = True
248
249     def __unicode__(self):
250         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
251
252     def materialize(self, change=None):
253         if self.head is None:
254             return u''
255         if change is None:
256             change = self.head
257         elif not isinstance(change, Change):
258             change = self.change_set.get(pk=change)
259         return change.materialize()
260
261     def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
262         """Commits a new revision.
263
264         This will automatically merge the commit into the main branch,
265         if parent is not document's head.
266
267         :param unicode text: new version of the document
268         :param parent: parent revision (head, if not specified)
269         :type parent: Change or None
270         :param User author: the commiter
271         :param unicode author_name: commiter name (if ``author`` not specified)
272         :param unicode author_email: commiter e-mail (if ``author`` not specified)
273         :param Tag[] tags: list of tags to apply to the new commit
274         :param bool publishable: set new commit as ready to publish
275         :returns: new head
276         """
277         if 'parent' not in kwargs:
278             parent = self.head
279         else:
280             parent = kwargs['parent']
281             if parent is not None and not isinstance(parent, Change):
282                 parent = self.change_set.objects.get(pk=kwargs['parent'])
283
284         tags = kwargs.get('tags', [])
285         if tags:
286             # set stage to next tag after the commited one
287             self.stage = max(tags, key=lambda t: t.ordering).get_next()
288
289         change = self.change_set.create(
290             author=author,
291             author_name=author_name,
292             author_email=author_email,
293             description=kwargs.get('description', ''),
294             publishable=publishable,
295             parent=parent)
296
297         change.tags = tags
298         change.data.save('', ContentFile(text.encode('utf-8')))
299         change.save()
300
301         if self.head:
302             # merge new change as new head
303             self.head = self.head.merge_with(
304                 change, author=author,
305                 author_name=author_name,
306                 author_email=author_email)
307         else:
308             self.head = change
309         self.save()
310
311         post_commit.send(sender=self.head)
312
313         return self.head
314
315     def history(self):
316         return self.change_set.all().order_by('revision')
317
318     def revision(self):
319         rev = self.change_set.aggregate(
320                 models.Max('revision'))['revision__max']
321         return rev
322
323     def at_revision(self, rev):
324         """Returns a Change with given revision number."""
325         return self.change_set.get(revision=rev)
326
327     def publishable(self):
328         changes = self.history().filter(publishable=True)
329         if changes.exists():
330             return changes.order_by('-revision')[0]
331         else:
332             return None
333
334     @transaction.commit_on_success
335     def prepend_history(self, other):
336         """Takes over the the other document's history and prepends to own."""
337
338         assert self != other
339         other_revs = other.change_set.all().count()
340         # workaround for a non-atomic UPDATE in SQLITE
341         self.change_set.all().update(revision=0-models.F('revision'))
342         self.change_set.all().update(revision=other_revs - models.F('revision'))
343         other.change_set.all().update(tree=self)
344         assert not other.change_set.exists()
345         other.delete()