1 # -*- coding: utf-8 -*-
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
14 logger = logging.getLogger('fnp.hazlenut.vstorage')
16 # Note: we have to set these before importing Mercurial
17 os.environ['HGENCODING'] = 'utf-8'
18 os.environ['HGMERGE'] = "internal:merge"
21 import mercurial.revlog
24 from vstorage.hgui import SilentUI
27 def urlquote(url, safe='/'):
30 >>> urlquote(u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144')
31 'Za%C5%BC%C3%B3%C5%82%C4%87%20g%C4%99%C5%9Bl%C4%85%20ja%C5%BA%C5%84'
33 return urllib.quote(url.encode('utf-8', 'ignore'), safe)
39 # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
40 # u'Za\u017c\xf3\u0142\u0107_g\u0119\u015bl\u0105 ja\u017a\u0144'
42 return unicode(urllib.unquote(url), 'utf-8', 'ignore')
45 def find_repo_path(path):
46 """Go up the directory tree looking for a Mercurial repository (a directory containing a .hg subdirectory)."""
47 while not os.path.isdir(os.path.join(path, ".hg")):
48 old_path, path = path, os.path.dirname(path)
54 def with_working_copy_locked(func):
55 """A decorator for locking the repository when calling a method."""
57 @functools.wraps(func)
58 def wrapped(self, *args, **kwargs):
59 """Wrap the original function in locks."""
60 wlock = self.repo.wlock()
62 return func(self, *args, **kwargs)
68 def with_storage_locked(func):
69 """A decorator for locking the repository when calling a method."""
71 @functools.wraps(func)
72 def wrapped(self, *args, **kwargs):
73 """Wrap the original function in locks."""
74 lock = self.repo.lock()
76 return func(self, *args, **kwargs)
82 def guess_mime(file_name):
84 Guess file's mime type based on extension.
85 Default of text/x-wiki for files without an extension.
87 >>> guess_mime('something.txt')
89 >>> guess_mime('SomePage')
91 >>> guess_mime(u'ąęśUnicodePage')
93 >>> guess_mime('image.png')
95 >>> guess_mime('style.css')
97 >>> guess_mime('archive.tar.gz')
101 mime, encoding = mimetypes.guess_type(file_name, strict=False)
103 mime = 'archive/%s' % encoding
109 class DocumentNotFound(Exception):
113 class VersionedStorage(object):
115 Provides means of storing text pages and keeping track of their
116 change history, using Mercurial repository as the storage method.
119 def __init__(self, path, charset=None):
121 Takes the path to the directory where the pages are to be kept.
122 If the directory doen't exist, it will be created. If it's inside
123 a Mercurial repository, that repository will be used, otherwise
124 a new repository will be created in it.
127 self.charset = charset or 'utf-8'
129 if not os.path.exists(self.path):
130 os.makedirs(self.path)
131 self.repo_path = find_repo_path(self.path)
135 if self.repo_path is None:
136 self.repo_path = self.path
141 self.repo_prefix = self.path[len(self.repo_path):].strip('/')
142 self.repo = mercurial.hg.repository(self.ui, self.repo_path,
146 """Close and reopen the repo, to make sure we are up to date."""
147 self.repo = mercurial.hg.repository(self.ui, self.repo_path)
149 def _file_path(self, title, type='.xml'):
150 """ Return plain version if exists in repo, add extension otherwise. """
151 path = os.path.join(self.path, urlquote(title, safe=''))
152 if type and self._title_to_file(title, '') not in self.repo['tip']:
156 def _title_to_file(self, title, type=".xml"):
157 """ Return plain version if exists in repo, add extension otherwise. """
158 path = os.path.join(self.repo_prefix, urlquote(title, safe=''))
159 if type and path not in self.repo['tip']:
163 def _file_to_title(self, filename):
164 assert filename.startswith(self.repo_prefix)
165 name = filename[len(self.repo_prefix):].strip('/').rsplit('.', 1)[0]
166 return urlunquote(name)
168 def __contains__(self, title):
169 return self._title_to_file(title) in self.repo['tip']
172 return self.all_pages()
174 def merge_changes(self, changectx, repo_file, text, user, parent):
175 """Commits and merges conflicting changes in the repository."""
176 tip_node = changectx.node()
177 filectx = changectx[repo_file].filectx(parent)
178 parent_node = filectx.changectx().node()
180 self.repo.dirstate.setparents(parent_node)
181 node = self._commit([repo_file], text, user)
183 def partial(filename):
184 return repo_file == filename
186 # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
187 p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
192 mercurial.merge.update(self.repo, tip_node, True, False, partial)
193 msg = 'merge of edit conflict'
194 except mercurial.util.Abort:
195 msg = 'failed merge of edit conflict'
197 self.repo.dirstate.setparents(tip_node, node)
198 # Mercurial 1.1 and later need updating the merge state
200 mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
201 except (AttributeError, KeyError):
205 @with_working_copy_locked
207 def save_file(self, title, file_name, **kwargs):
208 """Save an existing file as specified page."""
210 author = kwargs.get('author', u'anonymous').encode('utf-8')
211 comment = kwargs.get('comment', u'Empty comment.').encode('utf-8')
212 parent = kwargs.get('parent', None)
214 repo_file = self._title_to_file(title)
215 file_path = self._file_path(title)
216 mercurial.util.rename(file_name, file_path)
217 changectx = self._changectx()
220 filectx_tip = changectx[repo_file]
221 current_page_rev = filectx_tip.filerev()
222 except mercurial.revlog.LookupError:
223 self.repo[None].add([repo_file])
224 current_page_rev = -1
226 if parent is not None and current_page_rev != parent:
227 msg = self.merge_changes(changectx, repo_file, comment, author, parent)
229 comment = msg.encode('utf-8')
231 logger.debug("Commiting %r", repo_file)
233 self._commit([repo_file], comment, author)
235 def save_data(self, title, data, **kwargs):
236 """Save data as specified page."""
237 temp_path = tempfile.mkdtemp(dir=self.path)
238 file_path = os.path.join(temp_path, 'saved')
240 f = open(file_path, "wb")
244 return self.save_file(title=title, file_name=file_path, **kwargs)
255 def save_text(self, **kwargs):
256 """Save text as specified page, encoded to charset."""
257 text = kwargs.pop('text')
258 return self.save_data(data=text.encode(self.charset), **kwargs)
260 def _commit(self, files, comment, user):
261 match = mercurial.match.exact(self.repo_path, '', list(files))
262 return self.repo.commit(match=match, text=comment, user=user, force=True)
264 @with_working_copy_locked
266 def delete_page(self, title, author=u'', comment=u''):
267 user = author.encode('utf-8') or 'anon'
268 text = comment.encode('utf-8') or 'deleted'
269 repo_file = self._title_to_file(title)
270 file_path = self._file_path(title)
275 self.repo[None].remove([repo_file])
276 self._commit([repo_file], text, user)
278 def page_text(self, title, revision=None):
279 """Read unicode text of a page."""
280 ctx = self._find_filectx(title, revision)
283 raise DocumentNotFound(title)
285 return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
287 def page_text_by_tag(self, title, tag):
288 """Read unicode text of a taged page."""
289 fname = self._title_to_file(title)
290 tag = u"{fname}#{tag}".format(**locals()).encode('utf-8')
293 ctx = self.repo[tag][fname]
294 return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
296 raise DocumentNotFound(fname)
298 @with_working_copy_locked
299 def page_file_meta(self, title):
300 """Get page's inode number, size and last modification time."""
302 (_st_mode, st_ino, _st_dev, _st_nlink, _st_uid, _st_gid, st_size,
303 _st_atime, st_mtime, _st_ctime) = os.stat(self._file_path(title))
306 return st_ino, st_size, st_mtime
308 @with_working_copy_locked
309 def page_meta(self, title, revision=None):
310 """Get page's revision, date, last editor and his edit comment."""
311 fctx = self._find_filectx(title, revision)
314 raise DocumentNotFound(title)
317 "revision": fctx.filerev(),
318 "date": datetime.datetime.fromtimestamp(fctx.date()[0]),
319 "author": fctx.user().decode("utf-8", 'replace'),
320 "comment": fctx.description().decode("utf-8", 'replace'),
323 def repo_revision(self):
324 return self.repo['tip'].rev()
326 def _changectx(self):
327 return self.repo['tip']
329 def page_mime(self, title):
331 Guess page's mime type based on corresponding file name.
332 Default ot text/x-wiki for files without an extension.
334 return guess_mime(self._file_path(title))
336 def _find_filectx(self, title, rev=None):
338 Find the revision of the file in repo.
339 Only look for files still existing in repo's tip.
341 tip = self._changectx()
342 file = self._title_to_file(title)
343 logging.info('Looking for %s', file)
347 file = self._title_to_file(title, type='')
348 logging.info('.xml not found, trying plain')
352 raise DocumentNotFound(title)
355 fctx = fctx.filectx(rev)
359 def page_history(self, title):
360 """Iterate over the page's history."""
362 filectx_tip = self._find_filectx(title)
364 maxrev = filectx_tip.filerev()
366 for rev in range(maxrev, minrev - 1, -1):
367 filectx = filectx_tip.filectx(rev)
368 date = datetime.datetime.fromtimestamp(filectx.date()[0])
369 author = filectx.user().decode('utf-8', 'replace')
370 comment = filectx.description().decode("utf-8", 'replace')
371 tags = [t.rsplit('#', 1)[-1] for t in filectx.changectx().tags() if '#' in t]
377 "description": comment,
381 @with_working_copy_locked
382 def add_page_tag(self, title, rev, tag, user, doctag=True):
383 ctitle = self._title_to_file(title)
386 tag = u"{ctitle}#{tag}".format(**locals()).encode('utf-8')
388 message = u"Assigned tag {tag!r} to version {rev!r} of {ctitle!r}".format(**locals()).encode('utf-8')
390 fctx = self._find_filectx(title, rev)
392 names=tag, node=fctx.node(), local=False,
393 user=user, message=message, date=None,
397 """Iterate over the history of entire wiki."""
399 changectx = self._changectx()
400 maxrev = changectx.rev()
402 for wiki_rev in range(maxrev, minrev - 1, -1):
403 change = self.repo.changectx(wiki_rev)
404 date = datetime.datetime.fromtimestamp(change.date()[0])
405 author = change.user().decode('utf-8', 'replace')
406 comment = change.description().decode("utf-8", 'replace')
407 for repo_file in change.files():
408 if repo_file.startswith(self.repo_prefix):
409 title = self._file_to_title(repo_file)
411 rev = change[repo_file].filerev()
412 except mercurial.revlog.LookupError:
414 yield title, rev, date, author, comment
416 def all_pages(self, type=''):
417 tip = self.repo['tip']
418 """Iterate over the titles of all pages in the wiki."""
419 return [self._file_to_title(filename) for filename in tip
420 if not filename.startswith('.') and filename.endswith(type)]
422 def changed_since(self, rev):
423 """Return all pages that changed since specified repository revision."""
426 last = self.repo.lookup(int(rev))
428 for page in self.all_pages():
432 current = self.repo.lookup('tip')
433 status = self.repo.status(current, last)
434 modified, added, removed, deleted, unknown, ignored, clean = status
435 for filename in modified + added + removed + deleted:
436 if filename.startswith(self.repo_prefix):
437 yield self._file_to_title(filename)
439 def revert(self, pageid, rev, **commit_args):
440 """ Make the given version of page the current version (reverting changes). """
442 # Find the old version
443 fctx = self._find_filectx(pageid, rev)
445 # Restore the contents
446 self.save_data(pageid, fctx.data(), **commit_args)