Fix
[redakcja.git] / lib / wlrepo / mercurial_backend / document.py
1 # -*- encoding: utf-8 -*-
2
3 __author__ = "Ɓukasz Rekucki"
4 __date__ = "$2009-09-25 09:35:06$"
5 __doc__ = "Module documentation."
6
7 import wlrepo
8 import mercurial.error
9
10 class MercurialDocument(wlrepo.Document):
11
12     def data(self, entry):
13         path = self._library._sanitize_string(self.id + u'.' + entry)
14         try:
15             return self._library._filectx(path, \
16                 self._revision.hgrev()).data().decode('utf-8')
17         except mercurial.error.LookupError, e:
18             fl = [x.decode('utf-8') for x in self._revision._changectx]            
19             raise wlrepo.EntryNotFound(self._revision, path.decode('utf-8'), fl)
20
21     def quickwrite(self, entry, data, msg, user=None):
22         user = user or self.owner
23
24         if isinstance(data, unicode):
25             data = data.encode('utf-8')
26             
27         user = self._library._sanitize_string(user)
28         msg = self._library._sanitize_string(msg)
29         entry = self._library._sanitize_string(entry)
30
31         if user is None:
32             raise ValueError("Can't determine user.")
33         
34         def write(l, r):
35             f = l._fileopen(r(entry), "w+")
36             f.write(data)
37             f.close()
38             l._fileadd(r(entry))            
39
40         return self.invoke_and_commit(write, lambda d: (msg, \
41                 self._library._sanitize_string(self.owner)) )
42
43     def invoke_and_commit(self, ops, commit_info):
44         lock = self._library.lock()
45         try:            
46             self._library._checkout(self._revision.hgrev())
47
48             def entry_path(entry):
49                 return self._library._sanitize_string(self.id + u'.' + entry)
50             
51             ops(self._library, entry_path)
52             message, user = commit_info(self)
53
54             message = self._library._sanitize_string(message)
55             user = self._library._sanitize_string(user)
56
57             self._library._commit(message, user)
58             try:
59                 return self._library.document(docid=self.id, user=user)
60             except Exception, e:
61                 # rollback the last commit
62                 self._library._rollback()
63                 raise e
64         finally:
65             lock.release()
66         
67     # def commit(self, message, user):
68     #    """Make a new commit."""
69     #    self.invoke_and_commit(message, user, lambda *a: True)
70
71     def ismain(self):
72         return self._revision.user_name is None
73
74     def shared(self):
75         if self.ismain():
76             return self
77         
78         return self._library.document(docid=self.id)
79
80     def latest(self):
81         return self._library.document(docid=self.id, user=self.owner)
82
83     def take(self, user):
84         fullid = self._library.fulldocid(self.id, user)
85
86         def take_action(library, resolve):
87             # branch from latest 
88             library._create_branch(fullid, parent=self._revision)            
89
90         if not self._library.has_revision(fullid):
91             self.invoke_and_commit(take_action, \
92                 lambda d: ("$AUTO$ File checkout.", user) )
93
94         return self._library.document_for_rev(fullid)
95             
96     def update(self, user):
97         """Update parts of the document."""
98         lock = self.library.lock()
99         try:
100             if self.ismain():
101                 # main revision of the document
102                 return (True, False)
103             
104             if self._revision.has_children():
105                 print 'Update failed: has children.'
106                 # can't update non-latest revision
107                 return (False, False)
108
109             sv = self.shared()
110
111             if self.parentof(sv):
112                 return (True, False)
113
114             if sv.ancestorof(self):
115                 return (True, False)
116
117
118             return self._revision.merge_with(sv._revision, user=user)
119         finally:
120             lock.release()  
121
122     def share(self, message):
123         lock = self.library.lock()
124         try:            
125             if self.ismain():
126                 return (True, False) # always shared
127
128             user = self._revision.user_name
129             main = self.shared()._revision
130             local = self._revision            
131
132             # Case 1:
133             #         * local
134             #         |
135             #         * <- can also be here!
136             #        /|
137             #       / |
138             # main *  *
139             #      |  |
140             # The local branch has been recently updated,
141             # so we don't need to update yet again, but we need to
142             # merge down to default branch, even if there was
143             # no commit's since last update
144
145             if main.ancestorof(local):
146                 print "case 1"
147                 success, changed = main.merge_with(local, user=user, message=message)                
148             # Case 2:
149             #
150             # main *  * local
151             #      |\ |
152             #      | \|
153             #      |  *
154             #      |  |
155             #
156             # Default has no changes, to update from this branch
157             # since the last merge of local to default.
158             elif local.has_common_ancestor(main):
159                 print "case 2"
160                 if not local.parentof(main):
161                     success, changed = main.merge_with(local, user=user, message=message)
162
163             # Case 3:
164             # main *
165             #      |
166             #      * <- this case overlaps with previos one
167             #      |\
168             #      | \
169             #      |  * local
170             #      |  |
171             #
172             # There was a recent merge to the defaul branch and
173             # no changes to local branch recently.
174             #
175             # Use the fact, that user is prepared to see changes, to
176             # update his branch if there are any
177             elif local.ancestorof(main):
178                 print "case 3"
179                 if not local.parentof(main):
180                     success, changed = local.merge_with(main, user=user, \
181                         message='$AUTO$ Local branch update during share.')
182                     
183             else:
184                 print "case 4"
185                 success, changed = local.merge_with(main, user=user, \
186                         message='$AUTO$ Local branch update during share.')
187
188                 if not success:
189                     return False
190
191                 if changed:
192                     local = local.latest()
193                     
194                 success, changed = main.merge_with(local, user=user,\
195                     message=message)
196             
197             return success, changed
198         finally:
199             lock.release()     
200
201     def __unicode__(self):
202         return u"Document(%s:%s)" % (self.name, self.owner)
203
204     def __str__(self):
205         return self.__unicode__().encode('utf-8')
206     
207     def __eq__(self, other):
208         return (self._revision == other._revision) and (self.name == other.name)
209