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"
22 import mercurial.revlog
26 def urlquote(url, safe='/'):
29 >>> urlquote(u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144')
30 'Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84'
32 return urllib.quote(url.replace(' ', '_').encode('utf-8', 'ignore'), safe)
38 # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
39 # u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144'
41 return unicode(urllib.unquote(url), 'utf-8', 'ignore').replace('_', ' ')
44 def find_repo_path(path):
45 """Go up the directory tree looking for a Mercurial repository (a directory containing a .hg subdirectory)."""
46 while not os.path.isdir(os.path.join(path, ".hg")):
47 old_path, path = path, os.path.dirname(path)
53 def with_working_copy_locked(func):
54 """A decorator for locking the repository when calling a method."""
56 @functools.wraps(func)
57 def wrapped(self, *args, **kwargs):
58 """Wrap the original function in locks."""
59 wlock = self.repo.wlock()
61 return func(self, *args, **kwargs)
67 def with_storage_locked(func):
68 """A decorator for locking the repository when calling a method."""
70 @functools.wraps(func)
71 def wrapped(self, *args, **kwargs):
72 """Wrap the original function in locks."""
73 lock = self.repo.lock()
75 return func(self, *args, **kwargs)
81 def guess_mime(file_name):
83 Guess file's mime type based on extension.
84 Default of text/x-wiki for files without an extension.
86 >>> guess_mime('something.txt')
88 >>> guess_mime('SomePage')
90 >>> guess_mime(u'ąęśUnicodePage')
92 >>> guess_mime('image.png')
94 >>> guess_mime('style.css')
96 >>> guess_mime('archive.tar.gz')
100 mime, encoding = mimetypes.guess_type(file_name, strict=False)
102 mime = 'archive/%s' % encoding
108 class DocumentNotFound(Exception):
112 class VersionedStorage(object):
114 Provides means of storing text pages and keeping track of their
115 change history, using Mercurial repository as the storage method.
118 def __init__(self, path, charset=None):
120 Takes the path to the directory where the pages are to be kept.
121 If the directory doen't exist, it will be created. If it's inside
122 a Mercurial repository, that repository will be used, otherwise
123 a new repository will be created in it.
126 self.charset = charset or 'utf-8'
128 if not os.path.exists(self.path):
129 os.makedirs(self.path)
130 self.repo_path = find_repo_path(self.path)
132 self.ui = mercurial.ui.ui()
134 self.ui._report_untrusted = False
135 self.ui.setconfig('ui', 'interactive', False)
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):
152 return os.path.join(self.path, urlquote(title, safe=''))
154 def _title_to_file(self, title):
155 return os.path.join(self.repo_prefix, urlquote(title, safe=''))
157 def _file_to_title(self, filename):
158 assert filename.startswith(self.repo_prefix)
159 name = filename[len(self.repo_prefix):].strip('/')
160 return urlunquote(name)
162 def __contains__(self, title):
163 return urlquote(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.filerev()
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 self._commit([repo_file], comment, author)
226 def save_data(self, title, data, **kwargs):
227 """Save data as specified page."""
229 temp_path = tempfile.mkdtemp(dir=self.path)
230 file_path = os.path.join(temp_path, 'saved')
231 f = open(file_path, "wb")
235 return self.save_file(title=title, file_name=file_path, **kwargs)
246 def save_text(self, **kwargs):
247 """Save text as specified page, encoded to charset."""
248 text = kwargs.pop('text')
249 return self.save_data(data=text.encode(self.charset), **kwargs)
251 def _commit(self, files, comment, user):
252 match = mercurial.match.exact(self.repo_path, '', list(files))
253 return self.repo.commit(match=match, text=comment, user=user, force=True)
255 @with_working_copy_locked
257 def delete_page(self, title, author=u'', comment=u''):
258 user = author.encode('utf-8') or 'anon'
259 text = comment.encode('utf-8') or 'deleted'
260 repo_file = self._title_to_file(title)
261 file_path = self._file_path(title)
266 self.repo.remove([repo_file])
267 self._commit([repo_file], text, user)
269 def page_text(self, title, revision=None):
270 """Read unicode text of a page."""
271 ctx = self._find_filectx(title, revision)
274 raise DocumentNotFound(title)
276 return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
278 def page_text_by_tag(self, title, tag):
279 """Read unicode text of a taged page."""
280 fname = self._title_to_file(title)
281 tag = u"{fname}#{tag}".format(**locals()).encode('utf-8')
284 ctx = self.repo[tag][fname]
285 return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
287 raise DocumentNotFound(fname)
289 @with_working_copy_locked
290 def page_file_meta(self, title):
291 """Get page's inode number, size and last modification time."""
293 (_st_mode, st_ino, _st_dev, _st_nlink, _st_uid, _st_gid, st_size,
294 _st_atime, st_mtime, _st_ctime) = os.stat(self._file_path(title))
297 return st_ino, st_size, st_mtime
299 @with_working_copy_locked
300 def page_meta(self, title):
301 """Get page's revision, date, last editor and his edit comment."""
302 if not title in self:
303 raise DocumentNotFound(title)
305 filectx_tip = self._find_filectx(title)
306 if filectx_tip is None:
307 raise DocumentNotFound(title)
308 rev = filectx_tip.filerev()
309 filectx = filectx_tip.filectx(rev)
310 date = datetime.datetime.fromtimestamp(filectx.date()[0])
311 author = filectx.user().decode("utf-8", 'replace')
312 comment = filectx.description().decode("utf-8", 'replace')
313 return rev, date, author, comment
315 def repo_revision(self):
316 return self.repo['tip'].rev()
318 def _changectx(self):
319 return self.repo['tip']
321 def page_mime(self, title):
323 Guess page's mime type based on corresponding file name.
324 Default ot text/x-wiki for files without an extension.
326 return guess_mime(self._file_path(title))
328 def _find_filectx(self, title, rev=None):
329 """Find the last revision in which the file existed."""
330 repo_file = self._title_to_file(title)
331 changectx = self._changectx() # start with tip
334 while repo_file not in changectx:
338 changectx = stack.pop()
339 for parent in changectx.parents():
340 if parent != changectx:
344 fctx = changectx[repo_file]
347 fctx = fctx.filectx(rev)
351 except (IndexError, LookupError) as e:
352 raise DocumentNotFound(title)
354 def page_history(self, title):
355 """Iterate over the page's history."""
357 filectx_tip = self._find_filectx(title)
359 maxrev = filectx_tip.filerev()
361 for rev in range(maxrev, minrev - 1, -1):
362 filectx = filectx_tip.filectx(rev)
363 date = datetime.datetime.fromtimestamp(filectx.date()[0])
364 author = filectx.user().decode('utf-8', 'replace')
365 comment = filectx.description().decode("utf-8", 'replace')
366 tags = [t.rsplit('#', 1)[-1] for t in filectx.changectx().tags() if '#' in t]
372 "description": comment,
376 @with_working_copy_locked
377 def add_page_tag(self, title, rev, tag, user, doctag=True):
378 ctitle = self._title_to_file(title)
381 tag = u"{ctitle}#{tag}".format(**locals()).encode('utf-8')
383 message = u"Assigned tag {tag!r} to version {rev!r} of {ctitle!r}".format(**locals()).encode('utf-8')
385 fctx = self._find_filectx(title, rev)
387 names=tag, node=fctx.node(), local=False,
388 user=user, message=message, date=None,
392 """Iterate over the history of entire wiki."""
394 changectx = self._changectx()
395 maxrev = changectx.rev()
397 for wiki_rev in range(maxrev, minrev - 1, -1):
398 change = self.repo.changectx(wiki_rev)
399 date = datetime.datetime.fromtimestamp(change.date()[0])
400 author = change.user().decode('utf-8', 'replace')
401 comment = change.description().decode("utf-8", 'replace')
402 for repo_file in change.files():
403 if repo_file.startswith(self.repo_prefix):
404 title = self._file_to_title(repo_file)
406 rev = change[repo_file].filerev()
407 except mercurial.revlog.LookupError:
409 yield title, rev, date, author, comment
412 tip = self.repo['tip']
413 """Iterate over the titles of all pages in the wiki."""
414 return [urlunquote(filename) for filename in tip]
416 def changed_since(self, rev):
417 """Return all pages that changed since specified repository revision."""
420 last = self.repo.lookup(int(rev))
422 for page in self.all_pages():
425 current = self.repo.lookup('tip')
426 status = self.repo.status(current, last)
427 modified, added, removed, deleted, unknown, ignored, clean = status
428 for filename in modified + added + removed + deleted:
429 if filename.startswith(self.repo_prefix):
430 yield self._file_to_title(filename)