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)
66 def with_storage_locked(func):
67 """A decorator for locking the repository when calling a method."""
69 @functools.wraps(func)
70 def wrapped(self, *args, **kwargs):
71 """Wrap the original function in locks."""
72 lock = self.repo.lock()
74 return func(self, *args, **kwargs)
79 def guess_mime(file_name):
81 Guess file's mime type based on extension.
82 Default of text/x-wiki for files without an extension.
84 >>> guess_mime('something.txt')
86 >>> guess_mime('SomePage')
88 >>> guess_mime(u'ąęśUnicodePage')
90 >>> guess_mime('image.png')
92 >>> guess_mime('style.css')
94 >>> guess_mime('archive.tar.gz')
98 mime, encoding = mimetypes.guess_type(file_name, strict = False)
100 mime = 'archive/%s' % encoding
106 class DocumentNotFound(Exception):
110 class VersionedStorage(object):
112 Provides means of storing text pages and keeping track of their
113 change history, using Mercurial repository as the storage method.
116 def __init__(self, path, charset = None):
118 Takes the path to the directory where the pages are to be kept.
119 If the directory doen't exist, it will be created. If it's inside
120 a Mercurial repository, that repository will be used, otherwise
121 a new repository will be created in it.
124 self.charset = charset or 'utf-8'
126 if not os.path.exists(self.path):
127 os.makedirs(self.path)
128 self.repo_path = find_repo_path(self.path)
130 self.ui = mercurial.ui.ui()
132 self.ui._report_untrusted = False
133 self.ui.setconfig('ui', 'interactive', False)
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):
150 return os.path.join(self.path, urlquote(title, safe = ''))
152 def _title_to_file(self, title):
153 return os.path.join(self.repo_prefix, urlquote(title, safe = ''))
155 def _file_to_title(self, filename):
156 assert filename.startswith(self.repo_prefix)
157 name = filename[len(self.repo_prefix):].strip('/')
158 return urlunquote(name)
160 def __contains__(self, title):
161 return urlquote(title) in self.repo['tip']
164 return self.all_pages()
166 def merge_changes(self, changectx, repo_file, text, user, parent):
167 """Commits and merges conflicting changes in the repository."""
168 tip_node = changectx.node()
169 filectx = changectx[repo_file].filectx(parent)
170 parent_node = filectx.changectx().node()
172 self.repo.dirstate.setparents(parent_node)
173 node = self._commit([repo_file], text, user)
175 partial = lambda filename: repo_file == filename
177 # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
178 p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
183 mercurial.merge.update(self.repo, tip_node, True, False, partial)
184 msg = 'merge of edit conflict'
185 except mercurial.util.Abort:
186 msg = 'failed merge of edit conflict'
188 self.repo.dirstate.setparents(tip_node, node)
189 # Mercurial 1.1 and later need updating the merge state
191 mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
192 except (AttributeError, KeyError):
196 @with_working_copy_locked
198 def save_file(self, title, file_name, author = u'', comment = u'', parent = None):
199 """Save an existing file as specified page."""
200 user = author.encode('utf-8') or u'anonymous'.encode('utf-8')
201 text = comment.encode('utf-8') or u'comment'.encode('utf-8')
203 repo_file = self._title_to_file(title)
204 file_path = self._file_path(title)
205 mercurial.util.rename(file_name, file_path)
206 changectx = self._changectx()
209 filectx_tip = changectx[repo_file]
210 current_page_rev = filectx_tip.filerev()
211 except mercurial.revlog.LookupError:
212 self.repo.add([repo_file])
213 current_page_rev = -1
215 if parent is not None and current_page_rev != parent:
216 msg = self.merge_changes(changectx, repo_file, text, user, parent)
218 text = msg.encode('utf-8')
220 self._commit([repo_file], text, user)
223 def save_data(self, title, data, **kwargs):
224 """Save data as specified page."""
226 temp_path = tempfile.mkdtemp(dir = self.path)
227 file_path = os.path.join(temp_path, 'saved')
228 f = open(file_path, "wb")
231 self.save_file(title = title, file_name = file_path, **kwargs)
242 def save_text(self, text, **kwargs):
243 """Save text as specified page, encoded to charset."""
244 self.save_data(data = text.encode(self.charset), **kwargs)
247 def _commit(self, files, text, user):
248 match = mercurial.match.exact(self.repo_path, '', list(files))
249 return self.repo.commit(match = match, text = text, user = user, force = True)
251 def page_text(self, title):
252 """Read unicode text of a page."""
253 data = self.open_page(title).read()
254 text = unicode(data, self.charset, 'replace')
257 def page_lines(self, page):
259 yield unicode(data, self.charset, 'replace')
261 @with_working_copy_locked
263 def delete_page(self, title, author = u'', comment = u''):
264 user = author.encode('utf-8') or 'anon'
265 text = comment.encode('utf-8') or 'deleted'
266 repo_file = self._title_to_file(title)
267 file_path = self._file_path(title)
272 self.repo.remove([repo_file])
273 self._commit([repo_file], text, user)
275 @with_working_copy_locked
276 def open_page(self, title):
277 if title not in self:
278 raise DocumentNotFound()
280 path = self._title_to_file(title)
281 logger.debug("Opening page %s", path)
283 return self.repo.wfile(path, 'rb')
285 logger.exception("Failed to open page %s", title)
286 raise DocumentNotFound()
288 @with_working_copy_locked
289 def page_file_meta(self, title):
290 """Get page's inode number, size and last modification time."""
292 (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
293 st_atime, st_mtime, st_ctime) = os.stat(self._file_path(title))
296 return st_ino, st_size, st_mtime
298 @with_working_copy_locked
299 def page_meta(self, title):
300 """Get page's revision, date, last editor and his edit comment."""
301 if not title in self:
302 raise DocumentNotFound()
304 filectx_tip = self._find_filectx(title)
305 if filectx_tip is None:
306 raise DocumentNotFound()
307 rev = filectx_tip.filerev()
308 filectx = filectx_tip.filectx(rev)
309 date = datetime.datetime.fromtimestamp(filectx.date()[0])
310 author = unicode(filectx.user(), "utf-8",
311 'replace').split('<')[0].strip()
312 comment = unicode(filectx.description(), "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):
329 """Find the last revision in which the file existed."""
331 repo_file = self._title_to_file(title)
332 changectx = self._changectx()
334 while repo_file not in changectx:
337 changectx = stack.pop()
338 for parent in changectx.parents():
339 if parent != changectx:
341 return changectx[repo_file]
343 def page_history(self, title):
344 """Iterate over the page's history."""
346 filectx_tip = self._find_filectx(title)
347 if filectx_tip is None:
349 maxrev = filectx_tip.filerev()
351 for rev in range(maxrev, minrev - 1, -1):
352 filectx = filectx_tip.filectx(rev)
353 date = datetime.datetime.fromtimestamp(filectx.date()[0])
354 author = unicode(filectx.user(), "utf-8",
355 'replace').split('<')[0].strip()
356 comment = unicode(filectx.description(), "utf-8", 'replace')
357 tags = filectx.changectx().tags()
362 "description": comment,
363 "tag": tags[0] if tags else None,
366 def page_revision(self, title, rev):
367 """Get unicode contents of specified revision of the page."""
369 filectx_tip = self._find_filectx(title)
370 if filectx_tip is None:
371 raise DocumentNotFound()
373 data = filectx_tip.filectx(rev).data()
375 raise DocumentNotFound()
378 def revision_text(self, title, rev):
379 data = self.page_revision(title, rev)
380 text = unicode(data, self.charset, 'replace')
384 """Iterate over the history of entire wiki."""
386 changectx = self._changectx()
387 maxrev = changectx.rev()
389 for wiki_rev in range(maxrev, minrev - 1, -1):
390 change = self.repo.changectx(wiki_rev)
391 date = datetime.datetime.fromtimestamp(change.date()[0])
392 author = unicode(change.user(), "utf-8",
393 'replace').split('<')[0].strip()
394 comment = unicode(change.description(), "utf-8", 'replace')
395 for repo_file in change.files():
396 if repo_file.startswith(self.repo_prefix):
397 title = self._file_to_title(repo_file)
399 rev = change[repo_file].filerev()
400 except mercurial.revlog.LookupError:
402 yield title, rev, date, author, comment
405 tip = self.repo['tip']
406 """Iterate over the titles of all pages in the wiki."""
407 return [ urlunquote(filename) for filename in tip ]
409 def changed_since(self, rev):
410 """Return all pages that changed since specified repository revision."""
413 last = self.repo.lookup(int(rev))
415 for page in self.all_pages():
418 current = self.repo.lookup('tip')
419 status = self.repo.status(current, last)
420 modified, added, removed, deleted, unknown, ignored, clean = status
421 for filename in modified + added + removed + deleted:
422 if filename.startswith(self.repo_prefix):
423 yield self._file_to_title(filename)