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