9c9d350b230c4a2e005dc503e39528c94bdc0aa0
[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     revision = models.IntegerField(db_index=True)
19
20     parent = models.ForeignKey('self',
21                         null=True, blank=True, default=None,
22                         related_name="children")
23
24     merge_parent = models.ForeignKey('self',
25                         null=True, blank=True, default=None,
26                         related_name="merge_children")
27
28     description = models.TextField(blank=True, default='')
29     created_at = models.DateTimeField(auto_now_add=True, db_index=True)
30
31     class Meta:
32         ordering = ('created_at',)
33         unique_together = ['tree', 'revision']
34
35     def __unicode__(self):
36         return u"Id: %r, Tree %r, Parent %r, Patch '''\n%s'''" % (self.id, self.tree_id, self.parent_id, self.patch)
37
38     def save(self, *args, **kwargs):
39         """
40             take the next available revision number if none yet
41         """
42         if self.revision is None:
43             self.revision = self.tree.revision() + 1
44         return super(Change, self).save(*args, **kwargs)
45
46     @staticmethod
47     def make_patch(src, dst):
48         if isinstance(src, unicode):
49             src = src.encode('utf-8')
50         if isinstance(dst, unicode):
51             dst = dst.encode('utf-8')
52         return pickle.dumps(mdiff.textdiff(src, dst))
53
54     def materialize(self):
55         # special care for merged nodes
56         if self.parent is None and self.merge_parent is not None:
57             return self.apply_to(self.merge_parent.materialize())
58
59         changes = Change.objects.exclude(parent=None).filter(
60                         tree=self.tree,
61                         revision__lte=self.revision).order_by('revision')
62         text = u''
63         for change in changes:
64             text = change.apply_to(text)
65         return text
66
67     def make_child(self, patch, author, description):
68         return self.children.create(patch=patch,
69                         tree=self.tree, author=author,
70                         description=description)
71
72     def make_merge_child(self, patch, author, description):
73         return self.merge_children.create(patch=patch,
74                         tree=self.tree, author=author,
75                         description=description)
76
77     def apply_to(self, text):
78         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
79
80     def merge_with(self, other, author, description=u"Automatic merge."):
81         assert self.tree_id == other.tree_id  # same tree
82         if other.parent_id == self.pk:
83             # immediate child 
84             return other
85
86         local = self.materialize()
87         base = other.merge_parent.materialize()
88         remote = other.apply_to(base)
89
90         merge = simplemerge.Merge3Text(base, local, remote)
91         result = ''.join(merge.merge_lines())
92         patch = self.make_patch(local, result)
93         return self.children.create(
94                     patch=patch, merge_parent=other, tree=self.tree,
95                     author=author, description=description)
96
97     def revert(self, **kwargs):
98         """ commit this version of a doc as new head """
99         self.tree.commit(text=self.materialize(), **kwargs)
100
101
102 class Document(models.Model):
103     """
104         File in repository.        
105     """
106     creator = models.ForeignKey(User, null=True, blank=True)
107     head = models.ForeignKey(Change,
108                     null=True, blank=True, default=None,
109                     help_text=_("This document's current head."))
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         author = kwargs.get('author', None)
148
149         old_head = self.head
150         if parent != old_head:
151             change = parent.make_merge_child(patch, author, kwargs.get('description', ''))
152             # not Fast-Forward - perform a merge
153             self.head = old_head.merge_with(change, author=author)
154         else:
155             self.head = parent.make_child(patch, author, kwargs.get('description', ''))
156
157         self.save()
158         return self.head
159
160     def history(self):
161         return self.change_set.filter(revision__gt=0)
162
163     def revision(self):
164         rev = self.change_set.aggregate(
165                 models.Max('revision'))['revision__max']
166         return rev if rev is not None else 0
167
168     def at_revision(self, rev):
169         if rev:
170             return self.change_set.get(revision=rev)
171         else:
172             return self.head
173
174     @staticmethod
175     def listener_initial_commit(sender, instance, created, **kwargs):
176         if created:
177             instance.head = Change.objects.create(
178                     revision=0,
179                     author=instance.creator,
180                     patch=Change.make_patch('', ''),
181                     tree=instance)
182             instance.save()
183
184 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)