18fe18fef03670b9f880708f816757558a4d6ee7
[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         changes = Change.objects.exclude(parent=None).filter(
46                         tree=self.tree,
47                         created_at__lte=self.created_at).order_by('created_at')
48         text = u''
49         for change in changes:
50             text = change.apply_to(text)
51         return text
52
53     def make_child(self, patch, author, description):
54         return self.children.create(patch=patch,
55                         tree=self.tree, author=author,
56                         description=description)
57
58     def make_merge_child(self, patch, author, description):
59         return self.merge_children.create(patch=patch,
60                         tree=self.tree, author=author,
61                         description=description)
62
63     def apply_to(self, text):
64         return mdiff.patch(text, pickle.loads(self.patch.encode('ascii')))
65
66     def merge_with(self, other, author, description=u"Automatic merge."):
67         assert self.tree_id == other.tree_id  # same tree
68         if other.parent_id == self.pk:
69             # immediate child 
70             return other
71
72         local = self.materialize()
73         base = other.merge_parent.materialize()
74         remote = other.apply_to(base)
75
76         merge = simplemerge.Merge3Text(base, local, remote)
77         result = ''.join(merge.merge_lines())
78         patch = self.make_patch(local, result)
79         return self.children.create(
80                     patch=patch, merge_parent=other, tree=self.tree,
81                     author=author, description=description)
82
83
84 class Document(models.Model):
85     """
86         File in repository.        
87     """
88     creator = models.ForeignKey(User, null=True, blank=True)
89     head = models.ForeignKey(Change,
90                     null=True, blank=True, default=None,
91                     help_text=_("This document's current head."))
92
93     def __unicode__(self):
94         return u"{0}, HEAD: {1}".format(self.id, 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)