Merge branch 'master' of stigma.nowoczesnapolska.org.pl:platforma
[redakcja.git] / lib / wlrepo / mercurial_backend / library.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:33:02$"
8 __doc__ = "Module documentation."
9
10 import mercurial
11 from mercurial import localrepo as hglrepo
12 from mercurial import ui as hgui
13 from mercurial import error
14 import wlrepo
15
16 from wlrepo.mercurial_backend import MercurialRevision
17 from wlrepo.mercurial_backend.document import MercurialDocument
18
19 class MergeStatus(object):
20     def __init__(self, mstatus):
21         self.updated = mstatus[0]
22         self.merged = mstatus[1]
23         self.removed = mstatus[2]
24         self.unresolved = mstatus[3]
25
26     def isclean(self):
27         return self.unresolved == 0
28
29 class UpdateStatus(object):
30
31     def __init__(self, mstatus):
32         self.modified = mstatus[0]
33         self.added = mstatus[1]
34         self.removed = mstatus[2]
35         self.deleted = mstatus[3]
36         self.untracked = mstatus[4]
37         self.ignored = mstatus[5]
38         self.clean = mstatus[6]
39
40     def has_changes(self):
41         return bool(len(self.modified) + len(self.added) + \
42                     len(self.removed) + len(self.deleted))
43
44 class MercurialLibrary(wlrepo.Library):
45     """Mercurial implementation of the Library API"""
46
47     def __init__(self, path, **kwargs):
48         super(wlrepo.Library, self).__init__( ** kwargs)
49
50         self._revcache = {}
51         self._doccache = {}
52
53         self._hgui = hgui.ui()
54         self._hgui.config('ui', 'quiet', 'true')
55         self._hgui.config('ui', 'interactive', 'false')
56
57         import os.path
58         self._ospath = self._sanitize_string(os.path.realpath(path))        
59
60         if os.path.isdir(path):
61             try:
62                 self._hgrepo = hglrepo.localrepository(self._hgui, path)
63             except mercurial.error.RepoError:
64                 raise wlrepo.LibraryException("[HGLibrary] Not a valid repository at path '%s'." % path)
65         elif kwargs.get('create', False):
66             os.makedirs(path)
67             try:
68                 self._hgrepo = hglrepo.localrepository(self._hgui, path, create=1)
69             except mercurial.error.RepoError:
70                 raise wlrepo.LibraryException("[HGLibrary] Can't create a repository on path '%s'." % path)
71         else:
72             raise wlrepo.LibraryException("[HGLibrary] Can't open a library on path '%s'." % path)
73
74
75     def documents(self):
76         return [ key[5:].decode('utf-8') for key in \
77             self._hgrepo.branchmap() if key.startswith("$doc:") ]
78
79     @property
80     def ospath(self):
81         return self._ospath.decode('utf-8')
82
83     def document_for_rev(self, revision):
84         if revision is None:
85             raise ValueError("Revision can't be None.")
86         
87         if not isinstance(revision, MercurialRevision):            
88             rev = self.get_revision(revision)
89         else:
90             rev = revision       
91
92         if not self._doccache.has_key(str(rev)):
93             self._doccache[str(rev)] = MercurialDocument(self, rev)
94
95         # every revision is a document
96         return self._doccache[str(rev)]
97
98     def document(self, docid, user=None, rev=u'latest'):
99         rev = self._sanitize_string(rev)
100         
101         if rev != u'latest':
102             doc = self.document_for_rev(rev)
103
104             if doc.id != docid or (doc.owner != user):
105                 raise wlrepo.RevisionMismatch(self.fulldocid(docid, user)+u'@'+unicode(rev))
106             
107             return doc
108         else:
109             return self.document_for_rev(self.fulldocid(docid, user))
110
111     def get_revision(self, revid):
112         revid = self._sanitize_string(revid)
113
114         log.info("Looking up rev %r (%s)" %(revid, type(revid)) )
115
116         try:           
117             ctx = self._changectx( revid )
118         except mercurial.error.RepoError, e:
119             raise wlrepo.RevisionNotFound(revid)
120
121         if ctx is None:
122             raise wlrepo.RevisionNotFound(revid)
123
124         if self._revcache.has_key(ctx):
125             return self._revcache[ctx]
126
127         return MercurialRevision(self, ctx)
128
129     def fulldocid(self, docid, user=None):                
130         fulldocid = u''
131         if user is not None:
132             fulldocid += u'$user:' + user
133         fulldocid += u'$doc:' + docid
134         return fulldocid
135
136     def has_revision(self, revid):
137         try:
138             self._hgrepo[revid]
139             return True
140         except mercurial.error.RepoError:
141             return False
142
143     def document_create(self, docid):
144         
145         
146         # check if it already exists
147         fullid = self.fulldocid(docid)
148
149         if self.has_revision(fullid):
150             raise wlrepo.DocumentAlreadyExists(u"Document %s already exists!" % docid);
151
152         # doesn't exist
153         self._create_branch(self._sanitize_string(fullid))
154         return self.document_for_rev(fullid)
155
156     #
157     # Private methods
158     #
159
160     #
161     # Locking
162     #
163
164     def lock(self, write_mode=False):
165         return self._hgrepo.wlock() # no support for read/write mode yet
166
167     def _transaction(self, write_mode, action):
168         lock = self.lock(write_mode)
169         try:
170             return action(self)
171         finally:
172             lock.release()
173
174     #
175     # Basic repo manipulation
176     #
177
178     def _checkout(self, rev, force=True):
179         return MergeStatus(mercurial.merge.update(self._hgrepo, rev, False, force, None))
180
181     def _merge(self, rev):
182         """ Merge the revision into current working directory """
183         return MergeStatus(mercurial.merge.update(self._hgrepo, rev, True, False, None))
184
185     def _common_ancestor(self, revA, revB):
186         return self._hgrepo[revA].ancestor(self.repo[revB])
187
188     def _commit(self, message, user=u"library"):
189         return self._hgrepo.commit(text=message, user=user)
190
191
192     def _fileexists(self, fileid):
193         return (fileid in self._hgrepo[None])
194
195     def _fileadd(self, fileid):
196         return self._hgrepo.add([fileid])
197
198     def _filesadd(self, fileid_list):
199         return self._hgrepo.add(fileid_list)
200
201     def _filerm(self, fileid):
202         return self._hgrepo.remove([fileid])
203
204     def _filesrm(self, fileid_list):
205         return self._hgrepo.remove(fileid_list)   
206
207     def _fileopen(self, path, mode):
208         return self._hgrepo.wopener(path, mode)
209
210     def _filectx(self, fileid, revid):
211         return self._hgrepo.filectx(fileid, changeid=revid)
212
213     def _changectx(self, nodeid):
214         return self._hgrepo.changectx(nodeid)
215
216     def _rollback(self):
217         return self._hgrepo.rollback()
218
219     #
220     # BASIC BRANCH routines
221     #
222
223     def _bname(self, user, docid):
224         """Returns a branch name for a given document and user."""
225         docid = self._sanitize_string(docid)
226         uname = self._sanitize_string(user)
227         return "personal_" + uname + "_file_" + docid;
228
229     def _has_branch(self, name):
230         return self._hgrepo.branchmap().has_key(self._sanitize_string(name))
231
232     def _branch_tip(self, name):
233         name = self._sanitize_string(name)
234         return self._hgrepo.branchtags()[name]    
235
236     def _create_branch(self, name, parent=None, before_commit=None, message=None):
237         name = self._sanitize_string(name)
238
239         if self._has_branch(name): return # just exit
240
241         if parent is None:
242             parentrev = self._hgrepo['$branchbase'].node()
243         else:
244             parentrev = parent.hgrev()
245
246         self._checkout(parentrev)
247         self._set_branchname(name)
248
249         if before_commit: before_commit(self)
250
251         message = message or "$ADMN$ Initial commit for branch '%s'." % name
252         self._commit(message, user='$library')
253
254     def _set_branchname(self, name):
255         name = self._sanitize_string(name)
256         self._hgrepo.dirstate.setbranch(name)
257
258     def _switch_to_branch(self, branchname):
259         current = self._hgrepo[None].branch()
260
261         if current == branchname:
262             return current # quick exit
263
264         self._checkout(self._branch_tip(branchname))
265         return branchname    
266
267     #
268     # Utils
269     #
270
271     @staticmethod
272     def _sanitize_string(s):
273         if s is None:
274             return None
275
276         if isinstance(s, unicode):
277             s = s.encode('utf-8')        
278
279         return s