5ce00c0fec2623dec1173d2f5c8527b2f20a4eb7
[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 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
42
43
44 class Change(models.Model):
45     """
46         Single document change related to previous change. The "parent"
47         argument points to the version against which this change has been 
48         recorded. Initial text will have a null parent.
49         
50         Data contains a pickled diff needed to reproduce the initial document.
51     """
52     author = models.ForeignKey(User, null=True, blank=True)
53     author_desc = models.CharField(max_length=128, null=True, blank=True)
54     patch = models.TextField(blank=True)
55     tree = models.ForeignKey('Document')
56     revision = models.IntegerField(db_index=True)
57
58     parent = models.ForeignKey('self',
59                         null=True, blank=True, default=None,
60                         related_name="children")
61
62     merge_parent = models.ForeignKey('self',
63                         null=True, blank=True, default=None,
64                         related_name="merge_children")
65
66     description = models.TextField(blank=True, default='')
67     created_at = models.DateTimeField(editable=False, db_index=True, 
68                         default=datetime.now)
69
70     tags = models.ManyToManyField(Tag)
71
72     class Meta:
73         ordering = ('created_at',)
74         unique_together = ['tree', 'revision']
75
76     def __unicode__(self):
77         return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
78
79     def author_str(self):
80         if self.author:
81             return "%s %s <%s>" % (
82                 self.author.first_name,
83                 self.author.last_name, 
84                 self.author.email)
85         else:
86             return self.author_desc
87
88
89     def save(self, *args, **kwargs):
90         """
91             take the next available revision number if none yet
92         """
93         if self.revision is None:
94             self.revision = self.tree.revision() + 1
95         return super(Change, self).save(*args, **kwargs)
96
97     @staticmethod
98     def make_patch(src, dst):
99         if isinstance(src, unicode):
100             src = src.encode('utf-8')
101         if isinstance(dst, unicode):
102             dst = dst.encode('utf-8')
103         return pickle.dumps(mdiff.textdiff(src, dst))
104
105     def materialize(self):
106         # special care for merged nodes
107         if self.parent is None and self.merge_parent is not None:
108             return self.apply_to(self.merge_parent.materialize())
109
110         changes = Change.objects.exclude(parent=None).filter(
111                         tree=self.tree,
112                         revision__lte=self.revision).order_by('revision')
113         text = u''
114         for change in changes:
115             text = change.apply_to(text)
116         return text
117
118     def make_child(self, patch, description, author=None,
119             author_desc=None, tags=None):
120         ch = self.children.create(patch=patch,
121                         tree=self.tree, author=author,
122                         author_desc=author_desc,
123                         description=description)
124         if tags is not None:
125             ch.tags = tags
126         return ch
127
128     def make_merge_child(self, patch, description, author=None, 
129             author_desc=None, tags=None):
130         ch = self.merge_children.create(patch=patch,
131                         tree=self.tree, author=author,
132                         author_desc=author_desc,
133                         description=description,
134                         tags=tags)
135         if tags is not None:
136             ch.tags = tags
137         return ch
138
139     def apply_to(self, text):
140         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
141
142     def merge_with(self, other, author=None, author_desc=None,
143             description=u"Automatic merge."):
144         assert self.tree_id == other.tree_id  # same tree
145         if other.parent_id == self.pk:
146             # immediate child 
147             return other
148
149         local = self.materialize()
150         base = other.merge_parent.materialize()
151         remote = other.apply_to(base)
152
153         merge = simplemerge.Merge3Text(base, local, remote)
154         result = ''.join(merge.merge_lines())
155         patch = self.make_patch(local, result)
156         return self.children.create(
157                     patch=patch, merge_parent=other, tree=self.tree,
158                     author=author, author_desc=author_desc,
159                     description=description)
160
161     def revert(self, **kwargs):
162         """ commit this version of a doc as new head """
163         self.tree.commit(text=self.materialize(), **kwargs)
164
165
166 class Document(models.Model):
167     """
168         File in repository.        
169     """
170     creator = models.ForeignKey(User, null=True, blank=True, editable=False)
171     head = models.ForeignKey(Change,
172                     null=True, blank=True, default=None,
173                     help_text=_("This document's current head."),
174                     editable=False)
175
176     def __unicode__(self):
177         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
178
179     @models.permalink
180     def get_absolute_url(self):
181         return ('dvcs.views.document_data', (), {
182                         'document_id': self.id,
183                         'version': self.head_id,
184         })
185
186     def materialize(self, change=None):
187         if self.head is None:
188             return u''
189         if change is None:
190             change = self.head
191         elif not isinstance(change, Change):
192             change = self.change_set.get(pk=change)
193         return change.materialize()
194
195     def commit(self, **kwargs):
196         if 'parent' not in kwargs:
197             parent = self.head
198         else:
199             parent = kwargs['parent']
200             if not isinstance(parent, Change):
201                 parent = Change.objects.get(pk=kwargs['parent'])
202
203         if 'patch' not in kwargs:
204             if 'text' not in kwargs:
205                 raise ValueError("You must provide either patch or target document.")
206             patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
207         else:
208             if 'text' in kwargs:
209                 raise ValueError("You can provide only text or patch - not both")
210             patch = kwargs['patch']
211
212         author = kwargs.get('author', None)
213         author_desc = kwargs.get('author_desc', None)
214         tags = kwargs.get('tags', [])
215
216         old_head = self.head
217         if parent != old_head:
218             change = parent.make_merge_child(patch, author=author, 
219                     author_desc=author_desc,
220                     description=kwargs.get('description', ''),
221                     tags=tags)
222             # not Fast-Forward - perform a merge
223             self.head = old_head.merge_with(change, author=author,
224                     author_desc=author_desc)
225         else:
226             self.head = parent.make_child(patch, author=author, 
227                     author_desc=author_desc, 
228                     description=kwargs.get('description', ''),
229                     tags=tags)
230
231         self.save()
232         return self.head
233
234     def history(self):
235         return self.change_set.filter(revision__gt=-1)
236
237     def revision(self):
238         rev = self.change_set.aggregate(
239                 models.Max('revision'))['revision__max']
240         return rev if rev is not None else -1
241
242     def at_revision(self, rev):
243         if rev:
244             return self.change_set.get(revision=rev)
245         else:
246             return self.head
247
248     def last_tagged(self, tag):
249         changes = tag.change_set.filter(tree=self).order_by('-created_at')[:1]
250         if changes.count():
251             return changes[0]
252         else:
253             return None
254
255     @staticmethod
256     def listener_initial_commit(sender, instance, created, **kwargs):
257         # run for Document and its subclasses
258         if not isinstance(instance, Document):
259             return
260         if created:
261             instance.head = Change.objects.create(
262                     revision=-1,
263                     author=instance.creator,
264                     patch=Change.make_patch('', ''),
265                     tree=instance)
266             instance.save()
267
268 models.signals.post_save.connect(Document.listener_initial_commit)