1 # -*- coding: utf-8 -*-
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from datetime import datetime
9 from django.contrib.auth.models import User
10 from django.core.files.base import ContentFile
11 from django.db import models, transaction
12 from django.db.models.base import ModelBase
13 from django.utils.translation import string_concat, ugettext_lazy as _
14 from mercurial import simplemerge
16 from django.conf import settings
17 from dvcs.signals import post_commit, post_publishable
18 from dvcs.storage import GzipFileSystemStorage
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'))
31 ordering = ['ordering']
33 def __unicode__(self):
38 if slug in cls._object_cache:
39 return cls._object_cache[slug]
41 obj = cls.objects.get(slug=slug)
42 cls._object_cache[slug] = obj
46 def listener_changed(sender, instance, **kwargs):
47 sender._object_cache = {}
51 Returns the next tag - stage to work on.
52 Returns None for the last stage.
55 return type(self).objects.filter(ordering__gt=self.ordering)[0]
59 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
62 def data_upload_to(instance, filename):
63 return "%d/%d" % (instance.tree.pk, instance.pk)
66 class Change(models.Model):
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.
72 Data file contains a gzipped text of the document.
74 author = models.ForeignKey(User, 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)
81 parent = models.ForeignKey(
82 'self', null=True, blank=True, default=None, verbose_name=_('parent'), related_name="children")
84 merge_parent = models.ForeignKey(
85 'self', null=True, blank=True, default=None, verbose_name=_('merge parent'), related_name="merge_children")
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)
93 ordering = ('created_at',)
94 unique_together = ['tree', 'revision']
96 def __unicode__(self):
97 return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
101 return "%s %s <%s>" % (
102 self.author.first_name,
103 self.author.last_name,
111 def save(self, *args, **kwargs):
113 take the next available revision number if none yet
115 if self.revision is None:
116 tree_rev = self.tree.revision()
120 self.revision = tree_rev + 1
121 return super(Change, self).save(*args, **kwargs)
123 def materialize(self):
124 f = self.data.storage.open(self.data)
127 return unicode(text, 'utf-8')
129 def merge_with(self, other, author=None,
130 author_name=None, author_email=None,
131 description=u"Automatic merge."):
132 """Performs an automatic merge after straying commits."""
133 assert self.tree_id == other.tree_id # same tree
134 if other.parent_id == self.pk:
135 # immediate child - fast forward
138 local = self.materialize().encode('utf-8')
139 base = other.parent.materialize().encode('utf-8')
140 remote = other.materialize().encode('utf-8')
142 merge = simplemerge.Merge3Text(base, local, remote)
143 result = ''.join(merge.merge_lines())
144 merge_node = self.children.create(
145 merge_parent=other, tree=self.tree,
147 author_name=author_name,
148 author_email=author_email,
149 description=description)
150 merge_node.data.save('', ContentFile(result))
153 def revert(self, **kwargs):
154 """ commit this version of a doc as new head """
155 self.tree.commit(text=self.materialize(), **kwargs)
157 def set_publishable(self, publishable):
158 self.publishable = publishable
160 post_publishable.send(sender=self, publishable=publishable)
163 def create_tag_model(model):
164 name = model.__name__ + 'Tag'
166 class Meta(Tag.Meta):
167 app_label = model._meta.app_label
168 verbose_name = string_concat(
169 _("tag"), " ", _("for:"), " ", model._meta.verbose_name)
170 verbose_name_plural = string_concat(
171 _("tags"), " ", _("for:"), " ", model._meta.verbose_name)
174 '__module__': model.__module__,
177 return type(name, (Tag,), attrs)
180 def create_change_model(model):
181 name = model.__name__ + 'Change'
182 repo = GzipFileSystemStorage(location=model.REPO_PATH)
184 class Meta(Change.Meta):
185 app_label = model._meta.app_label
186 verbose_name = string_concat(
187 _("change"), " ", _("for:"), " ", model._meta.verbose_name)
188 verbose_name_plural = string_concat(
189 _("changes"), " ", _("for:"), " ", model._meta.verbose_name)
192 '__module__': model.__module__,
193 'tree': models.ForeignKey(model, related_name='change_set', verbose_name=_('document')),
194 'tags': models.ManyToManyField(model.tag_model, verbose_name=_('tags'), related_name='change_set'),
195 'data': models.FileField(_('data'), upload_to=data_upload_to, storage=repo),
198 return type(name, (Change,), attrs)
201 class DocumentMeta(ModelBase):
202 """Metaclass for Document models."""
203 def __new__(cls, name, bases, attrs):
205 model = super(DocumentMeta, cls).__new__(cls, name, bases, attrs)
206 if not model._meta.abstract:
207 # create a real Tag object and `stage' fk
208 model.tag_model = create_tag_model(model)
209 models.ForeignKey(model.tag_model, verbose_name=_('stage'),
210 null=True, blank=True).contribute_to_class(model, 'stage')
212 # create real Change model and `head' fk
213 model.change_model = create_change_model(model)
216 model.change_model, null=True, blank=True, default=None,
217 verbose_name=_('head'), help_text=_("This document's current head."),
218 editable=False).contribute_to_class(model, 'head')
221 User, null=True, blank=True, editable=False,
222 verbose_name=_('creator'), related_name="created_%s" % name.lower()
223 ).contribute_to_class(model, 'creator')
228 class Document(models.Model):
229 """File in repository. Subclass it to use version control in your app."""
231 __metaclass__ = DocumentMeta
233 # default repository path
234 REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
236 user = models.ForeignKey(User, null=True, blank=True, verbose_name=_('user'), help_text=_('Work assignment.'))
241 def __unicode__(self):
242 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
244 def materialize(self, change=None):
245 if self.head is None:
249 elif not isinstance(change, Change):
250 change = self.change_set.get(pk=change)
251 return change.materialize()
253 def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
254 """Commits a new revision.
256 This will automatically merge the commit into the main branch,
257 if parent is not document's head.
259 :param unicode text: new version of the document
260 :param parent: parent revision (head, if not specified)
261 :type parent: Change or None
262 :param User author: the commiter
263 :param unicode author_name: commiter name (if ``author`` not specified)
264 :param unicode author_email: commiter e-mail (if ``author`` not specified)
265 :param Tag[] tags: list of tags to apply to the new commit
266 :param bool publishable: set new commit as ready to publish
269 if 'parent' not in kwargs:
272 parent = kwargs['parent']
273 if parent is not None and not isinstance(parent, Change):
274 parent = self.change_set.objects.get(pk=kwargs['parent'])
276 tags = kwargs.get('tags', [])
278 # set stage to next tag after the commited one
279 self.stage = max(tags, key=lambda t: t.ordering).get_next()
281 change = self.change_set.create(
282 author=author, author_name=author_name, author_email=author_email,
283 description=kwargs.get('description', ''), publishable=publishable, parent=parent)
286 change.data.save('', ContentFile(text.encode('utf-8')))
290 # merge new change as new head
291 self.head = self.head.merge_with(change, author=author,
292 author_name=author_name,
293 author_email=author_email)
298 post_commit.send(sender=self.head)
303 return self.change_set.all().order_by('revision')
306 rev = self.change_set.aggregate(
307 models.Max('revision'))['revision__max']
310 def at_revision(self, rev):
311 """Returns a Change with given revision number."""
312 return self.change_set.get(revision=rev)
314 def publishable(self):
315 changes = self.history().filter(publishable=True)
317 return changes.order_by('-revision')[0]
322 def prepend_history(self, other):
323 """Takes over the the other document's history and prepends to own."""
326 other_revs = other.change_set.all().count()
327 # workaround for a non-atomic UPDATE in SQLITE
328 self.change_set.all().update(revision=0-models.F('revision'))
329 self.change_set.all().update(revision=other_revs - models.F('revision'))
330 other.change_set.all().update(tree=self)
331 assert not other.change_set.exists()