1 # -*- coding: utf-8 -*-
10 # Note: we have to set these before importing Mercurial
11 os.environ['HGENCODING'] = 'utf-8'
12 os.environ['HGMERGE'] = "internal:merge"
16 import mercurial.revlog
20 def urlquote(url, safe='/'):
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'
26 return urllib.quote(url.replace(' ', '_').encode('utf-8', 'ignore'), safe)
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'
34 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)
44 def locked_repo(func):
45 """A decorator for locking the repository when calling a method."""
47 def new_func(self, *args, **kwargs):
48 """Wrap the original function in locks."""
50 wlock = self.repo.wlock()
51 lock = self.repo.lock()
53 func(self, *args, **kwargs)
61 class DocumentNotFound(Exception):
65 class VersionedStorage(object):
67 Provides means of storing text pages and keeping track of their
68 change history, using Mercurial repository as the storage method.
71 def __init__(self, path, charset=None):
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.
79 self.charset = charset or 'utf-8'
81 if not os.path.exists(self.path):
82 os.makedirs(self.path)
83 self.repo_path = find_repo_path(self.path)
85 self.ui = mercurial.ui.ui(report_untrusted=False,
86 interactive=False, quiet=True)
88 # Mercurial 1.3 changed the way we setup the ui object.
89 self.ui = mercurial.ui.ui()
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
98 self.repo_prefix = self.path[len(self.repo_path):].strip('/')
99 self.repo = mercurial.hg.repository(self.ui, self.repo_path,
103 """Close and reopen the repo, to make sure we are up to date."""
105 self.repo = mercurial.hg.repository(self.ui, self.repo_path)
107 def _file_path(self, title):
108 return os.path.join(self.path, urlquote(title, safe=''))
110 def _title_to_file(self, title):
111 return os.path.join(self.repo_prefix, urlquote(title, safe=''))
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)
118 def __contains__(self, title):
119 return os.path.exists(self._file_path(title))
122 return self.all_pages()
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()
130 self.repo.dirstate.setparents(parent_node)
131 node = self._commit([repo_file], text, user)
133 partial = lambda filename: repo_file == filename
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]
141 unresolved = mercurial.merge.update(self.repo, tip_node, True, False, partial)
142 except mercurial.util.Abort:
144 unresolved = 1, 1, 1, 1
146 self.repo.dirstate.setparents(tip_node, node)
147 # Mercurial 1.1 and later need updating the merge state
149 mercurial.merge.mergestate(self.repo).mark(repo_file, "r")
150 except (AttributeError, KeyError):
152 return u'merge of edit conflict'
155 def save_file(self, title, file_name, author=u'', comment=u'', parent=None):
156 """Save an existing file as specified page."""
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()
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)
173 text = msg.encode('utf-8')
174 self._commit([repo_file], text, user)
177 def _commit(self, files, text, user):
179 return self.repo.commit(files=files, text=text, user=user,
180 force=True, empty_ok=True)
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,
188 def save_data(self, title, data, author=u'', comment=u'', parent=None):
189 """Save data as specified page."""
192 temp_path = tempfile.mkdtemp(dir=self.path)
193 file_path = os.path.join(temp_path, 'saved')
194 f = open(file_path, "wb")
197 self.save_file(title, file_path, author, comment, parent)
208 def save_text(self, title, text, author=u'', comment=u'', parent=None):
209 """Save text as specified page, encoded to charset."""
211 data = text.encode(self.charset)
212 self.save_data(title, data, author, comment, parent)
214 def page_text(self, title):
215 """Read unicode text of a page."""
217 data = self.open_page(title).read()
218 text = unicode(data, self.charset, 'replace')
221 def page_lines(self, page):
223 yield unicode(data, self.charset, 'replace')
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)
235 self.repo.remove([repo_file])
236 self._commit([repo_file], text, user)
238 def open_page(self, title):
240 return open(self._file_path(title), "rb")
242 raise DocumentNotFound()
244 def page_file_meta(self, title):
245 """Get page's inode number, size and last modification time."""
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))
252 return st_ino, st_size, st_mtime
254 def page_meta(self, title):
255 """Get page's revision, date, last editor and his edit comment."""
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
269 def repo_revision(self):
270 return self._changectx().rev()
272 def page_mime(self, title):
274 Guess page's mime type ased on corresponding file name.
275 Default ot text/x-wiki for files without an extension.
277 # >>> page_mime('something.txt')
279 # >>> page_mime('SomePage')
281 # >>> page_mime(u'ąęśUnicodePage')
283 # >>> page_mime('image.png')
285 # >>> page_mime('style.css')
287 # >>> page_mime('archive.tar.gz')
291 addr = self._file_path(title)
292 mime, encoding = mimetypes.guess_type(addr, strict=False)
294 mime = 'archive/%s' % encoding
299 def _changectx(self):
300 """Get the changectx of the tip."""
302 # This is for Mercurial 1.0
303 return self.repo.changectx()
305 # Mercurial 1.3 (and possibly earlier) needs an argument
306 return self.repo.changectx('tip')
308 def _find_filectx(self, title):
309 """Find the last revision in which the file existed."""
311 repo_file = self._title_to_file(title)
312 changectx = self._changectx()
314 while repo_file not in changectx:
317 changectx = stack.pop()
318 for parent in changectx.parents():
319 if parent != changectx:
321 return changectx[repo_file]
323 def page_history(self, title):
324 """Iterate over the page's history."""
326 filectx_tip = self._find_filectx(title)
327 if filectx_tip is None:
329 maxrev = filectx_tip.filerev()
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
339 def page_revision(self, title, rev):
340 """Get unicode contents of specified revision of the page."""
342 filectx_tip = self._find_filectx(title)
343 if filectx_tip is None:
344 raise DocumentNotFound()
346 data = filectx_tip.filectx(rev).data()
348 raise DocumentNotFound()
351 def revision_text(self, title, rev):
352 data = self.page_revision(title, rev)
353 text = unicode(data, self.charset, 'replace')
357 """Iterate over the history of entire wiki."""
359 changectx = self._changectx()
360 maxrev = changectx.rev()
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)
372 rev = change[repo_file].filerev()
373 except mercurial.revlog.LookupError:
375 yield title, rev, date, author, comment
378 """Iterate over the titles of all pages in the wiki."""
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)
385 def changed_since(self, rev):
386 """Return all pages that changed since specified repository revision."""
389 last = self.repo.lookup(int(rev))
391 for page in self.all_pages():
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)