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_name = models.CharField(max_length=128, null=True, blank=True)
64 author_email = models.CharField(max_length=128, null=True, blank=True)
65 patch = models.TextField(blank=True)
66 tree = models.ForeignKey('Document')
67 revision = models.IntegerField(db_index=True)
69 parent = models.ForeignKey('self',
70 null=True, blank=True, default=None,
71 related_name="children")
73 merge_parent = models.ForeignKey('self',
74 null=True, blank=True, default=None,
75 related_name="merge_children")
77 description = models.TextField(blank=True, default='')
78 created_at = models.DateTimeField(editable=False, db_index=True,
80 publishable = models.BooleanField(default=False)
82 tags = models.ManyToManyField(Tag)
85 ordering = ('created_at',)
86 unique_together = ['tree', 'revision']
88 def __unicode__(self):
89 return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
93 return "%s %s <%s>" % (
94 self.author.first_name,
95 self.author.last_name,
104 def save(self, *args, **kwargs):
106 take the next available revision number if none yet
108 if self.revision is None:
109 self.revision = self.tree.revision() + 1
110 return super(Change, self).save(*args, **kwargs)
113 def make_patch(src, dst):
114 if isinstance(src, unicode):
115 src = src.encode('utf-8')
116 if isinstance(dst, unicode):
117 dst = dst.encode('utf-8')
118 return pickle.dumps(mdiff.textdiff(src, dst))
120 def materialize(self):
121 # special care for merged nodes
122 if self.parent is None and self.merge_parent is not None:
123 return self.apply_to(self.merge_parent.materialize())
125 changes = Change.objects.exclude(parent=None).filter(
127 revision__lte=self.revision).order_by('revision')
129 for change in changes:
130 text = change.apply_to(text)
133 def make_child(self, patch, description, author=None,
134 author_name=None, author_email=None, tags=None):
135 ch = self.children.create(patch=patch,
136 tree=self.tree, author=author,
137 author_name=author_name,
138 author_email=author_email,
139 description=description)
144 def make_merge_child(self, patch, description, author=None,
145 author_name=None, author_email=None, tags=None):
146 ch = self.merge_children.create(patch=patch,
147 tree=self.tree, author=author,
148 author_name=author_name,
149 author_email=author_email,
150 description=description,
156 def apply_to(self, text):
157 return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
159 def merge_with(self, other, author=None,
160 author_name=None, author_email=None,
161 description=u"Automatic merge."):
162 assert self.tree_id == other.tree_id # same tree
163 if other.parent_id == self.pk:
167 local = self.materialize()
168 base = other.merge_parent.materialize()
169 remote = other.apply_to(base)
171 merge = simplemerge.Merge3Text(base, local, remote)
172 result = ''.join(merge.merge_lines())
173 patch = self.make_patch(local, result)
174 return self.children.create(
175 patch=patch, merge_parent=other, tree=self.tree,
177 author_name=author_name,
178 author_email=author_email,
179 description=description)
181 def revert(self, **kwargs):
182 """ commit this version of a doc as new head """
183 self.tree.commit(text=self.materialize(), **kwargs)
186 class Document(models.Model):
190 creator = models.ForeignKey(User, null=True, blank=True, editable=False,
191 related_name="created_documents")
192 head = models.ForeignKey(Change,
193 null=True, blank=True, default=None,
194 help_text=_("This document's current head."),
197 user = models.ForeignKey(User, null=True, blank=True)
198 stage = models.ForeignKey(Tag, null=True, blank=True)
200 def __unicode__(self):
201 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
204 def get_absolute_url(self):
205 return ('dvcs.views.document_data', (), {
206 'document_id': self.id,
207 'version': self.head_id,
210 def materialize(self, change=None):
211 if self.head is None:
215 elif not isinstance(change, Change):
216 change = self.change_set.get(pk=change)
217 return change.materialize()
219 def commit(self, **kwargs):
220 if 'parent' not in kwargs:
223 parent = kwargs['parent']
224 if not isinstance(parent, Change):
225 parent = Change.objects.get(pk=kwargs['parent'])
227 if 'patch' not in kwargs:
228 if 'text' not in kwargs:
229 raise ValueError("You must provide either patch or target document.")
230 patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
233 raise ValueError("You can provide only text or patch - not both")
234 patch = kwargs['patch']
236 author = kwargs.get('author', None)
237 author_name = kwargs.get('author_name', None)
238 author_email = kwargs.get('author_email', None)
239 tags = kwargs.get('tags', [])
241 # set stage to next tag after the commited one
242 self.stage = max(tags, key=lambda t: t.ordering).next()
245 if parent != old_head:
246 change = parent.make_merge_child(patch, author=author,
247 author_name=author_name,
248 author_email=author_email,
249 description=kwargs.get('description', ''),
251 # not Fast-Forward - perform a merge
252 self.head = old_head.merge_with(change, author=author,
253 author_name=author_name,
254 author_email=author_email)
256 self.head = parent.make_child(patch, author=author,
257 author_name=author_name,
258 author_email=author_email,
259 description=kwargs.get('description', ''),
266 return self.change_set.filter(revision__gt=-1)
269 rev = self.change_set.aggregate(
270 models.Max('revision'))['revision__max']
271 return rev if rev is not None else -1
273 def at_revision(self, rev):
275 return self.change_set.get(revision=rev)
279 def publishable(self):
280 changes = self.change_set.filter(publishable=True).order_by('-created_at')[:1]
287 def listener_initial_commit(sender, instance, created, **kwargs):
288 # run for Document and its subclasses
289 if not isinstance(instance, Document):
292 instance.head = Change.objects.create(
294 author=instance.creator,
295 patch=Change.make_patch('', ''),
299 models.signals.post_save.connect(Document.listener_initial_commit)