dfcef099ac668c4e7905aeb843dcb57af66ff2c9
[redakcja.git] / lib / wlrepo / backend_mercurial.py
1 # -*- encoding: utf-8 -*-
2
3 __author__ = "Ɓukasz Rekucki"
4 __date__ = "$2009-09-18 10:49:24$"
5
6 __doc__ = """RAL implementation over Mercurial"""
7
8 import mercurial
9 from mercurial import localrepo as hglrepo
10 from mercurial import ui as hgui
11 from mercurial.node import nullid
12 import re
13 import wlrepo
14
15 FILTER = re.compile(r"^pub_(.+)\.xml$", re.UNICODE)
16
17 def default_filter(name):
18     m = FILTER.match(name)    
19     if m is not None:
20         return name, m.group(1)
21     return None
22
23 class MercurialLibrary(wlrepo.Library):
24
25     def __init__(self, path, maincabinet="default", ** kwargs):
26         super(wlrepo.Library, self).__init__( ** kwargs)
27
28         self._hgui = hgui.ui()
29         self._hgui.config('ui', 'quiet', 'true')
30         self._hgui.config('ui', 'interactive', 'false')
31
32         import os.path        
33         self._ospath = self._sanitize_string(os.path.realpath(path))
34         
35         maincabinet = self._sanitize_string(maincabinet)
36
37         if os.path.isdir(path):
38             try:
39                 self._hgrepo = hglrepo.localrepository(self._hgui, path)
40             except mercurial.error.RepoError:
41                 raise wlrepo.LibraryException("[HGLibrary] Not a valid repository at path '%s'." % path)
42         elif kwargs.get('create', False):
43             os.makedirs(path)
44             try:
45                 self._hgrepo = hglrepo.localrepository(self._hgui, path, create=1)
46             except mercurial.error.RepoError:
47                 raise wlrepo.LibraryException("[HGLibrary] Can't create a repository on path '%s'." % path)
48         else:
49             raise wlrepo.LibraryException("[HGLibrary] Can't open a library on path '%s'." % path)
50
51         # fetch the main cabinet
52         lock = self._hgrepo.lock()
53         try:
54             btags = self._hgrepo.branchtags()
55             
56             if not self._has_branch(maincabinet):
57                 raise wlrepo.LibraryException("[HGLibrary] No branch named '%s' to init main cabinet" % maincabinet)
58         
59             self._maincab = MercurialCabinet(self, maincabinet)
60         finally:
61             lock.release()
62
63     @property
64     def ospath(self):
65         return self._ospath
66
67     @property
68     def main_cabinet(self):
69         return self._maincab
70
71     def document(self, docid, user):
72         return self.cabinet(docid, user, create=False).retrieve()
73
74     def cabinet(self, docid, user, create=False):
75         docid = self._sanitize_string(docid)
76         user = self._sanitize_string(user)
77         
78         bname = self._bname(user, docid)
79
80         lock = self._lock(True)
81         try:
82             if self._has_branch(bname):
83                 return MercurialCabinet(self, doc=docid, user=user)
84
85             if not create:
86                 raise wlrepo.CabinetNotFound(bname)
87
88             # check if the docid exists in the main cabinet
89             needs_touch = not self._maincab.exists(docid)            
90             cab = MercurialCabinet(self, doc=docid, user=user)
91
92             name, fileid = cab._filename(None)
93
94             def cleanup_action(l):
95                 if needs_touch:                    
96                     l._fileopener()(fileid, "w").write('')
97                     l._fileadd(fileid)
98                 
99                 garbage = [fid for (fid, did) in l._filelist() if not did.startswith(docid)]                
100                 l._filesrm(garbage)
101                 print "removed: ", garbage
102
103             # create the branch
104             self._create_branch(bname, before_commit=cleanup_action)
105             return MercurialCabinet(self, doc=docid, user=user)
106         finally:
107             lock.release()
108             
109     #
110     # Private methods
111     #
112
113     #
114     # Locking
115     #
116  
117     def _lock(self, write_mode=False):
118         return self._hgrepo.wlock() # no support for read/write mode yet
119
120     def _transaction(self, write_mode, action):
121         lock = self._lock(write_mode)
122         try:
123             return action(self)
124         finally:
125             lock.release()
126             
127     #
128     # Basic repo manipulation
129     #   
130
131     def _checkout(self, rev, force=True):
132         return MergeStatus(mercurial.merge.update(self._hgrepo, rev, False, force, None))
133
134     def _merge(self, rev):
135         """ Merge the revision into current working directory """
136         return MergeStatus(mercurial.merge.update(self._hgrepo, rev, True, False, None))
137     
138     def _common_ancestor(self, revA, revB):
139         return self._hgrepo[revA].ancestor(self.repo[revB])
140
141     def _commit(self, message, user=u"library"):
142         return self._hgrepo.commit(text=message, user=user)
143
144
145     def _fileexists(self, fileid):
146         return (fileid in self._hgrepo[None])
147
148     def _fileadd(self, fileid):
149         return self._hgrepo.add([fileid])
150     
151     def _filesadd(self, fileid_list):
152         return self._hgrepo.add(fileid_list)
153
154     def _filerm(self, fileid):
155         return self._hgrepo.remove([fileid])
156
157     def _filesrm(self, fileid_list):
158         return self._hgrepo.remove(fileid_list)
159
160     def _filelist(self, filter=default_filter):
161         for name in  self._hgrepo[None]:
162             result = filter(name)
163             if result is None: continue
164             
165             yield result
166
167     def _fileopener(self):
168         return self._hgrepo.wopener
169
170     def _filectx(self, fileid, branchid):
171         return self._hgrepo.filectx(fileid, changeid=branchid)
172
173     def _changectx(self, nodeid):
174         return self._hgrepo.changectx(nodeid)
175     
176     #
177     # BASIC BRANCH routines
178     #
179
180     def _bname(self, user, docid):
181         """Returns a branch name for a given document and user."""
182         docid = self._sanitize_string(docid)
183         uname = self._sanitize_string(user)
184         return "personal_" + uname + "_file_" + docid;
185
186     def _has_branch(self, name):
187         return self._hgrepo.branchmap().has_key(self._sanitize_string(name))
188
189     def _branch_tip(self, name):
190         name = self._sanitize_string(name)
191         return self._hgrepo.branchtags()[name]
192
193     def _create_branch(self, name, parent=None, before_commit=None):        
194         name = self._sanitize_string(name)
195
196         if self._has_branch(name): return # just exit
197
198         if parent is None:
199             parent = self._maincab
200
201         parentrev = parent._hgtip()
202
203         self._checkout(parentrev)
204         self._hgrepo.dirstate.setbranch(name)
205
206         if before_commit: before_commit(self)
207
208         self._commit("[AUTO] Initial commit for branch '%s'." % name, user='library')
209         
210         # revert back to main
211         self._checkout(self._maincab._hgtip())
212         return self._branch_tip(name)
213
214     def _switch_to_branch(self, branchname):
215         current = self._hgrepo[None].branch()
216
217         if current == branchname:
218             return current # quick exit
219         
220         self._checkout(self._branch_tip(branchname))
221         return branchname        
222
223     def shelf(self, nodeid=None):
224         if nodeid is None:
225             nodeid = self._maincab._name
226         return MercurialShelf(self, self._changectx(nodeid))   
227
228
229     #
230     # Utils
231     #
232
233     @staticmethod
234     def _sanitize_string(s):        
235         if isinstance(s, unicode):
236             s = s.encode('utf-8')
237         return s
238
239 class MercurialCabinet(wlrepo.Cabinet):
240     
241     def __init__(self, library, branchname=None, doc=None, user=None):
242         if doc and user:
243             super(MercurialCabinet, self).__init__(library, doc=doc, user=user)
244             self._branchname = library._bname(user=user, docid=doc)
245         elif branchname:
246             super(MercurialCabinet, self).__init__(library, name=branchname)
247             self._branchname = branchname
248         else:
249             raise ValueError("Provide either doc/user or branchname")
250
251     def shelf(self, selector=None):
252         return self._library.shelf(self._branchname)
253
254     def documents(self):        
255         return self._execute_in_branch(action=lambda l, c: (e[1] for e in l._filelist()))
256
257     def retrieve(self, part=None, shelf=None):
258         name, fileid = self._filename(part)
259
260         print "Retrieving document %s from cab %s" % (name, self._name)
261
262         if fileid is None:
263             raise wlrepo.LibraryException("Can't retrieve main document from main cabinet.")
264
265         def retrieve_action(l,c):
266             if l._fileexists(fileid):
267                 return MercurialDocument(c, name=name, fileid=fileid)
268             print "File %s not found " % fileid
269             return None
270                 
271         return self._execute_in_branch(retrieve_action)        
272
273     def create(self, name, initial_data):
274         name, fileid = self._filename(name)
275
276         if name is None:
277             raise ValueError("Can't create main doc for maincabinet.")
278
279         def create_action(l, c):
280             if l._fileexists(fileid):
281                 raise wlrepo.LibraryException("Can't create document '%s' in cabinet '%s' - it already exists" % (fileid, c.name))
282
283             fd = l._fileopener()(fileid, "w")
284             fd.write(initial_data)
285             fd.close()
286             l._fileadd(fileid)            
287             l._commit("File '%s' created." % fileid)            
288             return MercurialDocument(c, fileid=fileid, name=name)           
289
290         return self._execute_in_branch(create_action)
291
292     def exists(self, part=None, shelf=None):
293         name, filepath = self._filename(part)
294
295         if filepath is None: return False
296         return self._execute_in_branch(lambda l, c: l._fileexists(filepath))
297     
298     def _execute_in_branch(self, action, write=False):
299         def switch_action(library):
300             old = library._switch_to_branch(self._branchname)
301             try:
302                 return action(library, self)
303             finally:
304                 library._switch_to_branch(old)
305
306         return self._library._transaction(write_mode=write, action=switch_action)
307
308     def _filename(self, part):
309         part = self._library._sanitize_string(part)
310         docid = None
311
312         if self._maindoc == '':
313             if part is None: rreeturn [None, None]
314             docid = part
315         else:
316             docid = self._maindoc + (('$' + part) if part else '')
317
318         return docid, 'pub_' + docid + '.xml'
319
320     def _fileopener(self):
321         return self._library._fileopener()
322
323     def _hgtip(self):
324         return self._library._branch_tip(self._branchname)
325
326     def _filectx(self, fileid):
327         return self._library._filectx(fileid, self._branchname)
328
329     def ismain(self):
330         return (self._library.main_cabinet == self)
331
332 class MercurialDocument(wlrepo.Document):
333
334     def __init__(self, cabinet, name, fileid):
335         super(MercurialDocument, self).__init__(cabinet, name=name)
336         self._opener = self._cabinet._fileopener()
337         self._fileid = fileid
338         self.refresh()
339
340     def refresh(self):
341         self._filectx = self._cabinet._filectx(self._fileid)        
342
343     def read(self):
344         return self._opener(self._filectx.path(), "r").read()
345
346     def write(self, data):
347         return self._opener(self._filectx.path(), "w").write(data)
348
349     def commit(self, message, user):
350         self.library._fileadd(self._fileid)
351         self.library._commit(self._fileid, message, user)
352
353     def update(self):
354         lock = self.library._lock()
355         try:
356             if self._cabinet.ismain():
357                 return True # always up-to-date
358
359             user = self._cabinet.username or 'library'
360             mdoc = self.library.document(self._fileid)
361
362             mshelf = mdoc.shelf()
363             shelf = self.shelf()
364
365             if not mshelf.ancestorof(shelf) and not shelf.parentof(mshelf):
366                 shelf.merge_with(mshelf, user=user)
367
368             return True
369         finally:
370             lock.release()            
371
372     def share(self, message):
373         lock = self.library._lock()
374         try:
375             print "sharing from", self._cabinet, self._cabinet.username
376             
377             if self._cabinet.ismain():
378                 return True # always shared
379
380             if self._cabinet.username is None:
381                 raise ValueError("Can only share documents from personal cabinets.")
382             
383             user = self._cabinet.username
384
385             main = self.library.shelf()
386             local = self.shelf()
387
388             no_changes = True
389
390             # Case 1:
391             #         * local
392             #         |
393             #         * <- can also be here!
394             #        /|
395             #       / |
396             # main *  *
397             #      |  |
398             # The local branch has been recently updated,
399             # so we don't need to update yet again, but we need to
400             # merge down to default branch, even if there was
401             # no commit's since last update
402
403             if main.ancestorof(local):
404                 print "case 1"
405                 main.merge_with(local, user=user, message=message)
406                 no_changes = False
407             # Case 2:
408             #
409             # main *  * local
410             #      |\ |
411             #      | \|
412             #      |  *
413             #      |  |
414             #
415             # Default has no changes, to update from this branch
416             # since the last merge of local to default.
417             elif local.has_common_ancestor(main):
418                 print "case 2"
419                 if not local.parentof(main):
420                     main.merge_with(local, user=user, message=message)
421                     no_changes = False
422
423             # Case 3:
424             # main *
425             #      |
426             #      * <- this case overlaps with previos one
427             #      |\
428             #      | \
429             #      |  * local
430             #      |  |
431             #
432             # There was a recent merge to the defaul branch and
433             # no changes to local branch recently.
434             #
435             # Use the fact, that user is prepared to see changes, to
436             # update his branch if there are any
437             elif local.ancestorof(main):
438                 print "case 3"
439                 if not local.parentof(main):
440                     local.merge_with(main, user=user, message='Local branch update.')
441                     no_changes = False
442             else:
443                 print "case 4"
444                 local.merge_with(main, user=user, message='Local branch update.')
445                 local = self.shelf()
446                 main.merge_with(local, user=user, message=message)
447
448             print "no_changes: ", no_changes
449             return no_changes
450         finally:
451             lock.release()
452                
453     def shared(self):
454         return self.library.main_cabinet.retrieve(self._name)
455
456     def exists(self):
457         return self._cabinet.exists(self._fileid)
458
459     @property
460     def size(self):
461         return self._filectx.size()
462     
463     def shelf(self):
464         return MercurialShelf(self.library, self._filectx.node())
465
466     @property
467     def last_modified(self):
468         return self._filectx.date()
469
470     def __str__(self):
471         return u"Document(%s->%s)" % (self._cabinet.name, self._name)
472
473     def __eq__(self, other):
474         return self._filectx == other._filectx
475
476
477
478 class MercurialShelf(wlrepo.Shelf):
479
480     def __init__(self, lib, changectx):
481         super(MercurialShelf, self).__init__(lib)
482
483         if isinstance(changectx, str):
484             self._changectx = lib._changectx(changectx)
485         else:
486             self._changectx = changectx
487
488     @property
489     def _rev(self):
490         return self._changectx.node()
491
492     def __str__(self):
493         return self._changectx.hex()
494
495     def __repr__(self):
496         return "MercurialShelf(%s)" % self._changectx.hex()
497
498     def ancestorof(self, other):
499         nodes = list(other._changectx._parents)
500         while nodes[0].node() != nullid:
501             v = nodes.pop(0)
502             if v == self._changectx:
503                 return True
504             nodes.extend( v._parents )
505         return False
506
507     def parentof(self, other):
508         return self._changectx in other._changectx._parents
509
510     def has_common_ancestor(self, other):
511         a = self._changectx.ancestor(other._changectx)
512         # print a, self._changectx.branch(), a.branch()
513
514         return (a.branch() == self._changectx.branch())
515
516     def merge_with(self, other, user, message):
517         lock = self._library._lock(True)
518         try:
519             self._library._checkout(self._changectx.node())
520             self._library._merge(other._changectx.node())
521             self._library._commit(user=user, message=message)
522         finally:
523             lock.release()
524
525     def __eq__(self, other):
526         return self._changectx.node() == other._changectx.node()
527         
528
529 class MergeStatus(object):
530     def __init__(self, mstatus):
531         self.updated = mstatus[0]
532         self.merged = mstatus[1]
533         self.removed = mstatus[2]
534         self.unresolved = mstatus[3]
535
536     def isclean(self):
537         return self.unresolved == 0
538
539 class UpdateStatus(object):
540
541     def __init__(self, mstatus):
542         self.modified = mstatus[0]
543         self.added = mstatus[1]
544         self.removed = mstatus[2]
545         self.deleted = mstatus[3]
546         self.untracked = mstatus[4]
547         self.ignored = mstatus[5]
548         self.clean = mstatus[6]
549
550     def has_changes(self):
551         return bool(len(self.modified) + len(self.added) + \
552                     len(self.removed) + len(self.deleted))
553
554 __all__ = ["MercurialLibrary"]