Bugfix.
[redakcja.git] / lib / vstorage / __init__.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.revlog
22 import mercurial.util
23
24 from vstorage.hgui import SilentUI
25
26
27 def urlquote(url, safe='/'):
28     """Quotes URL
29
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'
32     """
33     return urllib.quote(url.encode('utf-8', 'ignore'), safe)
34
35
36 def urlunquote(url):
37     """Unqotes URL
38
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'
41     """
42     return unicode(urllib.unquote(url), 'utf-8', 'ignore')
43
44
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)
49         if path == old_path:
50             return None
51     return path
52
53
54 def with_working_copy_locked(func):
55     """A decorator for locking the repository when calling a method."""
56
57     @functools.wraps(func)
58     def wrapped(self, *args, **kwargs):
59         """Wrap the original function in locks."""
60         wlock = self.repo.wlock()
61         try:
62             return func(self, *args, **kwargs)
63         finally:
64             wlock.release()
65     return wrapped
66
67
68 def with_storage_locked(func):
69     """A decorator for locking the repository when calling a method."""
70
71     @functools.wraps(func)
72     def wrapped(self, *args, **kwargs):
73         """Wrap the original function in locks."""
74         lock = self.repo.lock()
75         try:
76             return func(self, *args, **kwargs)
77         finally:
78             lock.release()
79     return wrapped
80
81
82 def guess_mime(file_name):
83     """
84     Guess file's mime type based on extension.
85     Default of text/x-wiki for files without an extension.
86
87     >>> guess_mime('something.txt')
88     'text/plain'
89     >>> guess_mime('SomePage')
90     'text/x-wiki'
91     >>> guess_mime(u'ąęśUnicodePage')
92     'text/x-wiki'
93     >>> guess_mime('image.png')
94     'image/png'
95     >>> guess_mime('style.css')
96     'text/css'
97     >>> guess_mime('archive.tar.gz')
98     'archive/gzip'
99     """
100
101     mime, encoding = mimetypes.guess_type(file_name, strict=False)
102     if encoding:
103         mime = 'archive/%s' % encoding
104     if mime is None:
105         mime = 'text/x-wiki'
106     return mime
107
108
109 class DocumentNotFound(Exception):
110     pass
111
112
113 class VersionedStorage(object):
114     """
115     Provides means of storing text pages and keeping track of their
116     change history, using Mercurial repository as the storage method.
117     """
118
119     def __init__(self, path, charset=None):
120         """
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.
125         """
126
127         self.charset = charset or 'utf-8'
128         self.path = path
129         if not os.path.exists(self.path):
130             os.makedirs(self.path)
131         self.repo_path = find_repo_path(self.path)
132
133         self.ui = SilentUI()
134
135         if self.repo_path is None:
136             self.repo_path = self.path
137             create = True
138         else:
139             create = False
140
141         self.repo_prefix = self.path[len(self.repo_path):].strip('/')
142         self.repo = mercurial.hg.repository(self.ui, self.repo_path,
143                                             create=create)
144
145     def reopen(self):
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)
148
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']:
153             path += type
154         return path
155
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']:
160             path += type
161         return path
162
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)
167
168     def __contains__(self, title):
169         return self._title_to_file(title) in self.repo['tip']
170
171     def __iter__(self):
172         return self.all_pages()
173
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()
179
180         self.repo.dirstate.setparents(parent_node)
181         node = self._commit([repo_file], text, user)
182
183         partial = lambda filename: repo_file == filename
184
185         # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
186         p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
187         if p1 == p2:
188             return text
189
190         try:
191             mercurial.merge.update(self.repo, tip_node, True, False, partial)
192             msg = 'merge of edit conflict'
193         except mercurial.util.Abort:
194             msg = 'failed merge of edit conflict'
195
196         self.repo.dirstate.setparents(tip_node, node)
197         # Mercurial 1.1 and later need updating the merge state
198         try:
199             mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
200         except (AttributeError, KeyError):
201             pass
202         return msg
203
204     @with_working_copy_locked
205     @with_storage_locked
206     def save_file(self, title, file_name, **kwargs):
207         """Save an existing file as specified page."""
208
209         author = kwargs.get('author', u'anonymous').encode('utf-8')
210         comment = kwargs.get('comment', u'Empty comment.').encode('utf-8')
211         parent = kwargs.get('parent', None)
212
213         repo_file = self._title_to_file(title)
214         file_path = self._file_path(title)
215         mercurial.util.rename(file_name, file_path)
216         changectx = self._changectx()
217
218         try:
219             filectx_tip = changectx[repo_file]
220             current_page_rev = filectx_tip.filerev()
221         except mercurial.revlog.LookupError:
222             self.repo[None].add([repo_file])
223             current_page_rev = -1
224
225         if parent is not None and current_page_rev != parent:
226             msg = self.merge_changes(changectx, repo_file, comment, author, parent)
227             author = '<wiki>'
228             comment = msg.encode('utf-8')
229
230         logger.debug("Commiting %r", repo_file)
231
232         self._commit([repo_file], comment, author)
233
234     def save_data(self, title, data, **kwargs):
235         """Save data as specified page."""
236         try:
237             temp_path = tempfile.mkdtemp(dir=self.path)
238             file_path = os.path.join(temp_path, 'saved')
239             f = open(file_path, "wb")
240             f.write(data)
241             f.close()
242
243             return self.save_file(title=title, file_name=file_path, **kwargs)
244         finally:
245             try:
246                 os.unlink(file_path)
247             except OSError:
248                 pass
249             try:
250                 os.rmdir(temp_path)
251             except OSError:
252                 pass
253
254     def save_text(self, **kwargs):
255         """Save text as specified page, encoded to charset."""
256         text = kwargs.pop('text')
257         return self.save_data(data=text.encode(self.charset), **kwargs)
258
259     def _commit(self, files, comment, user):
260         match = mercurial.match.exact(self.repo_path, '', list(files))
261         return self.repo.commit(match=match, text=comment, user=user, force=True)
262
263     @with_working_copy_locked
264     @with_storage_locked
265     def delete_page(self, title, author=u'', comment=u''):
266         user = author.encode('utf-8') or 'anon'
267         text = comment.encode('utf-8') or 'deleted'
268         repo_file = self._title_to_file(title)
269         file_path = self._file_path(title)
270         try:
271             os.unlink(file_path)
272         except OSError:
273             pass
274         self.repo[None].remove([repo_file])
275         self._commit([repo_file], text, user)
276
277     def page_text(self, title, revision=None):
278         """Read unicode text of a page."""
279         ctx = self._find_filectx(title, revision)
280
281         if ctx is None:
282             raise DocumentNotFound(title)
283
284         return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
285
286     def page_text_by_tag(self, title, tag):
287         """Read unicode text of a taged page."""
288         fname = self._title_to_file(title)
289         tag = u"{fname}#{tag}".format(**locals()).encode('utf-8')
290
291         try:
292             ctx = self.repo[tag][fname]
293             return ctx.data().decode(self.charset, 'replace'), ctx.filerev()
294         except IndexError:
295             raise DocumentNotFound(fname)
296
297     @with_working_copy_locked
298     def page_file_meta(self, title):
299         """Get page's inode number, size and last modification time."""
300         try:
301             (_st_mode, st_ino, _st_dev, _st_nlink, _st_uid, _st_gid, st_size,
302              _st_atime, st_mtime, _st_ctime) = os.stat(self._file_path(title))
303         except OSError:
304             return 0, 0, 0
305         return st_ino, st_size, st_mtime
306
307     @with_working_copy_locked
308     def page_meta(self, title, revision=None):
309         """Get page's revision, date, last editor and his edit comment."""
310         fctx = self._find_filectx(title, revision)
311
312         if fctx is None:
313             raise DocumentNotFound(title)
314
315         return {
316             "revision": fctx.filerev(),
317             "date": datetime.datetime.fromtimestamp(fctx.date()[0]),
318             "author": fctx.user().decode("utf-8", 'replace'),
319             "comment": fctx.description().decode("utf-8", 'replace'),
320         }
321
322     def repo_revision(self):
323         return self.repo['tip'].rev()
324
325     def _changectx(self):
326         return self.repo['tip']
327
328     def page_mime(self, title):
329         """
330         Guess page's mime type based on corresponding file name.
331         Default ot text/x-wiki for files without an extension.
332         """
333         return guess_mime(self._file_path(title))
334
335     def _find_filectx(self, title, rev=None):
336         """
337         Find the revision of the file in repo.
338         Only look for files still existing in repo's tip.
339         """
340         tip = self._changectx()
341         file = self._title_to_file(title)
342         logging.info('Looking for %s', file)
343         if file in tip:
344             fctx = tip[file]
345         else:
346             file = self._title_to_file(title, type='')
347             logging.info('.xml not found, trying plain')
348             if file in tip:
349                 fctx = tip[file]
350             else:
351                 raise DocumentNotFound(title)
352
353         if rev is not None:
354             fctx = fctx.filectx(rev)
355             fctx.filerev()
356         return fctx
357
358     def page_history(self, title):
359         """Iterate over the page's history."""
360
361         filectx_tip = self._find_filectx(title)
362
363         maxrev = filectx_tip.filerev()
364         minrev = 0
365         for rev in range(maxrev, minrev - 1, -1):
366             filectx = filectx_tip.filectx(rev)
367             date = datetime.datetime.fromtimestamp(filectx.date()[0])
368             author = filectx.user().decode('utf-8', 'replace')
369             comment = filectx.description().decode("utf-8", 'replace')
370             tags = [t.rsplit('#', 1)[-1] for t in filectx.changectx().tags() if '#' in t]
371
372             yield {
373                 "version": rev,
374                 "date": date,
375                 "author": author,
376                 "description": comment,
377                 "tag": tags,
378             }
379
380     @with_working_copy_locked
381     def add_page_tag(self, title, rev, tag, user, doctag=True):
382         ctitle = self._title_to_file(title)
383
384         if doctag:
385             tag = u"{ctitle}#{tag}".format(**locals()).encode('utf-8')
386
387         message = u"Assigned tag {tag!r} to version {rev!r} of {ctitle!r}".format(**locals()).encode('utf-8')
388
389         fctx = self._find_filectx(title, rev)
390         self.repo.tag(
391             names=tag, node=fctx.node(), local=False,
392             user=user, message=message, date=None,
393         )
394
395     def history(self):
396         """Iterate over the history of entire wiki."""
397
398         changectx = self._changectx()
399         maxrev = changectx.rev()
400         minrev = 0
401         for wiki_rev in range(maxrev, minrev - 1, -1):
402             change = self.repo.changectx(wiki_rev)
403             date = datetime.datetime.fromtimestamp(change.date()[0])
404             author = change.user().decode('utf-8', 'replace')
405             comment = change.description().decode("utf-8", 'replace')
406             for repo_file in change.files():
407                 if repo_file.startswith(self.repo_prefix):
408                     title = self._file_to_title(repo_file)
409                     try:
410                         rev = change[repo_file].filerev()
411                     except mercurial.revlog.LookupError:
412                         rev = -1
413                     yield title, rev, date, author, comment
414
415     def all_pages(self, type=''):
416         tip = self.repo['tip']
417         """Iterate over the titles of all pages in the wiki."""
418         return [self._file_to_title(filename) for filename in tip
419                   if not filename.startswith('.')
420                     and filename.endswith(type) ]
421
422     def changed_since(self, rev):
423         """Return all pages that changed since specified repository revision."""
424
425         try:
426             last = self.repo.lookup(int(rev))
427         except IndexError:
428             for page in self.all_pages():
429                 yield page
430                 return
431         current = self.repo.lookup('tip')
432         status = self.repo.status(current, last)
433         modified, added, removed, deleted, unknown, ignored, clean = status
434         for filename in modified + added + removed + deleted:
435             if filename.startswith(self.repo_prefix):
436                 yield self._file_to_title(filename)
437
438     def revert(self, pageid, rev, **commit_args):
439         """ Make the given version of page the current version (reverting changes). """
440
441         # Find the old version
442         fctx = self._find_filectx(pageid, rev)
443
444         # Restore the contents
445         self.save_data(pageid, fctx.data(), **commit_args)