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