Coding style overhaul for Python files (PEP8 conformant). Removed buggy csstidy pytho...
[redakcja.git] / lib / vstorage.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 import os
7 import tempfile
8 import datetime
9 import mimetypes
10 import urllib
11 import functools
12
13 import logging
14 logger = logging.getLogger('fnp.hazlenut.vstorage')
15
16 # Note: we have to set these before importing Mercurial
17 os.environ['HGENCODING'] = 'utf-8'
18 os.environ['HGMERGE'] = "internal:merge"
19
20 import mercurial.hg
21 import mercurial.ui
22 import mercurial.revlog
23 import mercurial.util
24
25
26 def urlquote(url, safe='/'):
27     """Quotes URL
28
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'
31     """
32     return urllib.quote(url.replace(' ', '_').encode('utf-8', 'ignore'), safe)
33
34
35 def urlunquote(url):
36     """Unqotes URL
37
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'
40     """
41     return unicode(urllib.unquote(url), 'utf-8', 'ignore').replace('_', ' ')
42
43
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)
48         if path == old_path:
49             return None
50     return path
51
52
53 def with_working_copy_locked(func):
54     """A decorator for locking the repository when calling a method."""
55
56     @functools.wraps(func)
57     def wrapped(self, *args, **kwargs):
58         """Wrap the original function in locks."""
59         wlock = self.repo.wlock()
60         try:
61             return func(self, *args, **kwargs)
62         finally:
63             wlock.release()
64     return wrapped
65
66
67 def with_storage_locked(func):
68     """A decorator for locking the repository when calling a method."""
69
70     @functools.wraps(func)
71     def wrapped(self, *args, **kwargs):
72         """Wrap the original function in locks."""
73         lock = self.repo.lock()
74         try:
75             return func(self, *args, **kwargs)
76         finally:
77             lock.release()
78     return wrapped
79
80
81 def guess_mime(file_name):
82     """
83     Guess file's mime type based on extension.
84     Default of text/x-wiki for files without an extension.
85
86     >>> guess_mime('something.txt')
87     'text/plain'
88     >>> guess_mime('SomePage')
89     'text/x-wiki'
90     >>> guess_mime(u'ąęśUnicodePage')
91     'text/x-wiki'
92     >>> guess_mime('image.png')
93     'image/png'
94     >>> guess_mime('style.css')
95     'text/css'
96     >>> guess_mime('archive.tar.gz')
97     'archive/gzip'
98     """
99
100     mime, encoding = mimetypes.guess_type(file_name, strict=False)
101     if encoding:
102         mime = 'archive/%s' % encoding
103     if mime is None:
104         mime = 'text/x-wiki'
105     return mime
106
107
108 class DocumentNotFound(Exception):
109     pass
110
111
112 class VersionedStorage(object):
113     """
114     Provides means of storing text pages and keeping track of their
115     change history, using Mercurial repository as the storage method.
116     """
117
118     def __init__(self, path, charset=None):
119         """
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.
124         """
125
126         self.charset = charset or 'utf-8'
127         self.path = path
128         if not os.path.exists(self.path):
129             os.makedirs(self.path)
130         self.repo_path = find_repo_path(self.path)
131
132         self.ui = mercurial.ui.ui()
133         self.ui.quiet = True
134         self.ui._report_untrusted = False
135         self.ui.setconfig('ui', 'interactive', False)
136
137         if self.repo_path is None:
138             self.repo_path = self.path
139             create = True
140         else:
141             create = False
142
143         self.repo_prefix = self.path[len(self.repo_path):].strip('/')
144         self.repo = mercurial.hg.repository(self.ui, self.repo_path,
145                                             create=create)
146
147     def reopen(self):
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)
150
151     def _file_path(self, title):
152         return os.path.join(self.path, urlquote(title, safe=''))
153
154     def _title_to_file(self, title):
155         return os.path.join(self.repo_prefix, urlquote(title, safe=''))
156
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)
161
162     def __contains__(self, title):
163         return urlquote(title) in self.repo['tip']
164
165     def __iter__(self):
166         return self.all_pages()
167
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()
173
174         self.repo.dirstate.setparents(parent_node)
175         node = self._commit([repo_file], text, user)
176
177         partial = lambda filename: repo_file == filename
178
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]
181         if p1 == p2:
182             return text
183
184         try:
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'
189
190         self.repo.dirstate.setparents(tip_node, node)
191         # Mercurial 1.1 and later need updating the merge state
192         try:
193             mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
194         except (AttributeError, KeyError):
195             pass
196         return msg
197
198     @with_working_copy_locked
199     @with_storage_locked
200     def save_file(self, title, file_name, author=u'', comment=u'', parent=None):
201         """Save an existing file as specified page."""
202         user = author.encode('utf-8') or u'anonymous'.encode('utf-8')
203         text = comment.encode('utf-8') or u'comment'.encode('utf-8')
204
205         repo_file = self._title_to_file(title)
206         file_path = self._file_path(title)
207         mercurial.util.rename(file_name, file_path)
208         changectx = self._changectx()
209
210         try:
211             filectx_tip = changectx[repo_file]
212             current_page_rev = filectx_tip.filerev()
213         except mercurial.revlog.LookupError:
214             self.repo.add([repo_file])
215             current_page_rev = -1
216
217         if parent is not None and current_page_rev != parent:
218             msg = self.merge_changes(changectx, repo_file, text, user, parent)
219             user = '<wiki>'
220             text = msg.encode('utf-8')
221
222         self._commit([repo_file], text, user)
223
224     def save_data(self, title, data, **kwargs):
225         """Save data as specified page."""
226         try:
227             temp_path = tempfile.mkdtemp(dir=self.path)
228             file_path = os.path.join(temp_path, 'saved')
229             f = open(file_path, "wb")
230             f.write(data)
231             f.close()
232             self.save_file(title=title, file_name=file_path, **kwargs)
233         finally:
234             try:
235                 os.unlink(file_path)
236             except OSError:
237                 pass
238             try:
239                 os.rmdir(temp_path)
240             except OSError:
241                 pass
242
243     def save_text(self, text, **kwargs):
244         """Save text as specified page, encoded to charset."""
245         self.save_data(data=text.encode(self.charset), **kwargs)
246
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)
250
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')
255         return text
256
257     def page_lines(self, page):
258         for data in page:
259             yield unicode(data, self.charset, 'replace')
260
261     @with_working_copy_locked
262     @with_storage_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)
268         try:
269             os.unlink(file_path)
270         except OSError:
271             pass
272         self.repo.remove([repo_file])
273         self._commit([repo_file], text, user)
274
275     @with_working_copy_locked
276     def open_page(self, title):
277         if title not in self:
278             raise DocumentNotFound()
279
280         path = self._title_to_file(title)
281         logger.debug("Opening page %s", path)
282         try:
283             return self.repo.wfile(path, 'rb')
284         except IOError:
285             logger.exception("Failed to open page %s", title)
286             raise DocumentNotFound()
287
288     @with_working_copy_locked
289     def page_file_meta(self, title):
290         """Get page's inode number, size and last modification time."""
291         try:
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))
294         except OSError:
295             return 0, 0, 0
296         return st_ino, st_size, st_mtime
297
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()
303
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
314
315     def repo_revision(self):
316         return self.repo['tip'].rev()
317
318     def _changectx(self):
319         return self.repo['tip']
320
321     def page_mime(self, title):
322         """
323         Guess page's mime type based on corresponding file name.
324         Default ot text/x-wiki for files without an extension.
325         """
326         return guess_mime(self._file_path(title))
327
328     def _find_filectx(self, title, rev=None):
329         """Find the last revision in which the file existed."""
330
331         repo_file = self._title_to_file(title)
332         changectx = self._changectx()
333         stack = [changectx]
334         while repo_file not in changectx:
335             if not stack:
336                 return None
337             changectx = stack.pop()
338             for parent in changectx.parents():
339                 if parent != changectx:
340                     stack.append(parent)
341
342         try:
343             fctx = changectx[repo_file]
344             return fctx if rev is None else fctx.filectx(rev)
345         except IndexError, LookupError:
346             raise DocumentNotFound()
347
348     def page_history(self, title):
349         """Iterate over the page's history."""
350
351         filectx_tip = self._find_filectx(title)
352
353         maxrev = filectx_tip.filerev()
354         minrev = 0
355         for rev in range(maxrev, minrev - 1, -1):
356             filectx = filectx_tip.filectx(rev)
357             date = datetime.datetime.fromtimestamp(filectx.date()[0])
358             author = unicode(filectx.user(), "utf-8",
359                              'replace').split('<')[0].strip()
360             comment = unicode(filectx.description(), "utf-8", 'replace')
361             tags = [t.rsplit('#', 1)[-1] for t in filectx.changectx().tags() if '#' in t]
362
363             yield {
364                 "version": rev,
365                 "date": date,
366                 "author": author,
367                 "description": comment,
368                 "tag": tags,
369             }
370
371     def page_revision(self, title, rev):
372         """Get unicode contents of specified revision of the page."""
373         return self._find_filectx(title, rev).data()
374
375     def revision_text(self, title, rev):
376         data = self.page_revision(title, rev)
377         text = unicode(data, self.charset, 'replace')
378         return text
379
380     @with_working_copy_locked
381     def add_page_tag(self, title, rev, tag, user="<wiki>", doctag=True):
382         if doctag:
383             tag = "{title}#{tag}".format(**locals())
384
385         message = "Assigned tag {tag} to version {rev} of {title}".format(**locals())
386
387         fctx = self._find_filectx(title, rev)
388         self.repo.tag(
389             names=tag, node=fctx.node(), local=False,
390             user=user, message=message, date=None,
391         )
392
393     def history(self):
394         """Iterate over the history of entire wiki."""
395
396         changectx = self._changectx()
397         maxrev = changectx.rev()
398         minrev = 0
399         for wiki_rev in range(maxrev, minrev - 1, -1):
400             change = self.repo.changectx(wiki_rev)
401             date = datetime.datetime.fromtimestamp(change.date()[0])
402             author = unicode(change.user(), "utf-8",
403                              'replace').split('<')[0].strip()
404             comment = unicode(change.description(), "utf-8", 'replace')
405             for repo_file in change.files():
406                 if repo_file.startswith(self.repo_prefix):
407                     title = self._file_to_title(repo_file)
408                     try:
409                         rev = change[repo_file].filerev()
410                     except mercurial.revlog.LookupError:
411                         rev = -1
412                     yield title, rev, date, author, comment
413
414     def all_pages(self):
415         tip = self.repo['tip']
416         """Iterate over the titles of all pages in the wiki."""
417         return [urlunquote(filename) for filename in tip]
418
419     def changed_since(self, rev):
420         """Return all pages that changed since specified repository revision."""
421
422         try:
423             last = self.repo.lookup(int(rev))
424         except IndexError:
425             for page in self.all_pages():
426                 yield page
427                 return
428         current = self.repo.lookup('tip')
429         status = self.repo.status(current, last)
430         modified, added, removed, deleted, unknown, ignored, clean = status
431         for filename in modified + added + removed + deleted:
432             if filename.startswith(self.repo_prefix):
433                 yield self._file_to_title(filename)