1 from datetime import datetime
3 from django.db import models
4 from django.contrib.auth.models import User
5 from django.utils.translation import ugettext_lazy as _
6 from mercurial import mdiff, simplemerge
9 class Change(models.Model):
11 Single document change related to previous change. The "parent"
12 argument points to the version against which this change has been
13 recorded. Initial text will have a null parent.
15 Data contains a pickled diff needed to reproduce the initial document.
17 author = models.ForeignKey(User, null=True, blank=True)
18 patch = models.TextField(blank=True)
19 tree = models.ForeignKey('Document')
20 revision = models.IntegerField(db_index=True)
22 parent = models.ForeignKey('self',
23 null=True, blank=True, default=None,
24 related_name="children")
26 merge_parent = models.ForeignKey('self',
27 null=True, blank=True, default=None,
28 related_name="merge_children")
30 description = models.TextField(blank=True, default='')
31 created_at = models.DateTimeField(editable=False, db_index=True,
35 ordering = ('created_at',)
36 unique_together = ['tree', 'revision']
38 def __unicode__(self):
39 return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
41 def save(self, *args, **kwargs):
43 take the next available revision number if none yet
45 if self.revision is None:
46 self.revision = self.tree.revision() + 1
47 return super(Change, self).save(*args, **kwargs)
50 def make_patch(src, dst):
51 if isinstance(src, unicode):
52 src = src.encode('utf-8')
53 if isinstance(dst, unicode):
54 dst = dst.encode('utf-8')
55 return pickle.dumps(mdiff.textdiff(src, dst))
57 def materialize(self):
58 # special care for merged nodes
59 if self.parent is None and self.merge_parent is not None:
60 return self.apply_to(self.merge_parent.materialize())
62 changes = Change.objects.exclude(parent=None).filter(
64 revision__lte=self.revision).order_by('revision')
66 for change in changes:
67 text = change.apply_to(text)
70 def make_child(self, patch, author, description):
71 return self.children.create(patch=patch,
72 tree=self.tree, author=author,
73 description=description)
75 def make_merge_child(self, patch, author, description):
76 return self.merge_children.create(patch=patch,
77 tree=self.tree, author=author,
78 description=description)
80 def apply_to(self, text):
81 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
83 def merge_with(self, other, author, description=u"Automatic merge."):
84 assert self.tree_id == other.tree_id # same tree
85 if other.parent_id == self.pk:
89 local = self.materialize()
90 base = other.merge_parent.materialize()
91 remote = other.apply_to(base)
93 merge = simplemerge.Merge3Text(base, local, remote)
94 result = ''.join(merge.merge_lines())
95 patch = self.make_patch(local, result)
96 return self.children.create(
97 patch=patch, merge_parent=other, tree=self.tree,
98 author=author, description=description)
100 def revert(self, **kwargs):
101 """ commit this version of a doc as new head """
102 self.tree.commit(text=self.materialize(), **kwargs)
105 class Document(models.Model):
109 creator = models.ForeignKey(User, null=True, blank=True)
110 head = models.ForeignKey(Change,
111 null=True, blank=True, default=None,
112 help_text=_("This document's current head."))
114 def __unicode__(self):
115 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
118 def get_absolute_url(self):
119 return ('dvcs.views.document_data', (), {
120 'document_id': self.id,
121 'version': self.head_id,
124 def materialize(self, change=None):
125 if self.head is None:
129 elif not isinstance(change, Change):
130 change = self.change_set.get(pk=change)
131 return change.materialize()
133 def commit(self, **kwargs):
134 if 'parent' not in kwargs:
137 parent = kwargs['parent']
138 if not isinstance(parent, Change):
139 parent = Change.objects.get(pk=kwargs['parent'])
141 if 'patch' not in kwargs:
142 if 'text' not in kwargs:
143 raise ValueError("You must provide either patch or target document.")
144 patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
147 raise ValueError("You can provide only text or patch - not both")
148 patch = kwargs['patch']
150 author = kwargs.get('author', None)
153 if parent != old_head:
154 change = parent.make_merge_child(patch, author, kwargs.get('description', ''))
155 # not Fast-Forward - perform a merge
156 self.head = old_head.merge_with(change, author=author)
158 self.head = parent.make_child(patch, author, kwargs.get('description', ''))
164 return self.change_set.filter(revision__gt=-1)
167 rev = self.change_set.aggregate(
168 models.Max('revision'))['revision__max']
169 return rev if rev is not None else -1
171 def at_revision(self, rev):
173 return self.change_set.get(revision=rev)
178 def listener_initial_commit(sender, instance, created, **kwargs):
179 # run for Document and its subclasses
180 if not isinstance(instance, Document):
183 instance.head = Change.objects.create(
185 author=instance.creator,
186 patch=Change.make_patch('', ''),
190 models.signals.post_save.connect(Document.listener_initial_commit)