Remove unnecessary storage class.
[redakcja.git] / src / dvcs / models.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from datetime import datetime
5 import os.path
6 from zlib import compress, decompress
7
8 from django.contrib.auth.models import User
9 from django.core.files.base import ContentFile
10 from django.core.files.storage import FileSystemStorage
11 from django.db import models, transaction
12 from django.db.models.base import ModelBase
13 from django.utils.text import format_lazy
14 from django.utils.translation import ugettext_lazy as _
15 import merge3
16
17 from django.conf import settings
18 from dvcs.signals import post_commit, post_publishable
19
20
21 class Tag(models.Model):
22     """A tag (e.g. document stage) which can be applied to a Change."""
23     name = models.CharField(_('name'), max_length=64)
24     slug = models.SlugField(_('slug'), unique=True, max_length=64, null=True, blank=True)
25     ordering = models.IntegerField(_('ordering'))
26
27     _object_cache = {}
28
29     class Meta:
30         abstract = True
31         ordering = ['ordering']
32
33     def __str__(self):
34         return self.name
35
36     @classmethod
37     def get(cls, slug):
38         if slug in cls._object_cache:
39             return cls._object_cache[slug]
40         else:
41             obj = cls.objects.get(slug=slug)
42             cls._object_cache[slug] = obj
43             return obj
44
45     @staticmethod
46     def listener_changed(sender, instance, **kwargs):
47         sender._object_cache = {}
48
49     def get_next(self):
50         """
51             Returns the next tag - stage to work on.
52             Returns None for the last stage.
53         """
54         try:
55             return type(self).objects.filter(ordering__gt=self.ordering)[0]
56         except IndexError:
57             return None
58
59 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
60
61
62 def data_upload_to(instance, filename):
63     return "%d/%d" % (instance.tree.pk, instance.pk)
64
65
66 class Change(models.Model):
67     """
68         Single document change related to previous change. The "parent"
69         argument points to the version against which this change has been 
70         recorded. Initial text will have a null parent.
71         
72         Data file contains a gzipped text of the document.
73     """
74     author = models.ForeignKey(User, models.SET_NULL, null=True, blank=True, verbose_name=_('author'))
75     author_name = models.CharField(
76         _('author name'), max_length=128, null=True, blank=True, help_text=_("Used if author is not set."))
77     author_email = models.CharField(
78         _('author email'), max_length=128, null=True, blank=True, help_text=_("Used if author is not set."))
79     revision = models.IntegerField(_('revision'), db_index=True)
80
81     parent = models.ForeignKey(
82         'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('parent'), related_name="children")
83
84     merge_parent = models.ForeignKey(
85         'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('merge parent'), related_name="merge_children")
86
87     description = models.TextField(_('description'), blank=True, default='')
88     created_at = models.DateTimeField(editable=False, db_index=True, default=datetime.now)
89     publishable = models.BooleanField(_('publishable'), default=False)
90
91     class Meta:
92         abstract = True
93         ordering = ('created_at',)
94         unique_together = ['tree', 'revision']
95
96     def __str__(self):
97         return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
98
99     def author_str(self):
100         if self.author:
101             return "%s %s <%s>" % (
102                 self.author.first_name,
103                 self.author.last_name, 
104                 self.author.email)
105         else:
106             return "%s <%s>" % (
107                 self.author_name,
108                 self.author_email
109                 )
110
111     def save(self, *args, **kwargs):
112         """
113             take the next available revision number if none yet
114         """
115         if self.revision is None:
116             tree_rev = self.tree.revision()
117             if tree_rev is None:
118                 self.revision = 1
119             else:
120                 self.revision = tree_rev + 1
121         return super(Change, self).save(*args, **kwargs)
122
123     def save_text(self, text, **kwargs):
124         self.data.save(
125             '',
126             ContentFile(compress(text.encode('utf-8'))),
127             **kwargs
128         )
129
130     def materialize(self):
131         with self.data.open('rb') as f:
132             content = f.read()
133         return decompress(content).decode('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().splitlines(True)
145         base = other.parent.materialize().splitlines(True)
146         remote = other.materialize().splitlines(True)
147
148         merge = merge3.Merge3(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.save_text(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 = format_lazy(
175             '{} {} {}', _('tag'), _('for:'), model._meta.verbose_name)
176         verbose_name_plural = format_lazy(
177             '{} {} {}', _("tags"), _("for:"), 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 = FileSystemStorage(location=model.REPO_PATH)
189
190     class Meta(Change.Meta):
191         app_label = model._meta.app_label
192         verbose_name = format_lazy(
193             '{} {} {}', _("change"), _("for:"), model._meta.verbose_name)
194         verbose_name_plural = format_lazy(
195             '{} {} {}', _("changes"), _("for:"), model._meta.verbose_name)
196
197     attrs = {
198         '__module__': model.__module__,
199         'tree': models.ForeignKey(model, models.CASCADE, 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, models.CASCADE, 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(
222                 model.change_model, models.SET_NULL, null=True, blank=True, default=None,
223                 verbose_name=_('head'), help_text=_("This document's current head."),
224                 editable=False).contribute_to_class(model, 'head')
225
226             models.ForeignKey(
227                 User, models.SET_NULL, 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, metaclass=DocumentMeta):
235     """File in repository. Subclass it to use version control in your app."""
236
237     # default repository path
238     REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
239
240     user = models.ForeignKey(User, models.SET_NULL, null=True, blank=True, verbose_name=_('user'), help_text=_('Work assignment.'))
241
242     class Meta:
243         abstract = True
244
245     def __str__(self):
246         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
247
248     def materialize(self, change=None):
249         if self.head is None:
250             return u''
251         if change is None:
252             change = self.head
253         elif not isinstance(change, Change):
254             change = self.change_set.get(pk=change)
255         return change.materialize()
256
257     def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
258         """Commits a new revision.
259
260         This will automatically merge the commit into the main branch,
261         if parent is not document's head.
262
263         :param str text: new version of the document
264         :param parent: parent revision (head, if not specified)
265         :type parent: Change or None
266         :param User author: the commiter
267         :param str author_name: commiter name (if ``author`` not specified)
268         :param str author_email: commiter e-mail (if ``author`` not specified)
269         :param Tag[] tags: list of tags to apply to the new commit
270         :param bool publishable: set new commit as ready to publish
271         :returns: new head
272         """
273         if 'parent' not in kwargs:
274             parent = self.head
275         else:
276             parent = kwargs['parent']
277             if parent is not None and not isinstance(parent, Change):
278                 parent = self.change_set.objects.get(pk=kwargs['parent'])
279
280         tags = kwargs.get('tags', [])
281         if tags:
282             # set stage to next tag after the commited one
283             self.stage = max(tags, key=lambda t: t.ordering).get_next()
284
285         change = self.change_set.create(
286             author=author, author_name=author_name, author_email=author_email,
287             description=kwargs.get('description', ''), publishable=publishable, parent=parent)
288
289         change.tags.set(tags)
290         change.save_text(text)
291         change.save()
292
293         if self.head:
294             # merge new change as new head
295             self.head = self.head.merge_with(change, author=author,
296                     author_name=author_name,
297                     author_email=author_email)
298         else:
299             self.head = change
300         self.save()
301
302         post_commit.send(sender=self.head)
303
304         return self.head
305
306     def history(self):
307         return self.change_set.all().order_by('revision')
308
309     def revision(self):
310         rev = self.change_set.aggregate(
311                 models.Max('revision'))['revision__max']
312         return rev
313
314     def at_revision(self, rev):
315         """Returns a Change with given revision number."""
316         return self.change_set.get(revision=rev)
317
318     def publishable(self):
319         changes = self.history().filter(publishable=True)
320         if changes.exists():
321             return changes.order_by('-revision')[0]
322         else:
323             return None
324
325     @transaction.atomic
326     def prepend_history(self, other):
327         """Takes over the the other document's history and prepends to own."""
328
329         assert self != other
330         other_revs = other.change_set.all().count()
331         # workaround for a non-atomic UPDATE in SQLITE
332         self.change_set.all().update(revision=0-models.F('revision'))
333         self.change_set.all().update(revision=other_revs - models.F('revision'))
334         other.change_set.all().update(tree=self)
335         assert not other.change_set.exists()
336         other.delete()