Poprawki stylu pokazywania przypisów.
[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         print "Checking ", title
148         return urlquote(title) in self.repo.dirstate
149
150     def __iter__(self):
151         return self.all_pages()
152
153     def merge_changes(self, changectx, repo_file, text, user, parent):
154         """Commits and merges conflicting changes in the repository."""
155         tip_node = changectx.node()
156         filectx = changectx[repo_file].filectx(parent)
157         parent_node = filectx.changectx().node()
158
159         self.repo.dirstate.setparents(parent_node)
160         node = self._commit([repo_file], text, user)
161
162         partial = lambda filename: repo_file == filename
163
164         # If p1 is equal to p2, there is no work to do. Even the dirstate is correct.
165         p1, p2 = self.repo[None].parents()[0], self.repo[tip_node]
166         if p1 == p2:
167             return text
168
169         try:
170             mercurial.merge.update(self.repo, tip_node, True, False, partial)
171             msg = 'merge of edit conflict'
172         except mercurial.util.Abort:
173             msg = 'failed merge of edit conflict'
174
175         self.repo.dirstate.setparents(tip_node, node)
176         # Mercurial 1.1 and later need updating the merge state
177         try:
178             mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
179         except (AttributeError, KeyError):
180             pass
181         return msg
182
183     @locked_repo
184     def save_file(self, title, file_name, author = u'', comment = u'', parent = None):
185         """Save an existing file as specified page."""
186
187         user = author.encode('utf-8') or u'anon'.encode('utf-8')
188         text = comment.encode('utf-8') or u'comment'.encode('utf-8')
189         repo_file = self._title_to_file(title)
190         file_path = self._file_path(title)
191         mercurial.util.rename(file_name, file_path)
192         changectx = self._changectx()
193         try:
194             filectx_tip = changectx[repo_file]
195             current_page_rev = filectx_tip.filerev()
196         except mercurial.revlog.LookupError:
197             self.repo.add([repo_file])
198             current_page_rev = -1
199         if parent is not None and current_page_rev != parent:
200             msg = self.merge_changes(changectx, repo_file, text, user, parent)
201             user = '<wiki>'
202             text = msg.encode('utf-8')
203         self._commit([repo_file], text, user)
204
205
206     def _commit(self, files, text, user):
207         try:
208             return self.repo.commit(files = files, text = text, user = user,
209                                     force = True, empty_ok = True)
210         except TypeError:
211             # Mercurial 1.3 doesn't accept empty_ok or files parameter
212             match = mercurial.match.exact(self.repo_path, '', list(files))
213             return self.repo.commit(match = match, text = text, user = user,
214                                     force = True)
215
216
217     def save_data(self, title, data, author = u'', comment = u'', parent = None):
218         """Save data as specified page."""
219
220         try:
221             temp_path = tempfile.mkdtemp(dir = self.path)
222             file_path = os.path.join(temp_path, 'saved')
223             f = open(file_path, "wb")
224             f.write(data)
225             f.close()
226             self.save_file(title, file_path, author, comment, parent)
227         finally:
228             try:
229                 os.unlink(file_path)
230             except OSError:
231                 pass
232             try:
233                 os.rmdir(temp_path)
234             except OSError:
235                 pass
236
237     def save_text(self, title, text, author = u'', comment = u'', parent = None):
238         """Save text as specified page, encoded to charset."""
239
240         data = text.encode(self.charset)
241         self.save_data(title, data, author, comment, parent)
242
243     def page_text(self, title):
244         """Read unicode text of a page."""
245
246         data = self.open_page(title).read()
247         text = unicode(data, self.charset, 'replace')
248         return text
249
250     def page_lines(self, page):
251         for data in page:
252             yield unicode(data, self.charset, 'replace')
253
254     @locked_repo
255     def delete_page(self, title, author = u'', comment = u''):
256         user = author.encode('utf-8') or 'anon'
257         text = comment.encode('utf-8') or 'deleted'
258         repo_file = self._title_to_file(title)
259         file_path = self._file_path(title)
260         try:
261             os.unlink(file_path)
262         except OSError:
263             pass
264         self.repo.remove([repo_file])
265         self._commit([repo_file], text, user)
266
267     def open_page(self, title):
268         if title not in self:
269             raise DocumentNotFound()
270
271         try:
272             return open(self._file_path(title), "rb")
273         except IOError:
274             import traceback
275             print traceback.print_exc()
276             raise DocumentNotFound()
277
278     def page_file_meta(self, title):
279         """Get page's inode number, size and last modification time."""
280
281         try:
282             (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
283              st_atime, st_mtime, st_ctime) = os.stat(self._file_path(title))
284         except OSError:
285             return 0, 0, 0
286         return st_ino, st_size, st_mtime
287
288     def page_meta(self, title):
289         """Get page's revision, date, last editor and his edit comment."""
290         if not title in self:
291             raise DocumentNotFound()
292
293         filectx_tip = self._find_filectx(title)
294         if filectx_tip is None:
295             raise DocumentNotFound()
296         rev = filectx_tip.filerev()
297         filectx = filectx_tip.filectx(rev)
298         date = datetime.datetime.fromtimestamp(filectx.date()[0])
299         author = unicode(filectx.user(), "utf-8",
300                          'replace').split('<')[0].strip()
301         comment = unicode(filectx.description(), "utf-8", 'replace')
302         return rev, date, author, comment
303
304     def repo_revision(self):
305         return self._changectx().rev()
306
307     def page_mime(self, title):
308         """
309         Guess page's mime type based on corresponding file name.
310         Default ot text/x-wiki for files without an extension.
311         """
312         return guess_type(self._file_path(title))
313
314     def _changectx(self):
315         """Get the changectx of the tip."""
316         try:
317             # This is for Mercurial 1.0
318             return self.repo.changectx()
319         except TypeError:
320             # Mercurial 1.3 (and possibly earlier) needs an argument
321             return self.repo.changectx('tip')
322
323     def _find_filectx(self, title):
324         """Find the last revision in which the file existed."""
325
326         repo_file = self._title_to_file(title)
327         changectx = self._changectx()
328         stack = [changectx]
329         while repo_file not in changectx:
330             if not stack:
331                 return None
332             changectx = stack.pop()
333             for parent in changectx.parents():
334                 if parent != changectx:
335                     stack.append(parent)
336         return changectx[repo_file]
337
338     def page_history(self, title):
339         """Iterate over the page's history."""
340
341         filectx_tip = self._find_filectx(title)
342         if filectx_tip is None:
343             return
344         maxrev = filectx_tip.filerev()
345         minrev = 0
346         for rev in range(maxrev, minrev - 1, -1):
347             filectx = filectx_tip.filectx(rev)
348             date = datetime.datetime.fromtimestamp(filectx.date()[0])
349             author = unicode(filectx.user(), "utf-8",
350                              'replace').split('<')[0].strip()
351             comment = unicode(filectx.description(), "utf-8", 'replace')
352             yield rev, date, author, comment
353
354     def page_revision(self, title, rev):
355         """Get unicode contents of specified revision of the page."""
356
357         filectx_tip = self._find_filectx(title)
358         if filectx_tip is None:
359             raise DocumentNotFound()
360         try:
361             data = filectx_tip.filectx(rev).data()
362         except IndexError:
363             raise DocumentNotFound()
364         return data
365
366     def revision_text(self, title, rev):
367         data = self.page_revision(title, rev)
368         text = unicode(data, self.charset, 'replace')
369         return text
370
371     def history(self):
372         """Iterate over the history of entire wiki."""
373
374         changectx = self._changectx()
375         maxrev = changectx.rev()
376         minrev = 0
377         for wiki_rev in range(maxrev, minrev - 1, -1):
378             change = self.repo.changectx(wiki_rev)
379             date = datetime.datetime.fromtimestamp(change.date()[0])
380             author = unicode(change.user(), "utf-8",
381                              'replace').split('<')[0].strip()
382             comment = unicode(change.description(), "utf-8", 'replace')
383             for repo_file in change.files():
384                 if repo_file.startswith(self.repo_prefix):
385                     title = self._file_to_title(repo_file)
386                     try:
387                         rev = change[repo_file].filerev()
388                     except mercurial.revlog.LookupError:
389                         rev = -1
390                     yield title, rev, date, author, comment
391
392     def all_pages(self):
393         """Iterate over the titles of all pages in the wiki."""
394         return [ urlunquote(filename) for filename in self.repo.dirstate]
395         #status = self.repo.status(self.repo[None], None, None, True, True, True)
396         #clean_files = status[6]
397         #for filename in clean_files:
398         #    yield
399
400     def changed_since(self, rev):
401         """Return all pages that changed since specified repository revision."""
402
403         try:
404             last = self.repo.lookup(int(rev))
405         except IndexError:
406             for page in self.all_pages():
407                 yield page
408                 return
409         current = self.repo.lookup('tip')
410         status = self.repo.status(current, last)
411         modified, added, removed, deleted, unknown, ignored, clean = status
412         for filename in modified + added + removed + deleted:
413             if filename.startswith(self.repo_prefix):
414                 yield self._file_to_title(filename)