Merge branch 'master' into lqc-trunk
[redakcja.git] / lib / wlrepo / mercurial_backend / document.py
1 # -*- encoding: utf-8 -*-
2
3 import logging
4 log = logging.getLogger('ral.mercurial')
5
6 __author__ = "Ɓukasz Rekucki"
7 __date__ = "$2009-09-25 09:35:06$"
8 __doc__ = "Module documentation."
9
10 import wlrepo
11 import mercurial.error
12 import re
13
14 import logging
15 log = logging.getLogger('wlrepo.document')
16
17 class MercurialDocument(wlrepo.Document):
18
19     def data(self, entry):
20         path = self._library._sanitize_string(self.id + u'.' + entry)
21         try:
22             return self._library._filectx(path, \
23                 self._revision.hgrev()).data().decode('utf-8')
24         except mercurial.error.LookupError, e:
25             fl = [x.decode('utf-8') for x in self._revision._changectx]            
26             raise wlrepo.EntryNotFound(self._revision, path.decode('utf-8'), fl)
27
28     def quickwrite(self, entry, data, msg, user=None):
29         user = user or self.owner
30
31         if isinstance(data, unicode):
32             data = data.encode('utf-8')
33             
34         user = self._library._sanitize_string(user)
35         msg = self._library._sanitize_string(msg)
36         entry = self._library._sanitize_string(entry)
37
38         if user is None:
39             raise ValueError("Can't determine user.")
40         
41         def write(l, r):
42             f = l._fileopen(r(entry), "w+")
43             f.write(data)
44             f.close()
45             l._fileadd(r(entry))            
46
47         return self.invoke_and_commit(write, lambda d: (msg, \
48                 self._library._sanitize_string(self.owner)) )
49
50     def invoke_and_commit(self, ops, commit_info):
51         lock = self._library.lock()
52         try:            
53             self._library._checkout(self._revision.hgrev())
54
55             def entry_path(entry):
56                 return self._library._sanitize_string(self.id + u'.' + entry)
57             
58             ops(self._library, entry_path)
59             message, user = commit_info(self)
60
61             message = self._library._sanitize_string(message)
62             user = self._library._sanitize_string(user)
63
64             self._library._commit(message, user)
65             try:
66                 return self._library.document(docid=self.id, user=user)
67             except Exception, e:
68                 # rollback the last commit
69                 self._library._rollback()
70                 raise e
71         finally:
72             lock.release()
73         
74     # def commit(self, message, user):
75     #    """Make a new commit."""
76     #    self.invoke_and_commit(message, user, lambda *a: True)
77
78     def ismain(self):
79         return self._revision.user_name is None
80
81     def islatest(self):
82         return (self == self.latest())
83
84     def shared(self):
85         if self.ismain():
86             return self
87         
88         return self._library.document(docid=self.id)
89
90     def latest(self):
91         return self._library.document(docid=self.id, user=self.owner)
92
93     def take(self, user):
94         fullid = self._library.fulldocid(self.id, user)
95
96         def take_action(library, resolve):
97             # branch from latest 
98             library._set_branchname(fullid)
99
100         if not self._library.has_revision(fullid):
101             log.info("Checking out document %s" % fullid)
102
103             self.invoke_and_commit(take_action, \
104                 lambda d: ("$AUTO$ File checkout.", user) )
105
106         return self._library.document_for_revision(fullid)
107
108     def up_to_date(self):
109         if self.ismain():
110             return True
111
112         shared = self.shared()
113         
114         if shared.ancestorof(self):
115             return True
116
117         if shared.has_parent_from(self):
118             return True
119
120         return False
121                     
122     def update(self, user):
123         """Update parts of the document."""
124         lock = self.library.lock()
125         try:
126             if self.ismain():
127                 # main revision of the document
128                 return self
129
130             # check for children in this branch
131             if self._revision.has_children(limit_branch=True):
132                 raise wlrepo.UpdateException("Revision %s has children." % self.revision)
133
134             shared = self.shared()
135             #     *
136             #    /|
137             #   * |
138             #   | |
139             #
140             # we carry the latest version
141             if shared.ancestorof(self):
142                return self
143
144             #   *
145             #   |\
146             #   | *
147             #   | |
148             #
149             # We just shared
150             if self.parentof(shared):
151                 return self
152
153             #  s     s  S
154             #  |     |  |
155             #  *<-S  *<-*
156             #  |  |  |  .
157             #
158             #  This is ok (s - shared, S - self)
159
160             if self._revision.merge_with(shared._revision, user=user,\
161                 message="$AUTO$ Personal branch update."):
162                 return self.latest()
163             else:
164                 raise wlrepo.UpdateException("Merge failed.")
165         finally:
166             lock.release()
167
168
169     def would_share(self):
170         if self.ismain():
171             return False, "Main version is always shared"
172
173         shared = self.shared()
174
175         # we just did this - move on
176         if self.parentof(shared):
177             return False, "Document has been recetly shared - no changes"
178
179         #     *
180         #    /|
181         #   * *
182         #   |\|
183         #   | *
184         #   | |
185         # Situation above is ok - what we don't want, is:
186         #     *
187         #    /|
188         #   * |
189         #   |\|
190         #   | *
191         #   | |
192         # We want to prevent stuff like this.
193         if self.parent().parentof(shared) and shared.parentof(self):
194             return False, "Preventing zig-zag"
195
196         return True, "All ok"
197
198     def share(self, message):
199         lock = self.library.lock()
200         try:
201             # check if the document is in "updated" state
202             if not self.up_to_date():
203                 raise wlrepo.OutdatedException("You must update your document before share.")
204
205             # now check if there is anything to do
206             need_work, info = self.would_share()
207             
208             if not need_work:
209                 return self.shared()          
210       
211             # The good situation
212             #
213             #         * local
214             #         |
215             #        >* 
216             #        ||
217             #       / |
218             # main *  *
219             #      |  |
220             shared = self.shared()
221
222             try:
223                 success = shared._revision.merge_with(self._revision, user=self.owner, message=message)
224                 if not success:
225                     raise wlrepo.LibraryException("Merge failed.")
226                 
227                 return shared.latest()
228             except Abort, e:
229                 raise wlrepo.LibraryException( repr(e) )
230         finally:
231             lock.release()
232
233
234     def has_conflict_marks(self):
235         return re.search("^(?:<<<<<<< .*|=======|>>>>>>> .*)$", self.data('xml'), re.MULTILINE)        
236
237     def __unicode__(self):
238         return u"Document(%s:%s)" % (self.id, self.owner)
239
240     def __str__(self):
241         return self.__unicode__().encode('utf-8')
242     
243     def __eq__(self, other):
244         return (self._revision == other._revision)
245