d67e2c1089670fb59794980124a50fbaaf4107c9
[redakcja.git] / lib / vstorage.py
1 # -*- coding: utf-8 -*-
2 import os
3 import tempfile
4 import datetime
5 import mimetypes
6 import urllib
7
8 # Note: we have to set these before importing Mercurial
9 os.environ['HGENCODING'] = 'utf-8'
10 os.environ['HGMERGE'] = "internal:merge"
11
12 import mercurial.hg
13 import mercurial.ui
14 import mercurial.revlog
15 import mercurial.util
16
17
18 def urlquote(url, safe='/'):
19     """Quotes URL 
20     
21     >>> urlquote(u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144')
22     'Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84'
23     """
24     return urllib.quote(url.replace(' ', '_').encode('utf-8', 'ignore'), safe)
25
26
27 def urlunquote(url):
28     """Unqotes URL 
29     
30     # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
31     # u'Za\u017c\xf3\u0142\u0107 g\u0119\u015bl\u0105 ja\u017a\u0144'
32     """
33     return unicode(urllib.unquote(url), 'utf-8', 'ignore').replace('_', ' ')
34
35
36 def find_repo_path(path):
37     """Go up the directory tree looking for a Mercurial repository (a directory containing a .hg subdirectory)."""
38     while not os.path.isdir(os.path.join(path, ".hg")):
39         old_path, path = path, os.path.dirname(path)
40         if path == old_path:
41             return None
42     return path
43
44
45 def locked_repo(func):
46     """A decorator for locking the repository when calling a method."""
47
48     def new_func(self, *args, **kwargs):
49         """Wrap the original function in locks."""
50
51         wlock = self.repo.wlock()
52         lock = self.repo.lock()
53         try:
54             func(self, *args, **kwargs)
55         finally:
56             lock.release()
57             wlock.release()
58
59     return new_func
60
61
62 def guess_mime(file_name):
63     """
64     Guess file's mime type based on extension.
65     Default ot text/x-wiki for files without an extension.
66
67     >>> guess_mime('something.txt')
68     'text/plain'
69     >>> guess_mime('SomePage')
70     'text/x-wiki'
71     >>> guess_mime(u'ąęśUnicodePage')
72     'text/x-wiki'
73     >>> guess_mime('image.png')
74     'image/png'
75     >>> guess_mime('style.css')
76     'text/css'
77     >>> guess_mime('archive.tar.gz')
78     'archive/gzip'
79     """
80
81     mime, encoding = mimetypes.guess_type(file_name, strict=False)
82     if encoding:
83         mime = 'archive/%s' % encoding
84     if mime is None:
85         mime = 'text/x-wiki'
86     return mime
87
88
89 class DocumentNotFound(Exception):
90     pass
91
92
93 class VersionedStorage(object):
94     """
95     Provides means of storing text pages and keeping track of their
96     change history, using Mercurial repository as the storage method.
97     """
98
99     def __init__(self, path, charset=None):
100         """
101         Takes the path to the directory where the pages are to be kept.
102         If the directory doen't exist, it will be created. If it's inside
103         a Mercurial repository, that repository will be used, otherwise
104         a new repository will be created in it.
105         """
106
107         self.charset = charset or 'utf-8'
108         self.path = path
109         if not os.path.exists(self.path):
110             os.makedirs(self.path)
111         self.repo_path = find_repo_path(self.path)
112         try:
113             self.ui = mercurial.ui.ui(report_untrusted=False,
114                                       interactive=False, quiet=True)
115         except TypeError:
116             # Mercurial 1.3 changed the way we setup the ui object.
117             self.ui = mercurial.ui.ui()
118             self.ui.quiet = True
119             self.ui._report_untrusted = False
120             self.ui.setconfig('ui', 'interactive', False)
121         if self.repo_path is None:
122             self.repo_path = self.path
123             create = True
124         else:
125             create = False
126         self.repo_prefix = self.path[len(self.repo_path):].strip('/')
127         self.repo = mercurial.hg.repository(self.ui, self.repo_path,
128                                             create=create)
129
130     def reopen(self):
131         """Close and reopen the repo, to make sure we are up to date."""
132
133         self.repo = mercurial.hg.repository(self.ui, self.repo_path)
134
135     def _file_path(self, title):
136         return os.path.join(self.path, urlquote(title, safe=''))
137
138     def _title_to_file(self, title):
139         return os.path.join(self.repo_prefix, urlquote(title, safe=''))
140
141     def _file_to_title(self, filename):
142         assert filename.startswith(self.repo_prefix)
143         name = filename[len(self.repo_prefix):].strip('/')
144         return urlunquote(name)
145
146     def __contains__(self, title):
147         return urlquote(title) in self.repo.dirstate
148
149     def __iter__(self):
150         return self.all_pages()        
151         
152     def merge_changes(self, changectx, repo_file, text, user, parent):
153         """Commits and merges conflicting changes in the repository."""
154         tip_node = changectx.node()
155         filectx = changectx[repo_file].filectx(parent)
156         parent_node = filectx.changectx().node()
157
158         self.repo.dirstate.setparents(parent_node)
159         node = self._commit([repo_file], text, user)
160         
161         partial = lambda filename: repo_file == filename
162         
163         # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
164         p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
165         if p1 == p2:
166             return text
167         
168         try:
169             mercurial.merge.update(self.repo, tip_node, True, False, partial)
170             msg = 'merge of edit conflict'
171         except mercurial.util.Abort:
172             msg = 'failed merge of edit conflict'
173         
174         self.repo.dirstate.setparents(tip_node, node)
175         # Mercurial 1.1 and later need updating the merge state
176         try:
177             mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
178         except (AttributeError, KeyError):
179             pass
180         return msg
181
182     @locked_repo
183     def save_file(self, title, file_name, author=u'', comment=u'', parent=None):
184         """Save an existing file as specified page."""
185
186         user = author.encode('utf-8') or u'anon'.encode('utf-8')
187         text = comment.encode('utf-8') or u'comment'.encode('utf-8')
188         repo_file = self._title_to_file(title)
189         file_path = self._file_path(title)
190         mercurial.util.rename(file_name, file_path)
191         changectx = self._changectx()
192         try:
193             filectx_tip = changectx[repo_file]
194             current_page_rev = filectx_tip.filerev()
195         except mercurial.revlog.LookupError:
196             self.repo.add([repo_file])
197             current_page_rev = -1
198         if parent is not None and current_page_rev != parent:
199             msg = self.merge_changes(changectx, repo_file, text, user, parent)
200             user = '<wiki>'
201             text = msg.encode('utf-8')
202         self._commit([repo_file], text, user)
203
204
205     def _commit(self, files, text, user):
206         try:
207             return self.repo.commit(files=files, text=text, user=user,
208                                     force=True, empty_ok=True)
209         except TypeError:
210             # Mercurial 1.3 doesn't accept empty_ok or files parameter
211             match = mercurial.match.exact(self.repo_path, '', list(files))
212             return self.repo.commit(match=match, text=text, user=user,
213                                     force=True)
214
215
216     def save_data(self, title, data, author=u'', comment=u'', parent=None):
217         """Save data as specified page."""
218
219         try:
220             temp_path = tempfile.mkdtemp(dir=self.path)
221             file_path = os.path.join(temp_path, 'saved')
222             f = open(file_path, "wb")
223             f.write(data)
224             f.close()
225             self.save_file(title, file_path, author, comment, parent)
226         finally:
227             try:
228                 os.unlink(file_path)
229             except OSError:
230                 pass
231             try:
232                 os.rmdir(temp_path)
233             except OSError:
234                 pass
235
236     def save_text(self, title, text, author=u'', comment=u'', parent=None):
237         """Save text as specified page, encoded to charset."""
238
239         data = text.encode(self.charset)
240         self.save_data(title, data, author, comment, parent)
241
242     def page_text(self, title):
243         """Read unicode text of a page."""
244
245         data = self.open_page(title).read()
246         text = unicode(data, self.charset, 'replace')
247         return text
248
249     def page_lines(self, page):
250         for data in page:
251             yield unicode(data, self.charset, 'replace')
252
253     @locked_repo
254     def delete_page(self, title, author=u'', comment=u''):
255         user = author.encode('utf-8') or 'anon'
256         text = comment.encode('utf-8') or 'deleted'
257         repo_file = self._title_to_file(title)
258         file_path = self._file_path(title)
259         try:
260             os.unlink(file_path)
261         except OSError:
262             pass
263         self.repo.remove([repo_file])
264         self._commit([repo_file], text, user)
265
266     def open_page(self, title):
267         if title not in self:
268             print 'whatever', list(self.all_pages())
269             raise DocumentNotFound()
270         
271         try:
272             return open(self._file_path(title), "rb")
273         except IOError:
274             raise DocumentNotFound()
275
276     def page_file_meta(self, title):
277         """Get page's inode number, size and last modification time."""
278
279         try:
280             (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
281              st_atime, st_mtime, st_ctime) = os.stat(self._file_path(title))
282         except OSError:
283             return 0, 0, 0
284         return st_ino, st_size, st_mtime
285
286     def page_meta(self, title):
287         """Get page's revision, date, last editor and his edit comment."""
288
289         filectx_tip = self._find_filectx(title)
290         if filectx_tip is None:
291             raise DocumentNotFound()
292             #return -1, None, u'', u''
293         rev = filectx_tip.filerev()
294         filectx = filectx_tip.filectx(rev)
295         date = datetime.datetime.fromtimestamp(filectx.date()[0])
296         author = unicode(filectx.user(), "utf-8",
297                          'replace').split('<')[0].strip()
298         comment = unicode(filectx.description(), "utf-8", 'replace')
299         return rev, date, author, comment
300
301     def repo_revision(self):
302         return self._changectx().rev()
303
304     def page_mime(self, title):
305         """
306         Guess page's mime type based on corresponding file name.
307         Default ot text/x-wiki for files without an extension.
308         """
309         return guess_type(self._file_path(title))
310
311     def _changectx(self):
312         """Get the changectx of the tip."""
313         try:
314             # This is for Mercurial 1.0
315             return self.repo.changectx()
316         except TypeError:
317             # Mercurial 1.3 (and possibly earlier) needs an argument
318             return self.repo.changectx('tip')
319
320     def _find_filectx(self, title):
321         """Find the last revision in which the file existed."""
322
323         repo_file = self._title_to_file(title)
324         changectx = self._changectx()
325         stack = [changectx]
326         while repo_file not in changectx:
327             if not stack:
328                 return None
329             changectx = stack.pop()
330             for parent in changectx.parents():
331                 if parent != changectx:
332                     stack.append(parent)
333         return changectx[repo_file]
334
335     def page_history(self, title):
336         """Iterate over the page's history."""
337
338         filectx_tip = self._find_filectx(title)
339         if filectx_tip is None:
340             return
341         maxrev = filectx_tip.filerev()
342         minrev = 0
343         for rev in range(maxrev, minrev-1, -1):
344             filectx = filectx_tip.filectx(rev)
345             date = datetime.datetime.fromtimestamp(filectx.date()[0])
346             author = unicode(filectx.user(), "utf-8",
347                              'replace').split('<')[0].strip()
348             comment = unicode(filectx.description(), "utf-8", 'replace')
349             yield rev, date, author, comment
350
351     def page_revision(self, title, rev):
352         """Get unicode contents of specified revision of the page."""
353
354         filectx_tip = self._find_filectx(title)
355         if filectx_tip is None:
356             raise DocumentNotFound()
357         try:
358             data = filectx_tip.filectx(rev).data()
359         except IndexError:
360             raise DocumentNotFound()
361         return data
362
363     def revision_text(self, title, rev):
364         data = self.page_revision(title, rev)
365         text = unicode(data, self.charset, 'replace')
366         return text
367
368     def history(self):
369         """Iterate over the history of entire wiki."""
370
371         changectx = self._changectx()
372         maxrev = changectx.rev()
373         minrev = 0
374         for wiki_rev in range(maxrev, minrev-1, -1):
375             change = self.repo.changectx(wiki_rev)
376             date = datetime.datetime.fromtimestamp(change.date()[0])
377             author = unicode(change.user(), "utf-8",
378                              'replace').split('<')[0].strip()
379             comment = unicode(change.description(), "utf-8", 'replace')
380             for repo_file in change.files():
381                 if repo_file.startswith(self.repo_prefix):
382                     title = self._file_to_title(repo_file)
383                     try:
384                         rev = change[repo_file].filerev()
385                     except mercurial.revlog.LookupError:
386                         rev = -1
387                     yield title, rev, date, author, comment
388
389     def all_pages(self):
390         """Iterate over the titles of all pages in the wiki."""
391         status = self.repo.status(self.repo[None], None, None, True, True, True)
392         clean_files = status[6]
393         for filename in clean_files:
394             yield urlunquote(filename)
395
396     def changed_since(self, rev):
397         """Return all pages that changed since specified repository revision."""
398
399         try:
400             last = self.repo.lookup(int(rev))
401         except IndexError:
402             for page in self.all_pages():
403                 yield page
404                 return
405         current = self.repo.lookup('tip')
406         status = self.repo.status(current, last)
407         modified, added, removed, deleted, unknown, ignored, clean = status
408         for filename in modified+added+removed+deleted:
409             if filename.startswith(self.repo_prefix):
410                 yield self._file_to_title(filename)