1 from django.db import models
2 from django.contrib.auth.models import User
3 from django.utils.translation import ugettext_lazy as _
4 from mercurial import mdiff, simplemerge
7 class Change(models.Model):
9 Single document change related to previous change. The "parent"
10 argument points to the version against which this change has been
11 recorded. Initial text will have a null parent.
13 Data contains a pickled diff needed to reproduce the initial document.
15 author = models.ForeignKey(User, null=True, blank=True)
16 patch = models.TextField(blank=True)
17 tree = models.ForeignKey('Document')
19 parent = models.ForeignKey('self',
20 null=True, blank=True, default=None,
21 related_name="children")
23 merge_parent = models.ForeignKey('self',
24 null=True, blank=True, default=None,
25 related_name="merge_children")
27 description = models.TextField(blank=True, default='')
28 created_at = models.DateTimeField(auto_now_add=True)
31 ordering = ('created_at',)
33 def __unicode__(self):
34 return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
37 def make_patch(src, dst):
38 if isinstance(src, unicode):
39 src = src.encode('utf-8')
40 if isinstance(dst, unicode):
41 dst = dst.encode('utf-8')
42 return pickle.dumps(mdiff.textdiff(src, dst))
44 def materialize(self):
45 changes = Change.objects.exclude(parent=None).filter(
47 created_at__lte=self.created_at).order_by('created_at')
49 for change in changes:
50 text = change.apply_to(text)
53 def make_child(self, patch, author, description):
54 return self.children.create(patch=patch,
55 tree=self.tree, author=author,
56 description=description)
58 def make_merge_child(self, patch, author, description):
59 return self.merge_children.create(patch=patch,
60 tree=self.tree, author=author,
61 description=description)
63 def apply_to(self, text):
64 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
66 def merge_with(self, other, author, description=u"Automatic merge."):
67 assert self.tree_id == other.tree_id # same tree
68 if other.parent_id == self.pk:
72 local = self.materialize()
73 base = other.merge_parent.materialize()
74 remote = other.apply_to(base)
76 merge = simplemerge.Merge3Text(base, local, remote)
77 result = ''.join(merge.merge_lines())
78 patch = self.make_patch(local, result)
79 return self.children.create(
80 patch=patch, merge_parent=other, tree=self.tree,
81 author=author, description=description)
84 class Document(models.Model):
88 creator = models.ForeignKey(User, null=True, blank=True)
89 head = models.ForeignKey(Change,
90 null=True, blank=True, default=None,
91 help_text=_("This document's current head."))
93 def __unicode__(self):
94 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
97 def get_absolute_url(self):
98 return ('dvcs.views.document_data', (), {
99 'document_id': self.id,
100 'version': self.head_id,
103 def materialize(self, version=None):
104 if self.head is None:
108 elif not isinstance(version, Change):
109 version = self.change_set.get(pk=version)
110 return version.materialize()
112 def commit(self, **kwargs):
113 if 'parent' not in kwargs:
116 parent = kwargs['parent']
117 if not isinstance(parent, Change):
118 parent = Change.objects.get(pk=kwargs['parent'])
120 if 'patch' not in kwargs:
121 if 'text' not in kwargs:
122 raise ValueError("You must provide either patch or target document.")
123 patch = Change.make_patch(self.materialize(version=parent), kwargs['text'])
126 raise ValueError("You can provide only text or patch - not both")
127 patch = kwargs['patch']
130 if parent != old_head:
131 change = parent.make_merge_child(patch, kwargs['author'], kwargs.get('description', ''))
132 # not Fast-Forward - perform a merge
133 self.head = old_head.merge_with(change, author=kwargs['author'])
135 self.head = parent.make_child(patch, kwargs['author'], kwargs.get('description', ''))
140 return self.changes.all()
143 def listener_initial_commit(sender, instance, created, **kwargs):
145 instance.head = Change.objects.create(
146 author=instance.creator,
147 patch=pickle.dumps(mdiff.textdiff('', '')),
151 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)