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