1 # -*- coding: utf-8 -*-
2 from datetime import datetime
5 from django.contrib.auth.models import User
6 from django.core.files.base import ContentFile
7 from django.db import models, transaction
8 from django.db.models.base import ModelBase
9 from django.utils.translation import ugettext_lazy as _
10 from mercurial import simplemerge
12 from django.conf import settings
13 from dvcs.signals import post_commit, post_publishable
14 from dvcs.storage import GzipFileSystemStorage
17 class Tag(models.Model):
18 """A tag (e.g. document stage) which can be applied to a Change."""
19 name = models.CharField(_('name'), max_length=64)
20 slug = models.SlugField(_('slug'), unique=True, max_length=64, null=True, blank=True)
21 ordering = models.IntegerField(_('ordering'))
27 ordering = ['ordering']
28 verbose_name = _("tag")
29 verbose_name_plural = _("tags")
31 def __unicode__(self):
36 if slug in cls._object_cache:
37 return cls._object_cache[slug]
39 obj = cls.objects.get(slug=slug)
40 cls._object_cache[slug] = obj
44 def listener_changed(sender, instance, **kwargs):
45 sender._object_cache = {}
49 Returns the next tag - stage to work on.
50 Returns None for the last stage.
53 return type(self).objects.filter(ordering__gt=self.ordering)[0]
57 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
60 def data_upload_to(instance, filename):
61 return "%d/%d" % (instance.tree.pk, instance.pk)
64 class Change(models.Model):
66 Single document change related to previous change. The "parent"
67 argument points to the version against which this change has been
68 recorded. Initial text will have a null parent.
70 Data file contains a gzipped text of the document.
72 author = models.ForeignKey(User, null=True, blank=True, verbose_name=_('author'))
73 author_name = models.CharField(
74 _('author name'), max_length=128,
75 null=True, blank=True,
76 help_text=_("Used if author is not set."))
77 author_email = models.CharField(
78 _('author email'), max_length=128,
79 null=True, blank=True,
80 help_text=_("Used if author is not set."))
81 revision = models.IntegerField(_('revision'), db_index=True)
83 parent = models.ForeignKey(
85 null=True, blank=True, default=None,
86 verbose_name=_('parent'), related_name="children")
88 merge_parent = models.ForeignKey(
90 null=True, blank=True, default=None,
91 verbose_name=_('merge parent'),
92 related_name="merge_children")
94 description = models.TextField(_('description'), blank=True, default='')
95 created_at = models.DateTimeField(editable=False, db_index=True, default=datetime.now)
96 publishable = models.BooleanField(_('publishable'), default=False)
100 ordering = ('created_at',)
101 unique_together = ['tree', 'revision']
102 verbose_name = _("change")
103 verbose_name_plural = _("changes")
105 def __unicode__(self):
106 return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
108 def author_str(self):
110 return "%s %s <%s>" % (
111 self.author.first_name,
112 self.author.last_name,
120 def save(self, *args, **kwargs):
122 take the next available revision number if none yet
124 if self.revision is None:
125 tree_rev = self.tree.revision()
129 self.revision = tree_rev + 1
130 return super(Change, self).save(*args, **kwargs)
132 def materialize(self):
133 f = self.data.storage.open(self.data)
136 return unicode(text, 'utf-8')
138 def merge_with(self, other, author=None, author_name=None, author_email=None, description=u"Automatic merge."):
139 """Performs an automatic merge after straying commits."""
140 assert self.tree_id == other.tree_id # same tree
141 if other.parent_id == self.pk:
142 # immediate child - fast forward
145 local = self.materialize().encode('utf-8')
146 base = other.parent.materialize().encode('utf-8')
147 remote = other.materialize().encode('utf-8')
149 merge = simplemerge.Merge3Text(base, local, remote)
150 result = ''.join(merge.merge_lines())
151 merge_node = self.children.create(
152 merge_parent=other, tree=self.tree,
154 author_name=author_name,
155 author_email=author_email,
156 description=description)
157 merge_node.data.save('', ContentFile(result))
160 def revert(self, **kwargs):
161 """ commit this version of a doc as new head """
162 self.tree.commit(text=self.materialize(), **kwargs)
164 def set_publishable(self, publishable):
165 self.publishable = publishable
167 post_publishable.send(sender=self, publishable=publishable)
170 def create_tag_model(model):
171 name = model.__name__ + 'Tag'
173 class Meta(Tag.Meta):
174 app_label = model._meta.app_label
176 if hasattr(model, 'TagMeta'):
177 for attr, value in model.TagMeta.__dict__.items():
178 setattr(Meta, attr, value)
181 '__module__': model.__module__,
184 return type(name, (Tag,), attrs)
187 def create_change_model(model):
188 name = model.__name__ + 'Change'
189 repo = GzipFileSystemStorage(location=model.REPO_PATH)
191 class Meta(Change.Meta):
192 app_label = model._meta.app_label
195 '__module__': model.__module__,
196 'tree': models.ForeignKey(model, related_name='change_set', verbose_name=_('document')),
197 'tags': models.ManyToManyField(model.tag_model, verbose_name=_('tags'), related_name='change_set'),
198 'data': models.FileField(_('data'), upload_to=data_upload_to, storage=repo),
201 return type(name, (Change,), attrs)
204 class DocumentMeta(ModelBase):
205 """Metaclass for Document models."""
206 def __new__(mcs, name, bases, attrs):
208 model = super(DocumentMeta, mcs).__new__(mcs, name, bases, attrs)
209 if not model._meta.abstract:
210 # create a real Tag object and `stage' fk
211 model.tag_model = create_tag_model(model)
213 model.tag_model, verbose_name=_('stage'),
214 null=True, blank=True).contribute_to_class(model, 'stage')
216 # create real Change model and `head' fk
217 model.change_model = create_change_model(model)
221 null=True, blank=True, default=None,
222 verbose_name=_('head'),
223 help_text=_("This document's current head."),
224 editable=False).contribute_to_class(model, 'head')
227 User, null=True, blank=True, editable=False,
228 verbose_name=_('creator'), related_name="created_%s" % name.lower()
229 ).contribute_to_class(model, 'creator')
234 class Document(models.Model):
235 """File in repository. Subclass it to use version control in your app."""
237 __metaclass__ = DocumentMeta
239 # default repository path
240 REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
242 user = models.ForeignKey(
243 User, null=True, blank=True,
244 verbose_name=_('user'), help_text=_('Work assignment.'))
249 def __unicode__(self):
250 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
252 def materialize(self, change=None):
253 if self.head is None:
257 elif not isinstance(change, Change):
258 change = self.change_set.get(pk=change)
259 return change.materialize()
261 def commit(self, text, author=None, author_name=None, author_email=None, publishable=False, **kwargs):
262 """Commits a new revision.
264 This will automatically merge the commit into the main branch,
265 if parent is not document's head.
267 :param unicode text: new version of the document
268 :param parent: parent revision (head, if not specified)
269 :type parent: Change or None
270 :param User author: the commiter
271 :param unicode author_name: commiter name (if ``author`` not specified)
272 :param unicode author_email: commiter e-mail (if ``author`` not specified)
273 :param Tag[] tags: list of tags to apply to the new commit
274 :param bool publishable: set new commit as ready to publish
277 if 'parent' not in kwargs:
280 parent = kwargs['parent']
281 if parent is not None and not isinstance(parent, Change):
282 parent = self.change_set.objects.get(pk=kwargs['parent'])
284 tags = kwargs.get('tags', [])
286 # set stage to next tag after the commited one
287 self.stage = max(tags, key=lambda t: t.ordering).get_next()
289 change = self.change_set.create(
291 author_name=author_name,
292 author_email=author_email,
293 description=kwargs.get('description', ''),
294 publishable=publishable,
298 change.data.save('', ContentFile(text.encode('utf-8')))
302 # merge new change as new head
303 self.head = self.head.merge_with(
304 change, author=author,
305 author_name=author_name,
306 author_email=author_email)
311 post_commit.send(sender=self.head)
316 return self.change_set.all().order_by('revision')
319 rev = self.change_set.aggregate(
320 models.Max('revision'))['revision__max']
323 def at_revision(self, rev):
324 """Returns a Change with given revision number."""
325 return self.change_set.get(revision=rev)
327 def publishable(self):
328 changes = self.history().filter(publishable=True)
330 return changes.order_by('-revision')[0]
334 @transaction.commit_on_success
335 def prepend_history(self, other):
336 """Takes over the the other document's history and prepends to own."""
339 other_revs = other.change_set.all().count()
340 # workaround for a non-atomic UPDATE in SQLITE
341 self.change_set.all().update(revision=0-models.F('revision'))
342 self.change_set.all().update(revision=other_revs - models.F('revision'))
343 other.change_set.all().update(tree=self)
344 assert not other.change_set.exists()