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')
18 revision = models.IntegerField(db_index=True)
20 parent = models.ForeignKey('self',
21 null=True, blank=True, default=None,
22 related_name="children")
24 merge_parent = models.ForeignKey('self',
25 null=True, blank=True, default=None,
26 related_name="merge_children")
28 description = models.TextField(blank=True, default='')
29 created_at = models.DateTimeField(auto_now_add=True, db_index=True)
32 ordering = ('created_at',)
33 unique_together = ['tree', 'revision']
35 def __unicode__(self):
36 return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
38 def save(self, *args, **kwargs):
40 take the next available revision number if none yet
42 if self.revision is None:
43 self.revision = self.tree.revision() + 1
44 return super(Change, self).save(*args, **kwargs)
47 def make_patch(src, dst):
48 if isinstance(src, unicode):
49 src = src.encode('utf-8')
50 if isinstance(dst, unicode):
51 dst = dst.encode('utf-8')
52 return pickle.dumps(mdiff.textdiff(src, dst))
54 def materialize(self):
55 # special care for merged nodes
56 if self.parent is None and self.merge_parent is not None:
57 return self.apply_to(self.merge_parent.materialize())
59 changes = Change.objects.exclude(parent=None).filter(
61 revision__lte=self.revision).order_by('revision')
63 for change in changes:
64 text = change.apply_to(text)
67 def make_child(self, patch, author, description):
68 return self.children.create(patch=patch,
69 tree=self.tree, author=author,
70 description=description)
72 def make_merge_child(self, patch, author, description):
73 return self.merge_children.create(patch=patch,
74 tree=self.tree, author=author,
75 description=description)
77 def apply_to(self, text):
78 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
80 def merge_with(self, other, author, description=u"Automatic merge."):
81 assert self.tree_id == other.tree_id # same tree
82 if other.parent_id == self.pk:
86 local = self.materialize()
87 base = other.merge_parent.materialize()
88 remote = other.apply_to(base)
90 merge = simplemerge.Merge3Text(base, local, remote)
91 result = ''.join(merge.merge_lines())
92 patch = self.make_patch(local, result)
93 return self.children.create(
94 patch=patch, merge_parent=other, tree=self.tree,
95 author=author, description=description)
97 def revert(self, **kwargs):
98 """ commit this version of a doc as new head """
99 self.tree.commit(text=self.materialize(), **kwargs)
102 class Document(models.Model):
106 creator = models.ForeignKey(User, null=True, blank=True)
107 head = models.ForeignKey(Change,
108 null=True, blank=True, default=None,
109 help_text=_("This document's current head."))
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']
147 author = kwargs.get('author', None)
150 if parent != old_head:
151 change = parent.make_merge_child(patch, author, kwargs.get('description', ''))
152 # not Fast-Forward - perform a merge
153 self.head = old_head.merge_with(change, author=author)
155 self.head = parent.make_child(patch, author, kwargs.get('description', ''))
161 return self.change_set.filter(revision__gt=0)
164 rev = self.change_set.aggregate(
165 models.Max('revision'))['revision__max']
166 return rev if rev is not None else 0
168 def at_revision(self, rev):
170 return self.change_set.get(revision=rev)
175 def listener_initial_commit(sender, instance, created, **kwargs):
177 instance.head = Change.objects.create(
179 author=instance.creator,
180 patch=Change.make_patch('', ''),
184 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)