1 # -*- coding: utf-8 -*-
8 # Note: we have to set these before importing Mercurial
9 os.environ['HGENCODING'] = 'utf-8'
10 os.environ['HGMERGE'] = "internal:merge"
14 import mercurial.revlog
18 def urlquote(url, safe='/'):
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'
24 return urllib.quote(url.replace(' ', '_').encode('utf-8', 'ignore'), safe)
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'
33 return unicode(urllib.unquote(url), 'utf-8', 'ignore').replace('_', ' ')
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)
45 def locked_repo(func):
46 """A decorator for locking the repository when calling a method."""
48 def new_func(self, *args, **kwargs):
49 """Wrap the original function in locks."""
51 wlock = self.repo.wlock()
52 lock = self.repo.lock()
54 func(self, *args, **kwargs)
62 def guess_mime(file_name):
64 Guess file's mime type based on extension.
65 Default ot text/x-wiki for files without an extension.
67 >>> guess_mime('something.txt')
69 >>> guess_mime('SomePage')
71 >>> guess_mime(u'ąęśUnicodePage')
73 >>> guess_mime('image.png')
75 >>> guess_mime('style.css')
77 >>> guess_mime('archive.tar.gz')
81 mime, encoding = mimetypes.guess_type(file_name, strict=False)
83 mime = 'archive/%s' % encoding
89 class DocumentNotFound(Exception):
93 class VersionedStorage(object):
95 Provides means of storing text pages and keeping track of their
96 change history, using Mercurial repository as the storage method.
99 def __init__(self, path, charset=None):
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.
107 self.charset = charset or 'utf-8'
109 if not os.path.exists(self.path):
110 os.makedirs(self.path)
111 self.repo_path = find_repo_path(self.path)
113 self.ui = mercurial.ui.ui(report_untrusted=False,
114 interactive=False, quiet=True)
116 # Mercurial 1.3 changed the way we setup the ui object.
117 self.ui = mercurial.ui.ui()
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
126 self.repo_prefix = self.path[len(self.repo_path):].strip('/')
127 self.repo = mercurial.hg.repository(self.ui, self.repo_path,
131 """Close and reopen the repo, to make sure we are up to date."""
133 self.repo = mercurial.hg.repository(self.ui, self.repo_path)
135 def _file_path(self, title):
136 return os.path.join(self.path, urlquote(title, safe=''))
138 def _title_to_file(self, title):
139 return os.path.join(self.repo_prefix, urlquote(title, safe=''))
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)
146 def __contains__(self, title):
147 return os.path.exists(self._file_path(title))
150 return self.all_pages()
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()
158 self.repo.dirstate.setparents(parent_node)
159 node = self._commit([repo_file], text, user)
161 partial = lambda filename: repo_file == filename
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]
168 # TODO: Check if merge was successful
169 mercurial.merge.update(self.repo, tip_node, True, False, partial)
171 self.repo.dirstate.setparents(tip_node, node)
172 # Mercurial 1.1 and later need updating the merge state
174 mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
175 except (AttributeError, KeyError):
177 return u'merge of edit conflict'
180 def save_file(self, title, file_name, author=u'', comment=u'', parent=None):
181 """Save an existing file as specified page."""
183 user = author.encode('utf-8') or u'anon'.encode('utf-8')
184 text = comment.encode('utf-8') or u'comment'.encode('utf-8')
185 repo_file = self._title_to_file(title)
186 file_path = self._file_path(title)
187 mercurial.util.rename(file_name, file_path)
188 changectx = self._changectx()
190 filectx_tip = changectx[repo_file]
191 current_page_rev = filectx_tip.filerev()
192 except mercurial.revlog.LookupError:
193 self.repo.add([repo_file])
194 current_page_rev = -1
195 if parent is not None and current_page_rev != parent:
196 msg = self.merge_changes(changectx, repo_file, text, user, parent)
198 text = msg.encode('utf-8')
199 self._commit([repo_file], text, user)
202 def _commit(self, files, text, user):
204 return self.repo.commit(files=files, text=text, user=user,
205 force=True, empty_ok=True)
207 # Mercurial 1.3 doesn't accept empty_ok or files parameter
208 match = mercurial.match.exact(self.repo_path, '', list(files))
209 return self.repo.commit(match=match, text=text, user=user,
213 def save_data(self, title, data, author=u'', comment=u'', parent=None):
214 """Save data as specified page."""
217 temp_path = tempfile.mkdtemp(dir=self.path)
218 file_path = os.path.join(temp_path, 'saved')
219 f = open(file_path, "wb")
222 self.save_file(title, file_path, author, comment, parent)
233 def save_text(self, title, text, author=u'', comment=u'', parent=None):
234 """Save text as specified page, encoded to charset."""
236 data = text.encode(self.charset)
237 self.save_data(title, data, author, comment, parent)
239 def page_text(self, title):
240 """Read unicode text of a page."""
242 data = self.open_page(title).read()
243 text = unicode(data, self.charset, 'replace')
246 def page_lines(self, page):
248 yield unicode(data, self.charset, 'replace')
251 def delete_page(self, title, author=u'', comment=u''):
252 user = author.encode('utf-8') or 'anon'
253 text = comment.encode('utf-8') or 'deleted'
254 repo_file = self._title_to_file(title)
255 file_path = self._file_path(title)
260 self.repo.remove([repo_file])
261 self._commit([repo_file], text, user)
263 def open_page(self, title):
265 return open(self._file_path(title), "rb")
267 raise DocumentNotFound()
269 def page_file_meta(self, title):
270 """Get page's inode number, size and last modification time."""
273 (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
274 st_atime, st_mtime, st_ctime) = os.stat(self._file_path(title))
277 return st_ino, st_size, st_mtime
279 def page_meta(self, title):
280 """Get page's revision, date, last editor and his edit comment."""
282 filectx_tip = self._find_filectx(title)
283 if filectx_tip is None:
284 raise DocumentNotFound()
285 #return -1, None, u'', u''
286 rev = filectx_tip.filerev()
287 filectx = filectx_tip.filectx(rev)
288 date = datetime.datetime.fromtimestamp(filectx.date()[0])
289 author = unicode(filectx.user(), "utf-8",
290 'replace').split('<')[0].strip()
291 comment = unicode(filectx.description(), "utf-8", 'replace')
292 return rev, date, author, comment
294 def repo_revision(self):
295 return self._changectx().rev()
297 def page_mime(self, title):
299 Guess page's mime type based on corresponding file name.
300 Default ot text/x-wiki for files without an extension.
302 return guess_type(self._file_path(title))
304 def _changectx(self):
305 """Get the changectx of the tip."""
307 # This is for Mercurial 1.0
308 return self.repo.changectx()
310 # Mercurial 1.3 (and possibly earlier) needs an argument
311 return self.repo.changectx('tip')
313 def _find_filectx(self, title):
314 """Find the last revision in which the file existed."""
316 repo_file = self._title_to_file(title)
317 changectx = self._changectx()
319 while repo_file not in changectx:
322 changectx = stack.pop()
323 for parent in changectx.parents():
324 if parent != changectx:
326 return changectx[repo_file]
328 def page_history(self, title):
329 """Iterate over the page's history."""
331 filectx_tip = self._find_filectx(title)
332 if filectx_tip is None:
334 maxrev = filectx_tip.filerev()
336 for rev in range(maxrev, minrev-1, -1):
337 filectx = filectx_tip.filectx(rev)
338 date = datetime.datetime.fromtimestamp(filectx.date()[0])
339 author = unicode(filectx.user(), "utf-8",
340 'replace').split('<')[0].strip()
341 comment = unicode(filectx.description(), "utf-8", 'replace')
342 yield rev, date, author, comment
344 def page_revision(self, title, rev):
345 """Get unicode contents of specified revision of the page."""
347 filectx_tip = self._find_filectx(title)
348 if filectx_tip is None:
349 raise DocumentNotFound()
351 data = filectx_tip.filectx(rev).data()
353 raise DocumentNotFound()
356 def revision_text(self, title, rev):
357 data = self.page_revision(title, rev)
358 text = unicode(data, self.charset, 'replace')
362 """Iterate over the history of entire wiki."""
364 changectx = self._changectx()
365 maxrev = changectx.rev()
367 for wiki_rev in range(maxrev, minrev-1, -1):
368 change = self.repo.changectx(wiki_rev)
369 date = datetime.datetime.fromtimestamp(change.date()[0])
370 author = unicode(change.user(), "utf-8",
371 'replace').split('<')[0].strip()
372 comment = unicode(change.description(), "utf-8", 'replace')
373 for repo_file in change.files():
374 if repo_file.startswith(self.repo_prefix):
375 title = self._file_to_title(repo_file)
377 rev = change[repo_file].filerev()
378 except mercurial.revlog.LookupError:
380 yield title, rev, date, author, comment
383 """Iterate over the titles of all pages in the wiki."""
385 for filename in os.listdir(self.path):
386 if (os.path.isfile(os.path.join(self.path, filename))
387 and not filename.startswith('.')):
388 yield urlunquote(filename)
390 def changed_since(self, rev):
391 """Return all pages that changed since specified repository revision."""
394 last = self.repo.lookup(int(rev))
396 for page in self.all_pages():
399 current = self.repo.lookup('tip')
400 status = self.repo.status(current, last)
401 modified, added, removed, deleted, unknown, ignored, clean = status
402 for filename in modified+added+removed+deleted:
403 if filename.startswith(self.repo_prefix):
404 yield self._file_to_title(filename)