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 _
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']
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']
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 str(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().splitlines(True)
139 base = other.parent.materialize().splitlines(True)
140 remote = other.materialize().splitlines(True)
142 merge = merge3.Merge3(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, metaclass=DocumentMeta):
229 """File in repository. Subclass it to use version control in your app."""
231 # default repository path
232 REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
234 user = models.ForeignKey(User, null=True, blank=True, verbose_name=_('user'), help_text=_('Work assignment.'))
240 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
242 def materialize(self, change=None):
243 if self.head is None:
247 elif not isinstance(change, Change):
248 change = self.change_set.get(pk=change)
249 return change.materialize()
251 def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
252 """Commits a new revision.
254 This will automatically merge the commit into the main branch,
255 if parent is not document's head.
257 :param str text: new version of the document
258 :param parent: parent revision (head, if not specified)
259 :type parent: Change or None
260 :param User author: the commiter
261 :param str author_name: commiter name (if ``author`` not specified)
262 :param str author_email: commiter e-mail (if ``author`` not specified)
263 :param Tag[] tags: list of tags to apply to the new commit
264 :param bool publishable: set new commit as ready to publish
267 if 'parent' not in kwargs:
270 parent = kwargs['parent']
271 if parent is not None and not isinstance(parent, Change):
272 parent = self.change_set.objects.get(pk=kwargs['parent'])
274 tags = kwargs.get('tags', [])
276 # set stage to next tag after the commited one
277 self.stage = max(tags, key=lambda t: t.ordering).get_next()
279 change = self.change_set.create(
280 author=author, author_name=author_name, author_email=author_email,
281 description=kwargs.get('description', ''), publishable=publishable, parent=parent)
284 change.data.save('', ContentFile(text.encode('utf-8')))
288 # merge new change as new head
289 self.head = self.head.merge_with(change, author=author,
290 author_name=author_name,
291 author_email=author_email)
296 post_commit.send(sender=self.head)
301 return self.change_set.all().order_by('revision')
304 rev = self.change_set.aggregate(
305 models.Max('revision'))['revision__max']
308 def at_revision(self, rev):
309 """Returns a Change with given revision number."""
310 return self.change_set.get(revision=rev)
312 def publishable(self):
313 changes = self.history().filter(publishable=True)
315 return changes.order_by('-revision')[0]
320 def prepend_history(self, other):
321 """Takes over the the other document's history and prepends to own."""
324 other_revs = other.change_set.all().count()
325 # workaround for a non-atomic UPDATE in SQLITE
326 self.change_set.all().update(revision=0-models.F('revision'))
327 self.change_set.all().update(revision=other_revs - models.F('revision'))
328 other.change_set.all().update(tree=self)
329 assert not other.change_set.exists()