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
23 from mercurial.match import exact as hg_exact_match
24 from mercurial.cmdutil import walkchangerevs
26 from vstorage.hgui import SilentUI
29 def urlquote(url, safe='/'):
32 >>> urlquote(u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144')
33 'Za%C5%BC%C3%B3%C5%82%C4%87%20g%C4%99%C5%9Bl%C4%85%20ja%C5%BA%C5%84'
35 return urllib.quote(url.encode('utf-8', 'ignore'), safe)
41 # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
42 # u'Za\u017c\xf3\u0142\u0107_g\u0119\u015bl\u0105 ja\u017a\u0144'
44 return unicode(urllib.unquote(url), 'utf-8', 'ignore')
47 def find_repo_path(path):
48 """Go up the directory tree looking for a Mercurial repository (a directory containing a .hg subdirectory)."""
49 while not os.path.isdir(os.path.join(path, ".hg")):
50 old_path, path = path, os.path.dirname(path)
56 def with_working_copy_locked(func):
57 """A decorator for locking the repository when calling a method."""
59 @functools.wraps(func)
60 def wrapped(self, *args, **kwargs):
61 """Wrap the original function in locks."""
62 wlock = self.repo.wlock()
64 return func(self, *args, **kwargs)
70 def with_storage_locked(func):
71 """A decorator for locking the repository when calling a method."""
73 @functools.wraps(func)
74 def wrapped(self, *args, **kwargs):
75 """Wrap the original function in locks."""
76 lock = self.repo.lock()
78 return func(self, *args, **kwargs)
84 def guess_mime(file_name):
86 Guess file's mime type based on extension.
87 Default of text/x-wiki for files without an extension.
89 >>> guess_mime('something.txt')
91 >>> guess_mime('SomePage')
93 >>> guess_mime(u'ąęśUnicodePage')
95 >>> guess_mime('image.png')
97 >>> guess_mime('style.css')
99 >>> guess_mime('archive.tar.gz')
103 mime, encoding = mimetypes.guess_type(file_name, strict=False)
105 mime = 'archive/%s' % encoding
111 class DocumentNotFound(Exception):
115 class VersionedStorage(object):
117 Provides means of storing text pages and keeping track of their
118 change history, using Mercurial repository as the storage method.
121 def __init__(self, path, charset=None):
123 Takes the path to the directory where the pages are to be kept.
124 If the directory doen't exist, it will be created. If it's inside
125 a Mercurial repository, that repository will be used, otherwise
126 a new repository will be created in it.
129 self.charset = charset or 'utf-8'
131 if not os.path.exists(self.path):
132 os.makedirs(self.path)
133 self.repo_path = find_repo_path(self.path)
137 if self.repo_path is None:
138 self.repo_path = self.path
143 self.repo_prefix = self.path[len(self.repo_path):].strip('/')
144 self.repo = mercurial.hg.repository(self.ui, self.repo_path,
148 """Close and reopen the repo, to make sure we are up to date."""
149 self.repo = mercurial.hg.repository(self.ui, self.repo_path)
151 def _file_path(self, title, type='.xml'):
152 return os.path.join(self.path, urlquote(title, safe='')) + type
154 def _title_to_file(self, title, type=".xml"):
155 return os.path.join(self.repo_prefix, urlquote(title, safe='')) + type
157 def _file_to_title(self, filename):
158 assert filename.startswith(self.repo_prefix)
159 name = filename[len(self.repo_prefix):].strip('/').split('.', 1)[0]
160 return urlunquote(name)
162 def __contains__(self, title):
163 return self._title_to_file(title) in self.repo['tip']
166 return self.all_pages()
168 def merge_changes(self, changectx, repo_file, text, user, parent):
169 """Commits and merges conflicting changes in the repository."""
170 tip_node = changectx.node()
171 filectx = changectx[repo_file].filectx(parent)
172 parent_node = filectx.changectx().node()
174 self.repo.dirstate.setparents(parent_node)
175 node = self._commit([repo_file], text, user)
177 partial = lambda filename: repo_file == filename
179 # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
180 p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
185 mercurial.merge.update(self.repo, tip_node, True, False, partial)
186 msg = 'merge of edit conflict'
187 except mercurial.util.Abort:
188 msg = 'failed merge of edit conflict'
190 self.repo.dirstate.setparents(tip_node, node)
191 # Mercurial 1.1 and later need updating the merge state
193 mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
194 except (AttributeError, KeyError):
198 @with_working_copy_locked
200 def save_file(self, title, file_name, **kwargs):
201 """Save an existing file as specified page."""
203 author = kwargs.get('author', u'anonymous').encode('utf-8')
204 comment = kwargs.get('comment', u'Empty comment.').encode('utf-8')
205 parent = kwargs.get('parent', None)
207 repo_file = self._title_to_file(title)
208 file_path = self._file_path(title)
209 mercurial.util.rename(file_name, file_path)
210 changectx = self._changectx()
213 filectx_tip = changectx[repo_file]
214 current_page_rev = filectx_tip.rev()
215 except mercurial.revlog.LookupError:
216 self.repo.add([repo_file])
217 current_page_rev = -1
219 if parent is not None and current_page_rev != parent:
220 msg = self.merge_changes(changectx, repo_file, comment, author, parent)
222 comment = msg.encode('utf-8')
224 logger.debug("Commiting %r", repo_file)
226 self._commit([repo_file], comment, author)
228 def save_data(self, title, data, **kwargs):
229 """Save data as specified page."""
231 temp_path = tempfile.mkdtemp(dir=self.path)
232 file_path = os.path.join(temp_path, 'saved')
233 f = open(file_path, "wb")
237 return self.save_file(title=title, file_name=file_path, **kwargs)
248 def save_text(self, **kwargs):
249 """Save text as specified page, encoded to charset."""
250 text = kwargs.pop('text')
251 return self.save_data(data=text.encode(self.charset), **kwargs)
253 def _commit(self, files, comment, user):
254 match = mercurial.match.exact(self.repo_path, '', list(files))
255 return self.repo.commit(match=match, text=comment, user=user, force=True)
257 @with_working_copy_locked
259 def delete_page(self, title, author=u'', comment=u''):
260 user = author.encode('utf-8') or 'anon'
261 text = comment.encode('utf-8') or 'deleted'
262 repo_file = self._title_to_file(title)
263 file_path = self._file_path(title)
268 self.repo.remove([repo_file])
269 self._commit([repo_file], text, user)
271 def page_text(self, title, revision=None):
272 """Read unicode text of a page."""
273 ctx = self._find_filectx(title, revision)
276 raise DocumentNotFound(title)
278 return ctx.data().decode(self.charset, 'replace'), ctx.rev()
280 def page_text_by_tag(self, title, tag):
281 """Read unicode text of a taged page."""
282 fname = self._title_to_file(title)
283 tag = u"{fname}#{tag}".format(**locals()).encode('utf-8')
286 ctx = self.repo[tag][fname]
287 return ctx.data().decode(self.charset, 'replace'), ctx.rev()
289 raise DocumentNotFound(fname)
291 @with_working_copy_locked
292 def page_file_meta(self, title):
293 """Get page's inode number, size and last modification time."""
295 (_st_mode, st_ino, _st_dev, _st_nlink, _st_uid, _st_gid, st_size,
296 _st_atime, st_mtime, _st_ctime) = os.stat(self._file_path(title))
299 return st_ino, st_size, st_mtime
301 @with_working_copy_locked
302 def page_meta(self, title, revision=None):
303 """Get page's revision, date, last editor and his edit comment."""
304 fctx = self._find_filectx(title, revision)
307 raise DocumentNotFound(title)
310 "revision": fctx.rev(),
311 "date": datetime.datetime.fromtimestamp(fctx.date()[0]),
312 "author": fctx.user().decode("utf-8", 'replace'),
313 "comment": fctx.description().decode("utf-8", 'replace'),
316 def repo_revision(self):
317 return self.repo['tip'].rev()
319 def _changectx(self):
320 return self.repo['tip']
322 def page_mime(self, title):
324 Guess page's mime type based on corresponding file name.
325 Default ot text/x-wiki for files without an extension.
327 return guess_mime(self._file_path(title))
329 def _find_filectx(self, title, rev=None, oldest=0, newest= -1):
330 """Find the last revision in which the file existed."""
332 oldest, newest = rev, -1
333 opts = {"follow": True, "rev": ["%s:%s" % (newest, oldest)]}
334 def prepare(ctx, fns):
336 xml_file = self._title_to_file(title)
337 matchfn = hg_exact_match(self.repo.root, self.repo.getcwd(), [xml_file])
338 generator = walkchangerevs(self.repo, matchfn, opts, prepare)
341 current_name = xml_file
342 for change in generator:
343 fctx = change[current_name]
344 renamed = fctx.renamed()
346 current_name = renamed[0]
350 return last[current_name]
353 raise DocumentNotFound(title)
355 def page_history(self, title, oldest=0, newest= -1):
356 """Iterate over the page's history."""
357 opts = {"follow": True, "rev": ["%s:%s" % (newest, oldest)]}
358 prepare = lambda * args: True
359 repo_file = self._title_to_file(title)
360 matchfn = hg_exact_match(self.repo.root, self.repo.getcwd(), [repo_file])
361 generator = walkchangerevs(self.repo, matchfn, opts, prepare)
363 for changeset in generator:
365 date = datetime.datetime.fromtimestamp(changeset.date()[0])
366 author = changeset.user().decode('utf-8', 'replace')
367 comment = changeset.description().decode("utf-8", 'replace')
368 tags = [t.rsplit('#', 1)[-1] for t in changeset.tags() if '#' in t]
371 "version": changeset.rev(),
374 "description": comment,
378 @with_working_copy_locked
379 def add_page_tag(self, title, rev, tag, user, doctag=True):
380 ctitle = self._title_to_file(title)
383 tag = u"{ctitle}#{tag}".format(**locals()).encode('utf-8')
385 message = u"Assigned tag {tag!r} to version {rev!r} of {ctitle!r}".format(**locals()).encode('utf-8')
387 fctx = self._find_filectx(title, rev)
389 names=tag, node=fctx.node(), local=False,
390 user=user, message=message, date=None,
393 def history(self, newest=None):
394 """Iterate over the history of entire wiki."""
395 opts = {"follow": False, "rev": newest} # follow doesn't make sense
396 prepare = lambda * args: True
397 repo_file = self._title_to_file(title)
398 matchfn = hg_exact_match(self.repo.root, self.repo.getcwd(), [repo_file])
399 generator = walkchangerevs(self.repo, matchfn, opts, prepare)
401 for change in generator:
402 date = datetime.datetime.fromtimestamp(change.date()[0])
403 author = change.user().decode('utf-8', 'replace')
404 comment = change.description().decode("utf-8", 'replace')
405 for repo_file in change.files():
406 title = self._file_to_title(repo_file)
407 yield title, change.rev(), date, author, comment
409 def all_pages(self, type=''):
410 tip = self.repo['tip']
411 """Iterate over the titles of all pages in the wiki."""
412 return [self._file_to_title(filename) for filename in tip
413 if not filename.startswith('.')
414 and filename.endswith(type) ]
416 def revert(self, pageid, rev, **commit_args):
417 """ Make the given version of page the current version (reverting changes). """
419 # Find the old version
420 fctx = self._find_filectx(pageid, rev)
422 # Restore the contents
423 self.save_data(pageid, fctx.data(), **commit_args)