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
10 class Tag(models.Model):
12 a tag (e.g. document stage) which can be applied to a change
15 name = models.CharField(_('name'), max_length=64)
16 slug = models.SlugField(_('slug'), unique=True, max_length=64,
17 null=True, blank=True)
18 ordering = models.IntegerField(_('ordering'))
23 ordering = ['ordering']
25 def __unicode__(self):
30 if slug in cls._object_cache:
31 return cls._object_cache[slug]
33 obj = cls.objects.get(slug=slug)
34 cls._object_cache[slug] = obj
38 def listener_changed(sender, instance, **kwargs):
39 sender._object_cache = {}
43 Returns the next tag - stage to work on.
44 Returns None for the last stage.
47 return Tag.objects.filter(ordering__gt=self.ordering)[0]
51 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
54 class Change(models.Model):
56 Single document change related to previous change. The "parent"
57 argument points to the version against which this change has been
58 recorded. Initial text will have a null parent.
60 Data contains a pickled diff needed to reproduce the initial document.
62 author = models.ForeignKey(User, null=True, blank=True)
63 author_desc = models.CharField(max_length=128, null=True, blank=True)
64 patch = models.TextField(blank=True)
65 tree = models.ForeignKey('Document')
66 revision = models.IntegerField(db_index=True)
68 parent = models.ForeignKey('self',
69 null=True, blank=True, default=None,
70 related_name="children")
72 merge_parent = models.ForeignKey('self',
73 null=True, blank=True, default=None,
74 related_name="merge_children")
76 description = models.TextField(blank=True, default='')
77 created_at = models.DateTimeField(editable=False, db_index=True,
79 publishable = models.BooleanField(default=False)
81 tags = models.ManyToManyField(Tag)
84 ordering = ('created_at',)
85 unique_together = ['tree', 'revision']
87 def __unicode__(self):
88 return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
92 return "%s %s <%s>" % (
93 self.author.first_name,
94 self.author.last_name,
97 return self.author_desc
100 def save(self, *args, **kwargs):
102 take the next available revision number if none yet
104 if self.revision is None:
105 self.revision = self.tree.revision() + 1
106 return super(Change, self).save(*args, **kwargs)
109 def make_patch(src, dst):
110 if isinstance(src, unicode):
111 src = src.encode('utf-8')
112 if isinstance(dst, unicode):
113 dst = dst.encode('utf-8')
114 return pickle.dumps(mdiff.textdiff(src, dst))
116 def materialize(self):
117 # special care for merged nodes
118 if self.parent is None and self.merge_parent is not None:
119 return self.apply_to(self.merge_parent.materialize())
121 changes = Change.objects.exclude(parent=None).filter(
123 revision__lte=self.revision).order_by('revision')
125 for change in changes:
126 text = change.apply_to(text)
129 def make_child(self, patch, description, author=None,
130 author_desc=None, tags=None):
131 ch = self.children.create(patch=patch,
132 tree=self.tree, author=author,
133 author_desc=author_desc,
134 description=description)
139 def make_merge_child(self, patch, description, author=None,
140 author_desc=None, tags=None):
141 ch = self.merge_children.create(patch=patch,
142 tree=self.tree, author=author,
143 author_desc=author_desc,
144 description=description,
150 def apply_to(self, text):
151 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
153 def merge_with(self, other, author=None, author_desc=None,
154 description=u"Automatic merge."):
155 assert self.tree_id == other.tree_id # same tree
156 if other.parent_id == self.pk:
160 local = self.materialize()
161 base = other.merge_parent.materialize()
162 remote = other.apply_to(base)
164 merge = simplemerge.Merge3Text(base, local, remote)
165 result = ''.join(merge.merge_lines())
166 patch = self.make_patch(local, result)
167 return self.children.create(
168 patch=patch, merge_parent=other, tree=self.tree,
169 author=author, author_desc=author_desc,
170 description=description)
172 def revert(self, **kwargs):
173 """ commit this version of a doc as new head """
174 self.tree.commit(text=self.materialize(), **kwargs)
177 class Document(models.Model):
181 creator = models.ForeignKey(User, null=True, blank=True, editable=False,
182 related_name="created_documents")
183 head = models.ForeignKey(Change,
184 null=True, blank=True, default=None,
185 help_text=_("This document's current head."),
188 user = models.ForeignKey(User, null=True, blank=True)
189 stage = models.ForeignKey(Tag, null=True, blank=True)
191 def __unicode__(self):
192 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
195 def get_absolute_url(self):
196 return ('dvcs.views.document_data', (), {
197 'document_id': self.id,
198 'version': self.head_id,
201 def materialize(self, change=None):
202 if self.head is None:
206 elif not isinstance(change, Change):
207 change = self.change_set.get(pk=change)
208 return change.materialize()
210 def commit(self, **kwargs):
211 if 'parent' not in kwargs:
214 parent = kwargs['parent']
215 if not isinstance(parent, Change):
216 parent = Change.objects.get(pk=kwargs['parent'])
218 if 'patch' not in kwargs:
219 if 'text' not in kwargs:
220 raise ValueError("You must provide either patch or target document.")
221 patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
224 raise ValueError("You can provide only text or patch - not both")
225 patch = kwargs['patch']
227 author = kwargs.get('author', None)
228 author_desc = kwargs.get('author_desc', None)
229 tags = kwargs.get('tags', [])
231 # set stage to next tag after the commited one
232 self.stage = max(tags, key=lambda t: t.ordering).next()
235 if parent != old_head:
236 change = parent.make_merge_child(patch, author=author,
237 author_desc=author_desc,
238 description=kwargs.get('description', ''),
240 # not Fast-Forward - perform a merge
241 self.head = old_head.merge_with(change, author=author,
242 author_desc=author_desc)
244 self.head = parent.make_child(patch, author=author,
245 author_desc=author_desc,
246 description=kwargs.get('description', ''),
253 return self.change_set.filter(revision__gt=-1)
256 rev = self.change_set.aggregate(
257 models.Max('revision'))['revision__max']
258 return rev if rev is not None else -1
260 def at_revision(self, rev):
262 return self.change_set.get(revision=rev)
266 def publishable(self):
267 changes = self.change_set.filter(publishable=True).order_by('-created_at')[:1]
274 def listener_initial_commit(sender, instance, created, **kwargs):
275 # run for Document and its subclasses
276 if not isinstance(instance, Document):
279 instance.head = Change.objects.create(
281 author=instance.creator,
282 patch=Change.make_patch('', ''),
286 models.signals.post_save.connect(Document.listener_initial_commit)