47e7c26d51f6588bf7d44679e7e2dbf6dc5b4f81
[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)
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         return pickle.dumps(mdiff.textdiff(src, dst))
39
40     def materialize(self):
41         changes = Change.objects.exclude(parent=None).filter(
42                         tree=self.tree,
43                         created_at__lte=self.created_at).order_by('created_at')
44         text = u''
45         for change in changes:
46             text = change.apply_to(text)
47         return text
48
49     def make_child(self, patch, author, description):
50         return self.children.create(patch=patch,
51                         tree=self.tree, author=author,
52                         description=description)
53
54     def make_merge_child(self, patch, author, description):
55         return self.merge_children.create(patch=patch,
56                         tree=self.tree, author=author,
57                         description=description)
58
59     def apply_to(self, text):
60         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
61
62     def merge_with(self, other, author, description=u"Automatic merge."):
63         assert self.tree_id == other.tree_id  # same tree
64         if other.parent_id == self.pk:
65             # immediate child 
66             return other
67
68         local = self.materialize()
69         base = other.merge_parent.materialize()
70         remote = other.apply_to(base)
71
72         merge = simplemerge.Merge3Text(base, local, remote)
73         result = ''.join(merge.merge_lines())
74         patch = self.make_patch(local, result)
75         return self.children.create(
76                     patch=patch, merge_parent=other, tree=self.tree,
77                     author=author, description=description)
78
79
80 class Document(models.Model):
81     """
82         File in repository.        
83     """
84     creator = models.ForeignKey(User)
85     head = models.ForeignKey(Change,
86                     null=True, blank=True, default=None,
87                     help_text=_("This document's current head."))
88
89     # Some meta-data
90     name = models.CharField(max_length=200,
91                 help_text=_("Name for this file to display."))
92
93     def __unicode__(self):
94         return u"{0}, HEAD: {1}".format(self.name, self.head_id)
95
96     @models.permalink
97     def get_absolute_url(self):
98         return ('dvcs.views.document_data', (), {
99                         'document_id': self.id,
100                         'version': self.head_id,
101         })
102
103     def materialize(self, version=None):
104         if self.head is None:
105             return u''
106         if version is None:
107             version = self.head
108         elif not isinstance(version, Change):
109             version = self.change_set.get(pk=version)
110         return version.materialize()
111
112     def commit(self, **kwargs):
113         if 'parent' not in kwargs:
114             parent = self.head
115         else:
116             parent = kwargs['parent']
117             if not isinstance(parent, Change):
118                 parent = Change.objects.get(pk=kwargs['parent'])
119
120         if 'patch' not in kwargs:
121             if 'text' not in kwargs:
122                 raise ValueError("You must provide either patch or target document.")
123             patch = Change.make_patch(self.materialize(version=parent), kwargs['text'])
124         else:
125             if 'text' in kwargs:
126                 raise ValueError("You can provide only text or patch - not both")
127             patch = kwargs['patch']
128
129         old_head = self.head
130         if parent != old_head:
131             change = parent.make_merge_child(patch, kwargs['author'], kwargs.get('description', ''))
132             # not Fast-Forward - perform a merge
133             self.head = old_head.merge_with(change, author=kwargs['author'])
134         else:
135             self.head = parent.make_child(patch, kwargs['author'], kwargs.get('description', ''))
136         self.save()
137         return self.head
138
139     def history(self):
140         return self.changes.all()
141
142     @staticmethod
143     def listener_initial_commit(sender, instance, created, **kwargs):
144         if created:
145             instance.head = Change.objects.create(
146                     author=instance.creator,
147                     patch=pickle.dumps(mdiff.textdiff('', '')),
148                     tree=instance)
149             instance.save()
150
151 models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)