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