1c303873ee97d4d431f0479dc917d5bc473a85b7
[redakcja.git] / apps / dvcs / models.py
1 from django.db import models
2 from django.contrib.auth.models import User
3 from django.utils.translation import ugettext_lazy as _
4 from mercurial import mdiff, simplemerge
5 import pickle
6
7 class Change(models.Model):
8     """
9         Single document change related to previous change. The "parent"
10         argument points to the version against which this change has been 
11         recorded. Initial text will have a null parent.
12         
13         Data contains a pickled diff needed to reproduce the initial document.
14     """
15     author = models.ForeignKey(User, null=True, blank=True)
16     patch = models.TextField(blank=True)
17     tree = models.ForeignKey('Document')
18
19     parent = models.ForeignKey('self',
20                         null=True, blank=True, default=None,
21                         related_name="children")
22
23     merge_parent = models.ForeignKey('self',
24                         null=True, blank=True, default=None,
25                         related_name="merge_children")
26
27     description = models.TextField(blank=True, default='')
28     created_at = models.DateTimeField(auto_now_add=True)
29
30     class Meta:
31         ordering = ('created_at',)
32
33     def __unicode__(self):
34         return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
35
36     @staticmethod
37     def make_patch(src, dst):
38         if isinstance(src, unicode):
39             src = src.encode('utf-8')
40         if isinstance(dst, unicode):
41             dst = dst.encode('utf-8')
42         return pickle.dumps(mdiff.textdiff(src, dst))
43
44     def materialize(self):
45         # special care for merged nodes
46         if self.parent is None and self.merge_parent is not None:
47             return self.apply_to(self.merge_parent.materialize())
48
49         changes = Change.objects.filter(
50                         ~models.Q(parent=None) | models.Q(merge_parent=None),
51                         tree=self.tree,
52                         created_at__lte=self.created_at).order_by('created_at')
53         text = u''
54         for change in changes:
55             text = change.apply_to(text)
56         return text
57
58     def make_child(self, patch, author, description):
59         return self.children.create(patch=patch,
60                         tree=self.tree, author=author,
61                         description=description)
62
63     def make_merge_child(self, patch, author, description):
64         return self.merge_children.create(patch=patch,
65                         tree=self.tree, author=author,
66                         description=description)
67
68     def apply_to(self, text):
69         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
70
71     def merge_with(self, other, author, description=u"Automatic merge."):
72         assert self.tree_id == other.tree_id  # same tree
73         if other.parent_id == self.pk:
74             # immediate child 
75             return other
76
77         local = self.materialize()
78         base = other.merge_parent.materialize()
79         remote = other.apply_to(base)
80
81         merge = simplemerge.Merge3Text(base, local, remote)
82         result = ''.join(merge.merge_lines())
83         patch = self.make_patch(local, result)
84         return self.children.create(
85                     patch=patch, merge_parent=other, tree=self.tree,
86                     author=author, description=description)
87
88     def revert(self, **kwargs):
89         """ commit this version of a doc as new head """
90         self.tree.commit(text=self.materialize(), **kwargs)
91
92
93 class Document(models.Model):
94     """
95         File in repository.        
96     """
97     creator = models.ForeignKey(User, null=True, blank=True)
98     head = models.ForeignKey(Change,
99                     null=True, blank=True, default=None,
100                     help_text=_("This document's current head."))
101
102     @classmethod
103     def create(cls, text='', *args, **kwargs):
104         instance = cls(*args, **kwargs)
105         instance.save()
106         head = instance.head
107         head.patch = Change.make_patch('', text)
108         head.save()
109         return instance
110
111     def __unicode__(self):
112         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
113
114     @models.permalink
115     def get_absolute_url(self):
116         return ('dvcs.views.document_data', (), {
117                         'document_id': self.id,
118                         'version': self.head_id,
119         })
120
121     def materialize(self, change=None):
122         if self.head is None:
123             return u''
124         if change is None:
125             change = self.head
126         elif not isinstance(change, Change):
127             change = self.change_set.get(pk=change)
128         return change.materialize()
129
130     def commit(self, **kwargs):
131         if 'parent' not in kwargs:
132             parent = self.head
133         else:
134             parent = kwargs['parent']
135             if not isinstance(parent, Change):
136                 parent = Change.objects.get(pk=kwargs['parent'])
137
138         if 'patch' not in kwargs:
139             if 'text' not in kwargs:
140                 raise ValueError("You must provide either patch or target document.")
141             patch = Change.make_patch(self.materialize(change=parent), kwargs['text'])
142         else:
143             if 'text' in kwargs:
144                 raise ValueError("You can provide only text or patch - not both")
145             patch = kwargs['patch']
146
147         old_head = self.head
148         if parent != old_head:
149             change = parent.make_merge_child(patch, kwargs['author'], kwargs.get('description', ''))
150             # not Fast-Forward - perform a merge
151             self.head = old_head.merge_with(change, author=kwargs['author'])
152         else:
153             self.head = parent.make_child(patch, kwargs['author'], kwargs.get('description', ''))
154
155         self.save()
156         return self.head
157
158     def history(self):
159         return self.change_set.all()
160
161     def revision(self):
162         return self.change_set.all().count()
163
164     def at_revision(self, rev):
165         if rev:
166             return self.change_set.all()[rev-1]
167         else:
168             return self.head
169
170     @staticmethod
171     def listener_initial_commit(sender, instance, created, **kwargs):
172         if created:
173             instance.head = Change.objects.create(
174                     author=instance.creator,
175                     patch=Change.make_patch('', ''),
176                     tree=instance)
177             instance.save()
178
179 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)