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