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