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.
4 from datetime import datetime
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 _
15 from django.conf import settings
16 from dvcs.signals import post_commit, post_publishable
17 from dvcs.storage import GzipFileSystemStorage
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'))
30 ordering = ['ordering']
37 if slug in cls._object_cache:
38 return cls._object_cache[slug]
40 obj = cls.objects.get(slug=slug)
41 cls._object_cache[slug] = obj
45 def listener_changed(sender, instance, **kwargs):
46 sender._object_cache = {}
50 Returns the next tag - stage to work on.
51 Returns None for the last stage.
54 return type(self).objects.filter(ordering__gt=self.ordering)[0]
58 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
61 def data_upload_to(instance, filename):
62 return "%d/%d" % (instance.tree.pk, instance.pk)
65 class Change(models.Model):
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.
71 Data file contains a gzipped text of the document.
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)
80 parent = models.ForeignKey(
81 'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('parent'), related_name="children")
83 merge_parent = models.ForeignKey(
84 'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('merge parent'), related_name="merge_children")
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)
92 ordering = ('created_at',)
93 unique_together = ['tree', 'revision']
96 return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
100 return "%s %s <%s>" % (
101 self.author.first_name,
102 self.author.last_name,
110 def save(self, *args, **kwargs):
112 take the next available revision number if none yet
114 if self.revision is None:
115 tree_rev = self.tree.revision()
119 self.revision = tree_rev + 1
120 return super(Change, self).save(*args, **kwargs)
122 def materialize(self):
123 f = self.data.storage.open(self.data)
126 return str(text, 'utf-8')
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
137 local = self.materialize().splitlines(True)
138 base = other.parent.materialize().splitlines(True)
139 remote = other.materialize().splitlines(True)
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,
146 author_name=author_name,
147 author_email=author_email,
148 description=description)
149 merge_node.data.save('', ContentFile(result))
152 def revert(self, **kwargs):
153 """ commit this version of a doc as new head """
154 self.tree.commit(text=self.materialize(), **kwargs)
156 def set_publishable(self, publishable):
157 self.publishable = publishable
159 post_publishable.send(sender=self, publishable=publishable)
162 def create_tag_model(model):
163 name = model.__name__ + 'Tag'
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)
173 '__module__': model.__module__,
176 return type(name, (Tag,), attrs)
179 def create_change_model(model):
180 name = model.__name__ + 'Change'
181 repo = GzipFileSystemStorage(location=model.REPO_PATH)
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)
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),
197 return type(name, (Change,), attrs)
200 class DocumentMeta(ModelBase):
201 """Metaclass for Document models."""
202 def __new__(cls, name, bases, attrs):
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')
211 # create real Change model and `head' fk
212 model.change_model = create_change_model(model)
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')
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')
227 class Document(models.Model, metaclass=DocumentMeta):
228 """File in repository. Subclass it to use version control in your app."""
230 # default repository path
231 REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
233 user = models.ForeignKey(User, models.SET_NULL, null=True, blank=True, verbose_name=_('user'), help_text=_('Work assignment.'))
239 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
241 def materialize(self, change=None):
242 if self.head is None:
246 elif not isinstance(change, Change):
247 change = self.change_set.get(pk=change)
248 return change.materialize()
250 def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
251 """Commits a new revision.
253 This will automatically merge the commit into the main branch,
254 if parent is not document's head.
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
266 if 'parent' not in kwargs:
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'])
273 tags = kwargs.get('tags', [])
275 # set stage to next tag after the commited one
276 self.stage = max(tags, key=lambda t: t.ordering).get_next()
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)
282 change.tags.set(tags)
283 change.data.save('', ContentFile(text.encode('utf-8')))
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)
295 post_commit.send(sender=self.head)
300 return self.change_set.all().order_by('revision')
303 rev = self.change_set.aggregate(
304 models.Max('revision'))['revision__max']
307 def at_revision(self, rev):
308 """Returns a Change with given revision number."""
309 return self.change_set.get(revision=rev)
311 def publishable(self):
312 changes = self.history().filter(publishable=True)
314 return changes.order_by('-revision')[0]
319 def prepend_history(self, other):
320 """Takes over the the other document's history and prepends to own."""
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()