django 1.3, comments on books, last activity log, some minor changes
[redakcja.git] / apps / dvcs / models.py
1 from datetime import datetime
2
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
7 import pickle
8
9
10 class Tag(models.Model):
11     """
12         a tag (e.g. document stage) which can be applied to a change
13     """
14
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'))
19
20     _object_cache = {}
21
22     class Meta:
23         ordering = ['ordering']
24
25     def __unicode__(self):
26         return self.name
27
28     @classmethod
29     def get(cls, slug):
30         if slug in cls._object_cache:
31             return cls._object_cache[slug]
32         else:
33             obj = cls.objects.get(slug=slug)
34             cls._object_cache[slug] = obj
35             return obj
36
37     @staticmethod
38     def listener_changed(sender, instance, **kwargs):
39         sender._object_cache = {}
40
41     def next(self):
42         """
43             Returns the next tag - stage to work on.
44             Returns None for the last stage.
45         """
46         try:
47             return Tag.objects.filter(ordering__gt=self.ordering)[0]
48         except IndexError:
49             return None
50
51 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
52
53
54 class Change(models.Model):
55     """
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.
59         
60         Data contains a pickled diff needed to reproduce the initial document.
61     """
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)
68
69     parent = models.ForeignKey('self',
70                         null=True, blank=True, default=None,
71                         related_name="children")
72
73     merge_parent = models.ForeignKey('self',
74                         null=True, blank=True, default=None,
75                         related_name="merge_children")
76
77     description = models.TextField(blank=True, default='')
78     created_at = models.DateTimeField(editable=False, db_index=True, 
79                         default=datetime.now)
80     publishable = models.BooleanField(default=False)
81
82     tags = models.ManyToManyField(Tag)
83
84     class Meta:
85         ordering = ('created_at',)
86         unique_together = ['tree', 'revision']
87
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)
90
91     def author_str(self):
92         if self.author:
93             return "%s %s <%s>" % (
94                 self.author.first_name,
95                 self.author.last_name, 
96                 self.author.email)
97         else:
98             return "%s <%s>" % (
99                 self.author_name,
100                 self.author_email
101                 )
102
103
104     def save(self, *args, **kwargs):
105         """
106             take the next available revision number if none yet
107         """
108         if self.revision is None:
109             self.revision = self.tree.revision() + 1
110         return super(Change, self).save(*args, **kwargs)
111
112     @staticmethod
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))
119
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())
124
125         changes = Change.objects.exclude(parent=None).filter(
126                         tree=self.tree,
127                         revision__lte=self.revision).order_by('revision')
128         text = u''
129         for change in changes:
130             text = change.apply_to(text)
131         return text
132
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)
140         if tags is not None:
141             ch.tags = tags
142         return ch
143
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,
151                         tags=tags)
152         if tags is not None:
153             ch.tags = tags
154         return ch
155
156     def apply_to(self, text):
157         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
158
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:
164             # immediate child 
165             return other
166
167         local = self.materialize()
168         base = other.merge_parent.materialize()
169         remote = other.apply_to(base)
170
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,
176                     author=author,
177                     author_name=author_name,
178                     author_email=author_email,
179                     description=description)
180
181     def revert(self, **kwargs):
182         """ commit this version of a doc as new head """
183         self.tree.commit(text=self.materialize(), **kwargs)
184
185
186 class Document(models.Model):
187     """
188         File in repository.        
189     """
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."),
195                     editable=False)
196
197     user = models.ForeignKey(User, null=True, blank=True)
198     stage = models.ForeignKey(Tag, null=True, blank=True)
199
200     def __unicode__(self):
201         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
202
203     @models.permalink
204     def get_absolute_url(self):
205         return ('dvcs.views.document_data', (), {
206                         'document_id': self.id,
207                         'version': self.head_id,
208         })
209
210     def materialize(self, change=None):
211         if self.head is None:
212             return u''
213         if change is None:
214             change = self.head
215         elif not isinstance(change, Change):
216             change = self.change_set.get(pk=change)
217         return change.materialize()
218
219     def commit(self, **kwargs):
220         if 'parent' not in kwargs:
221             parent = self.head
222         else:
223             parent = kwargs['parent']
224             if not isinstance(parent, Change):
225                 parent = Change.objects.get(pk=kwargs['parent'])
226
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'])
231         else:
232             if 'text' in kwargs:
233                 raise ValueError("You can provide only text or patch - not both")
234             patch = kwargs['patch']
235
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', [])
240         if tags:
241             # set stage to next tag after the commited one
242             self.stage = max(tags, key=lambda t: t.ordering).next()
243
244         old_head = self.head
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', ''),
250                     tags=tags)
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)
255         else:
256             self.head = parent.make_child(patch, author=author, 
257                     author_name=author_name,
258                     author_email=author_email,
259                     description=kwargs.get('description', ''),
260                     tags=tags)
261
262         self.save()
263         return self.head
264
265     def history(self):
266         return self.change_set.filter(revision__gt=-1)
267
268     def revision(self):
269         rev = self.change_set.aggregate(
270                 models.Max('revision'))['revision__max']
271         return rev if rev is not None else -1
272
273     def at_revision(self, rev):
274         if rev is not None:
275             return self.change_set.get(revision=rev)
276         else:
277             return self.head
278
279     def publishable(self):
280         changes = self.change_set.filter(publishable=True).order_by('-created_at')[:1]
281         if changes.count():
282             return changes[0]
283         else:
284             return None
285
286     @staticmethod
287     def listener_initial_commit(sender, instance, created, **kwargs):
288         # run for Document and its subclasses
289         if not isinstance(instance, Document):
290             return
291         if created:
292             instance.head = Change.objects.create(
293                     revision=-1,
294                     author=instance.creator,
295                     patch=Change.make_patch('', ''),
296                     tree=instance)
297             instance.save()
298
299 models.signals.post_save.connect(Document.listener_initial_commit)