1 from datetime import datetime
4 from django.contrib.auth.models import User
5 from django.core.files.base import ContentFile
6 from django.core.files.storage import FileSystemStorage
7 from django.db import models, transaction
8 from django.db.models.base import ModelBase
9 from django.utils.translation import string_concat, ugettext_lazy as _
10 from mercurial import mdiff, 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,
21 null=True, blank=True)
22 ordering = models.IntegerField(_('ordering'))
28 ordering = ['ordering']
30 def __unicode__(self):
35 if slug in cls._object_cache:
36 return cls._object_cache[slug]
38 obj = cls.objects.get(slug=slug)
39 cls._object_cache[slug] = obj
43 def listener_changed(sender, instance, **kwargs):
44 sender._object_cache = {}
48 Returns the next tag - stage to work on.
49 Returns None for the last stage.
52 return type(self).objects.filter(ordering__gt=self.ordering)[0]
56 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
59 def data_upload_to(instance, filename):
60 return "%d/%d" % (instance.tree.pk, instance.pk)
62 class Change(models.Model):
64 Single document change related to previous change. The "parent"
65 argument points to the version against which this change has been
66 recorded. Initial text will have a null parent.
68 Data file contains a gzipped text of the document.
70 author = models.ForeignKey(User, null=True, blank=True, verbose_name=_('author'))
71 author_name = models.CharField(_('author name'), max_length=128,
72 null=True, blank=True,
73 help_text=_("Used if author is not set.")
75 author_email = models.CharField(_('author email'), max_length=128,
76 null=True, blank=True,
77 help_text=_("Used if author is not set.")
79 revision = models.IntegerField(_('revision'), db_index=True)
81 parent = models.ForeignKey('self',
82 null=True, blank=True, default=None,
83 verbose_name=_('parent'),
84 related_name="children")
86 merge_parent = models.ForeignKey('self',
87 null=True, blank=True, default=None,
88 verbose_name=_('merge parent'),
89 related_name="merge_children")
91 description = models.TextField(_('description'), blank=True, default='')
92 created_at = models.DateTimeField(editable=False, db_index=True,
94 publishable = models.BooleanField(_('publishable'), default=False)
98 ordering = ('created_at',)
99 unique_together = ['tree', 'revision']
101 def __unicode__(self):
102 return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
104 def author_str(self):
106 return "%s %s <%s>" % (
107 self.author.first_name,
108 self.author.last_name,
117 def save(self, *args, **kwargs):
119 take the next available revision number if none yet
121 if self.revision is None:
122 tree_rev = self.tree.revision()
126 self.revision = tree_rev + 1
127 return super(Change, self).save(*args, **kwargs)
129 def materialize(self):
130 f = self.data.storage.open(self.data)
133 return unicode(text, 'utf-8')
135 def merge_with(self, other, author=None,
136 author_name=None, author_email=None,
137 description=u"Automatic merge."):
138 """Performs an automatic merge after straying commits."""
139 assert self.tree_id == other.tree_id # same tree
140 if other.parent_id == self.pk:
141 # immediate child - fast forward
144 local = self.materialize().encode('utf-8')
145 base = other.parent.materialize().encode('utf-8')
146 remote = other.materialize().encode('utf-8')
148 merge = simplemerge.Merge3Text(base, local, remote)
149 result = ''.join(merge.merge_lines())
150 merge_node = self.children.create(
151 merge_parent=other, tree=self.tree,
153 author_name=author_name,
154 author_email=author_email,
155 description=description)
156 merge_node.data.save('', ContentFile(result))
159 def revert(self, **kwargs):
160 """ commit this version of a doc as new head """
161 self.tree.commit(text=self.materialize(), **kwargs)
163 def set_publishable(self, publishable):
164 self.publishable = publishable
166 post_publishable.send(sender=self, publishable=publishable)
171 def create_tag_model(model):
172 name = model.__name__ + 'Tag'
174 class Meta(Tag.Meta):
175 app_label = model._meta.app_label
176 verbose_name = string_concat(_("tag"), " ", _("for:"), " ",
177 model._meta.verbose_name)
178 verbose_name_plural = string_concat(_("tags"), " ", _("for:"), " ",
179 model._meta.verbose_name)
182 '__module__': model.__module__,
185 return type(name, (Tag,), attrs)
188 def create_change_model(model):
189 name = model.__name__ + 'Change'
190 repo = GzipFileSystemStorage(location=model.REPO_PATH)
192 class Meta(Change.Meta):
193 app_label = model._meta.app_label
194 verbose_name = string_concat(_("change"), " ", _("for:"), " ",
195 model._meta.verbose_name)
196 verbose_name_plural = string_concat(_("changes"), " ", _("for:"), " ",
197 model._meta.verbose_name)
200 '__module__': model.__module__,
201 'tree': models.ForeignKey(model, related_name='change_set', verbose_name=_('document')),
202 'tags': models.ManyToManyField(model.tag_model, verbose_name=_('tags'), related_name='change_set'),
203 'data': models.FileField(_('data'), upload_to=data_upload_to, storage=repo),
206 return type(name, (Change,), attrs)
209 class DocumentMeta(ModelBase):
210 "Metaclass for Document models."
211 def __new__(cls, name, bases, attrs):
213 model = super(DocumentMeta, cls).__new__(cls, name, bases, attrs)
214 if not model._meta.abstract:
215 # create a real Tag object and `stage' fk
216 model.tag_model = create_tag_model(model)
217 models.ForeignKey(model.tag_model, verbose_name=_('stage'),
218 null=True, blank=True).contribute_to_class(model, 'stage')
220 # create real Change model and `head' fk
221 model.change_model = create_change_model(model)
223 models.ForeignKey(model.change_model,
224 null=True, blank=True, default=None,
225 verbose_name=_('head'),
226 help_text=_("This document's current head."),
227 editable=False).contribute_to_class(model, 'head')
229 models.ForeignKey(User, null=True, blank=True, editable=False,
230 verbose_name=_('creator'), related_name="created_%s" % name.lower()
231 ).contribute_to_class(model, 'creator')
236 class Document(models.Model):
237 """File in repository. Subclass it to use version control in your app."""
239 __metaclass__ = DocumentMeta
241 # default repository path
242 REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
244 user = models.ForeignKey(User, null=True, blank=True,
245 verbose_name=_('user'), help_text=_('Work assignment.'))
250 def __unicode__(self):
251 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
253 def materialize(self, change=None):
254 if self.head is None:
258 elif not isinstance(change, Change):
259 change = self.change_set.get(pk=change)
260 return change.materialize()
262 def commit(self, text, author=None, author_name=None, author_email=None,
263 publishable=False, **kwargs):
264 """Commits a new revision.
266 This will automatically merge the commit into the main branch,
267 if parent is not document's head.
269 :param unicode text: new version of the document
270 :param parent: parent revision (head, if not specified)
271 :type parent: Change or None
272 :param User author: the commiter
273 :param unicode author_name: commiter name (if ``author`` not specified)
274 :param unicode author_email: commiter e-mail (if ``author`` not specified)
275 :param Tag[] tags: list of tags to apply to the new commit
276 :param bool publishable: set new commit as ready to publish
279 if 'parent' not in kwargs:
282 parent = kwargs['parent']
283 if parent is not None and not isinstance(parent, Change):
284 parent = self.change_set.objects.get(pk=kwargs['parent'])
286 tags = kwargs.get('tags', [])
288 # set stage to next tag after the commited one
289 self.stage = max(tags, key=lambda t: t.ordering).next()
291 change = self.change_set.create(author=author,
292 author_name=author_name,
293 author_email=author_email,
294 description=kwargs.get('description', ''),
295 publishable=publishable,
299 change.data.save('', ContentFile(text.encode('utf-8')))
303 # merge new change as new head
304 self.head = self.head.merge_with(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()