1 from datetime import datetime
3 from django.core.files.base import ContentFile
4 from django.core.files.storage import FileSystemStorage
5 from django.db import models
6 from django.db.models.base import ModelBase
7 from django.contrib.auth.models import User
8 from django.utils.translation import ugettext_lazy as _
9 from mercurial import mdiff, simplemerge
11 from dvcs.fields import GzipFileSystemStorage
12 from dvcs.settings import REPO_PATH
15 class Tag(models.Model):
17 a tag (e.g. document stage) which can be applied to a change
20 name = models.CharField(_('name'), max_length=64)
21 slug = models.SlugField(_('slug'), unique=True, max_length=64,
22 null=True, blank=True)
23 ordering = models.IntegerField(_('ordering'))
29 ordering = ['ordering']
31 def __unicode__(self):
36 if slug in cls._object_cache:
37 return cls._object_cache[slug]
39 obj = cls.objects.get(slug=slug)
40 cls._object_cache[slug] = obj
44 def listener_changed(sender, instance, **kwargs):
45 sender._object_cache = {}
49 Returns the next tag - stage to work on.
50 Returns None for the last stage.
53 return Tag.objects.filter(ordering__gt=self.ordering)[0]
57 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
60 repo = GzipFileSystemStorage(location=REPO_PATH)
62 def data_upload_to(instance, filename):
63 return "%d/%d" % (instance.tree.pk, instance.pk)
65 class Change(models.Model):
67 Single document change related to previous change. The "parent"
68 argument points to the version against which this change has been
69 recorded. Initial text will have a null parent.
71 Data file contains a gzipped text of the document.
73 author = models.ForeignKey(User, null=True, blank=True)
74 author_name = models.CharField(max_length=128, null=True, blank=True)
75 author_email = models.CharField(max_length=128, null=True, blank=True)
76 data = models.FileField(upload_to=data_upload_to, storage=repo)
77 revision = models.IntegerField(db_index=True)
79 parent = models.ForeignKey('self',
80 null=True, blank=True, default=None,
81 related_name="children")
83 merge_parent = models.ForeignKey('self',
84 null=True, blank=True, default=None,
85 related_name="merge_children")
87 description = models.TextField(blank=True, default='')
88 created_at = models.DateTimeField(editable=False, db_index=True,
90 publishable = models.BooleanField(default=False)
94 ordering = ('created_at',)
95 unique_together = ['tree', 'revision']
97 def __unicode__(self):
98 return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
100 def author_str(self):
102 return "%s %s <%s>" % (
103 self.author.first_name,
104 self.author.last_name,
113 def save(self, *args, **kwargs):
115 take the next available revision number if none yet
117 if self.revision is None:
118 tree_rev = self.tree.revision()
122 self.revision = tree_rev + 1
123 return super(Change, self).save(*args, **kwargs)
125 def materialize(self):
126 f = self.data.storage.open(self.data)
129 return unicode(text, 'utf-8')
131 def merge_with(self, other, author=None,
132 author_name=None, author_email=None,
133 description=u"Automatic merge."):
134 """Performs an automatic merge after straying commits."""
135 assert self.tree_id == other.tree_id # same tree
136 if other.parent_id == self.pk:
137 # immediate child - fast forward
140 local = self.materialize().encode('utf-8')
141 base = other.parent.materialize().encode('utf-8')
142 remote = other.materialize().encode('utf-8')
144 merge = simplemerge.Merge3Text(base, local, remote)
145 result = ''.join(merge.merge_lines())
146 merge_node = self.children.create(
147 merge_parent=other, tree=self.tree,
149 author_name=author_name,
150 author_email=author_email,
151 description=description)
152 merge_node.data.save('', ContentFile(result))
155 def revert(self, **kwargs):
156 """ commit this version of a doc as new head """
157 self.tree.commit(text=self.materialize(), **kwargs)
160 def create_tag_model(model):
161 name = model.__name__ + 'Tag'
163 '__module__': model.__module__,
165 return type(name, (Tag,), attrs)
168 def create_change_model(model):
169 name = model.__name__ + 'Change'
172 '__module__': model.__module__,
173 'tree': models.ForeignKey(model, related_name='change_set'),
174 'tags': models.ManyToManyField(model.tag_model, related_name='change_set'),
176 return type(name, (Change,), attrs)
180 class DocumentMeta(ModelBase):
181 "Metaclass for Document models."
182 def __new__(cls, name, bases, attrs):
183 model = super(DocumentMeta, cls).__new__(cls, name, bases, attrs)
184 if not model._meta.abstract:
185 # create a real Tag object and `stage' fk
186 model.tag_model = create_tag_model(model)
187 models.ForeignKey(model.tag_model,
188 null=True, blank=True).contribute_to_class(model, 'stage')
190 # create real Change model and `head' fk
191 model.change_model = create_change_model(model)
192 models.ForeignKey(model.change_model,
193 null=True, blank=True, default=None,
194 help_text=_("This document's current head."),
195 editable=False).contribute_to_class(model, 'head')
201 class Document(models.Model):
205 __metaclass__ = DocumentMeta
207 creator = models.ForeignKey(User, null=True, blank=True, editable=False,
208 related_name="created_documents")
210 user = models.ForeignKey(User, null=True, blank=True)
215 def __unicode__(self):
216 return u"{0}, HEAD: {1}".format(self.id, self.head_id)
219 def get_absolute_url(self):
220 return ('dvcs.views.document_data', (), {
221 'document_id': self.id,
222 'version': self.head_id,
225 def materialize(self, change=None):
226 if self.head is None:
230 elif not isinstance(change, Change):
231 change = self.change_set.get(pk=change)
232 return change.materialize()
234 def commit(self, text, **kwargs):
235 if 'parent' not in kwargs:
238 parent = kwargs['parent']
239 if parent is not None and not isinstance(parent, Change):
240 parent = self.change_set.objects.get(pk=kwargs['parent'])
242 author = kwargs.get('author', None)
243 author_name = kwargs.get('author_name', None)
244 author_email = kwargs.get('author_email', None)
245 tags = kwargs.get('tags', [])
247 # set stage to next tag after the commited one
248 self.stage = max(tags, key=lambda t: t.ordering).next()
250 change = self.change_set.create(author=author,
251 author_name=author_name,
252 author_email=author_email,
253 description=kwargs.get('description', ''),
257 change.data.save('', ContentFile(text.encode('utf-8')))
261 # merge new change as new head
262 self.head = self.head.merge_with(change, author=author,
263 author_name=author_name,
264 author_email=author_email)
271 return self.change_set.filter(revision__gt=-1)
274 rev = self.change_set.aggregate(
275 models.Max('revision'))['revision__max']
278 def at_revision(self, rev):
279 """Returns a Change with given revision number."""
280 return self.change_set.get(revision=rev)
282 def publishable(self):
283 changes = self.change_set.filter(publishable=True).order_by('-created_at')[:1]