bzrbrowse.cgi 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. #!/usr/bin/env python
  2. # Copyright (C) 2008 Lukas Lalinsky <lalinsky@gmail.com>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. # CHANGE THIS:
  18. config = {
  19. 'root': '/home/ccan/ccan',
  20. 'base_url': '/browse',
  21. 'images_url': '/browse',
  22. 'branch_url': 'http://ccan.ozlabs.org/repo',
  23. }
  24. import os, sys
  25. from bzrlib.branch import Branch
  26. from bzrlib.errors import NotBranchError
  27. from bzrlib import urlutils, osutils
  28. __version__ = '0.0.1'
  29. class HTTPError(Exception):
  30. def __init__(self, code, message):
  31. self.code = code
  32. self.message = message
  33. class NotFound(HTTPError):
  34. def __init__(self, message):
  35. super(NotFound, self).__init__('404 Not Found', message)
  36. def escape_html(text):
  37. return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("\n", '<br />')
  38. class BzrBrowse(object):
  39. icons = {
  40. 'file': 'file.png',
  41. 'directory': 'folder.png',
  42. }
  43. page_tmpl = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  44. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>%(title)s</title><style type="text/css">
  45. body { font-family: sans-serif; font-size: 10pt; }
  46. div#page { padding: 0.5em; border: solid 1px #444; background: #FAFAFA; }
  47. #footer { font-size: 70%%; background-color: #444; color: #FFF; margin: 0; padding: 0.1em 0.3em; }
  48. #footer hr { display: none; }
  49. h1 { margin: 0; font-size: 14pt; background-color: #444; color: #FFF; padding: 0.1em 0.3em; }
  50. h1 a { color: #FFF; }
  51. h1 a:hover { color: #8CB1D8; }
  52. #page a { color: #244B7C; }
  53. #page a:hover { color: #B12319; }
  54. pre { margin: 0; font-size: 90%%; }
  55. .linenumbers { text-align: right; padding-right: 0.5em; border-right: solid 1px #444; }
  56. .text { padding-left: 0.5em; }
  57. .msg { margin: 0; margin-bottom: 0.5em; padding: 0.3em 0em; border-bottom: solid 1px #444;}
  58. code { background-color: #000; color: #FFF; font-size: 90%%;}
  59. </style>
  60. </head><body>
  61. <h1>%(header)s</h1>
  62. <div id="page">%(contents)s</div>
  63. <div id="footer"><hr />bzrbrowse/%(version)s</div>
  64. </body></html>'''
  65. def __init__(self, config):
  66. self.config = config
  67. self.base_url = None
  68. def list_to_html(self, entries):
  69. content = []
  70. for entry in entries:
  71. line = '<img src="%(images_url)s/%(icon)s" /> <a href="%(base_url)s/%(path)s">%(name)s</a><br />' % {
  72. 'base_url': self.config['base_url'],
  73. 'images_url': self.config['images_url'],
  74. 'path': entry['path'],
  75. 'name': entry['name'],
  76. 'icon': self.icons.get(entry['kind'], self.icons['file'])
  77. }
  78. content.append(line)
  79. return ''.join(content)
  80. def list_fs_directory(self, path):
  81. entries = []
  82. if path:
  83. entries.append({
  84. 'name': '..',
  85. 'path': os.path.dirname(path),
  86. 'kind': 'directory',
  87. })
  88. if path:
  89. prefix = path + '/'
  90. else:
  91. prefix = ''
  92. try:
  93. filelist = os.listdir(os.path.join(self.config['root'], path))
  94. except OSError:
  95. raise NotFound('Path not found: ' + path)
  96. for name in sorted(filelist):
  97. if name.startswith('.'):
  98. continue
  99. abspath = os.path.join(path, name)
  100. if os.path.isdir(os.path.join(self.config['root'], abspath)):
  101. entries.append({
  102. 'name': name,
  103. 'path': prefix + name,
  104. 'kind': 'directory',
  105. })
  106. return self.list_to_html(entries)
  107. def view_branch_file(self, tree, ie):
  108. if ie.text_size > 1024 * 1024:
  109. return 'File too big. (%d bytes)' % (ie.text_size)
  110. tree.lock_read()
  111. try:
  112. text = tree.get_file_text(ie.file_id)
  113. finally:
  114. tree.unlock()
  115. if '\0' in text:
  116. return 'Binary file. (%d bytes)' % (ie.text_size)
  117. try:
  118. text = text.decode('utf-8')
  119. except UnicodeDecodeError:
  120. text = text.decode('latin-1')
  121. linenumbers = []
  122. for i in range(1, text.count('\n') + 1):
  123. linenumbers.append('<a id="l-%d" href="#l-%d">%d</a>' % (i, i, i))
  124. linenumbers = '\n'.join(linenumbers)
  125. return ('<table cellspacing="0" cellpadding="0"><tr><td class="linenumbers"><pre>' +
  126. linenumbers + '</pre></td><td class="text"><pre>' + escape_html(text) +
  127. '</pre></td></tr></table>')
  128. def list_branch_directory(self, branch, path, relpath):
  129. tree = branch.basis_tree()
  130. file_id = tree.path2id(relpath)
  131. ie = tree.inventory[file_id]
  132. if ie.kind == 'file':
  133. return self.view_branch_file(tree, ie)
  134. entries = []
  135. if path:
  136. entries.append({
  137. 'name': '..',
  138. 'path': urlutils.dirname(path),
  139. 'kind': 'directory',
  140. })
  141. if path:
  142. prefix = path + '/'
  143. else:
  144. prefix = ''
  145. for name, child in sorted(ie.children.iteritems()):
  146. entries.append({
  147. 'name': name,
  148. 'path': prefix + name,
  149. 'kind': child.kind,
  150. })
  151. html = self.list_to_html(entries)
  152. base = self.config['branch_url'] + '/' + osutils.relpath(self.config['root'], urlutils.local_path_from_url(branch.base))
  153. html = ('<p class="msg">This is a <a href="http://bazaar-vcs.org/">Bazaar</a> branch. ' +
  154. 'Use <code>bzr branch ' + base + '</code> to download it.</p>' + html)
  155. return html
  156. def request(self, path):
  157. abspath = os.path.join(self.config['root'], path)
  158. try:
  159. branch, relpath = Branch.open_containing(abspath)
  160. except NotBranchError:
  161. return self.list_fs_directory(path)
  162. return self.list_branch_directory(branch, path, relpath)
  163. def title(self, path):
  164. return '/' + path
  165. def header(self, path):
  166. title = []
  167. p = ''
  168. title.append('<a href="%s%s">root</a>' % (self.config['base_url'], p))
  169. for name in path.split('/'):
  170. p += '/' + name
  171. title.append('<a href="%s%s">%s</a>' % (self.config['base_url'], p, name))
  172. return '/'.join(title)
  173. def __call__(self, environ, start_response):
  174. try:
  175. path = '/'.join(filter(bool, environ.get('PATH_INFO', '').split('/')))
  176. contents = self.page_tmpl % {
  177. 'title': self.title(path),
  178. 'header': self.header(path),
  179. 'contents': self.request(path),
  180. 'version': __version__
  181. }
  182. contents = contents.encode('utf-8')
  183. headers = [('Content-type','text/html; charset=UTF-8')]
  184. start_response('200 OK', headers)
  185. return [contents]
  186. except HTTPError, e:
  187. headers = [('Content-type','text/html; charset=UTF-8')]
  188. start_response(e.code, headers)
  189. return [e.message]
  190. except:
  191. import cgitb, sys
  192. traceback_html = cgitb.html(sys.exc_info())
  193. headers = [('Content-type','text/html; charset=UTF-8')]
  194. start_response('200 OK', headers)
  195. return [traceback_html]
  196. from wsgiref.handlers import CGIHandler
  197. CGIHandler().run(BzrBrowse(config))