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 # special care for merged nodes
46 if self.parent is None and self.merge_parent is not None:
47 return self.apply_to(self.merge_parent.materialize())
49 changes = Change.objects.filter(
50 ~models.Q(parent=None) | models.Q(merge_parent=None),
52 created_at__lte=self.created_at).order_by('created_at')
54 for change in changes:
55 text = change.apply_to(text)
58 def make_child(self, patch, author, description):
59 return self.children.create(patch=patch,
60 tree=self.tree, author=author,
61 description=description)
63 def make_merge_child(self, patch, author, description):
64 return self.merge_children.create(patch=patch,
65 tree=self.tree, author=author,
66 description=description)
68 def apply_to(self, text):
69 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
71 def merge_with(self, other, author, description=u"Automatic merge."):
72 assert self.tree_id == other.tree_id # same tree
73 if other.parent_id == self.pk:
77 local = self.materialize()
78 base = other.merge_parent.materialize()
79 remote = other.apply_to(base)
81 merge = simplemerge.Merge3Text(base, local, remote)
82 result = ''.join(merge.merge_lines())
83 patch = self.make_patch(local, result)
84 return self.children.create(
85 patch=patch, merge_parent=other, tree=self.tree,
86 author=author, description=description)
88 def revert(self, **kwargs):
89 """ commit this version of a doc as new head """
90 self.tree.commit(text=self.materialize(), **kwargs)
93 class Document(models.Model):
97 creator = models.ForeignKey(User, null=True, blank=True)
98 head = models.ForeignKey(Change,
99 null=True, blank=True, default=None,
100 help_text=_("This document's current head."))
103 def create(cls, text='', *args, **kwargs):
104 instance = cls(*args, **kwargs)
107 head.patch = Change.make_patch('', text)
111 def __unicode__(self):
112 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
115 def get_absolute_url(self):
116 return ('dvcs.views.document_data', (), {
117 'document_id': self.id,
118 'version': self.head_id,
121 def materialize(self, change=None):
122 if self.head is None:
126 elif not isinstance(change, Change):
127 change = self.change_set.get(pk=change)
128 return change.materialize()
130 def commit(self, **kwargs):
131 if 'parent' not in kwargs:
134 parent = kwargs['parent']
135 if not isinstance(parent, Change):
136 parent = Change.objects.get(pk=kwargs['parent'])
138 if 'patch' not in kwargs:
139 if 'text' not in kwargs:
140 raise ValueError("You must provide either patch or target document.")
141 patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
144 raise ValueError("You can provide only text or patch - not both")
145 patch = kwargs['patch']
148 if parent != old_head:
149 change = parent.make_merge_child(patch, kwargs['author'], kwargs.get('description', ''))
150 # not Fast-Forward - perform a merge
151 self.head = old_head.merge_with(change, author=kwargs['author'])
153 self.head = parent.make_child(patch, kwargs['author'], kwargs.get('description', ''))
159 return self.change_set.all()
162 return self.change_set.all().count()
164 def at_revision(self, rev):
166 return self.change_set.all()[rev-1]
171 def listener_initial_commit(sender, instance, created, **kwargs):
173 instance.head = Change.objects.create(
174 author=instance.creator,
175 patch=Change.make_patch('', ''),
179 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)