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