1
# Copyright (C) 2008, 2009 Canonical Ltd.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Serve branches at urls that mimic a transport's file system layout."""
21
from bzrlib import branch, errors, lru_cache, urlutils
22
from bzrlib.config import LocationConfig
23
from bzrlib.smart import request
24
from bzrlib.transport import get_transport
25
from bzrlib.transport.http import wsgi
1
import cgi, os, tempfile
2
from bzrlib import branch, errors
3
from loggerhead.history import History
4
from loggerhead.wsgiapp import BranchWSGIApp, static_app
27
5
from paste.request import path_info_pop
6
from paste.wsgiwrappers import WSGIRequest, WSGIResponse
28
7
from paste import httpexceptions
29
from paste import urlparser
31
from loggerhead import util
32
from loggerhead.apps.branch import BranchWSGIApp
33
from loggerhead.apps import favicon_app, robots_app, static_app
34
from loggerhead.controllers.directory_ui import DirectoryUI
36
# TODO: Use bzrlib.ui.bool_from_string(), added in bzr 1.18
38
'yes': True, 'no': False,
39
'on': True, 'off': False,
40
'1': True, '0': False,
41
'true': True, 'false': False,
44
class BranchesFromTransportServer(object):
46
def __init__(self, transport, root, name=None):
47
self.transport = transport
8
from paste import httpserver
9
from paste.httpexceptions import make_middleware
10
from paste.translogger import make_filter
11
from loggerhead.changecache import FileChangeCache
14
sql_dir = tempfile.mkdtemp()
16
class BranchesFromFileSystemServer(object):
17
def __init__(self, folder, root):
50
self._config = root._config
52
def app_for_branch(self, branch):
54
name = branch._get_nick(local=True)
59
branch_app = BranchWSGIApp(
62
{'cachepath': self._config.SQL_DIR},
63
self.root.graph_cache,
65
use_cdn=self._config.get_option('use_cdn'),
69
def app_for_non_branch(self, environ):
70
segment = path_info_pop(environ)
72
raise httpexceptions.HTTPMovedPermanently.relative_redirect(
73
environ['SCRIPT_NAME'] + '/', environ)
80
environ['loggerhead.static.url'], self.transport, name)
82
new_transport = self.transport.clone(segment)
84
new_name = urlutils.join(self.name, segment)
86
new_name = '/' + segment
87
return BranchesFromTransportServer(new_transport, self.root, new_name)
89
def app_for_bazaar_data(self, relpath):
90
if relpath == '/.bzr/smart':
91
root_transport = get_transport_for_thread(self.root.base)
92
wsgi_app = wsgi.SmartWSGIApp(root_transport)
93
return wsgi.RelpathSetter(wsgi_app, '', 'loggerhead.path_info')
95
# TODO: Use something here that uses the transport API
96
# rather than relying on the local filesystem API.
97
base = self.transport.base
99
path = util.local_path_from_url(base)
100
except errors.InvalidURL:
101
raise httpexceptions.HTTPNotFound()
103
return urlparser.make_static(None, path)
105
def check_serveable(self, config):
106
value = config.get_user_option('http_serve')
109
elif not _bools.get(value.lower(), True):
21
def __call__(self, environ, start_response):
22
path = os.path.join(self.root.folder, self.folder)
23
if not os.path.isdir(path):
110
24
raise httpexceptions.HTTPNotFound()
112
def __call__(self, environ, start_response):
113
path = environ['PATH_INFO']
25
if path in self.root.cache:
26
return self.root.cache[path](environ, start_response)
115
b = branch.Branch.open_from_transport(self.transport)
28
b = branch.Branch.open(path)
116
29
except errors.NotBranchError:
117
if path.startswith('/.bzr'):
118
self.check_serveable(LocationConfig(self.transport.base))
119
return self.app_for_bazaar_data(path)(environ, start_response)
120
if not self.transport.listable() or not self.transport.has('.'):
121
raise httpexceptions.HTTPNotFound()
122
return self.app_for_non_branch(environ)(environ, start_response)
30
segment = path_info_pop(environ)
32
request = WSGIRequest(environ)
33
response = WSGIResponse()
34
listing = [d for d in os.listdir(path) if not d.startswith('.')]
35
response.headers['Content-Type'] = 'text/html'
36
print >> response, '<html><body>'
37
for d in sorted(listing):
38
if os.path.isdir(os.path.join(path, d)):
40
print >> response, '<li><a href="%s/">%s</a></li>' % (d, d)
41
print >> response, '</body></html>'
42
return response(environ, start_response)
44
relpath = os.path.join(self.folder, segment)
45
return BranchesFromFileSystemServer(relpath, self.root)(
46
environ, start_response)
124
self.check_serveable(b.get_config())
125
if path.startswith('/.bzr'):
126
return self.app_for_bazaar_data(path)(environ, start_response)
128
return self.app_for_branch(b)(environ, start_response)
131
_transport_store = threading.local()
133
def get_transport_for_thread(base):
134
thread_transports = getattr(_transport_store, 'transports', None)
135
if thread_transports is None:
136
thread_transports = _transport_store.transports = {}
137
if base in thread_transports:
138
return thread_transports[base]
139
transport = get_transport(base)
140
thread_transports[base] = transport
144
class BranchesFromTransportRoot(object):
146
def __init__(self, base, config):
147
self.graph_cache = lru_cache.LRUCache(10)
149
self._config = config
50
_history = History.from_branch(b)
51
_history.use_file_cache(FileChangeCache(_history, sql_dir))
52
print '!!!', self.folder, path
54
name = os.path.basename(os.path.abspath(path))
57
h = BranchWSGIApp(_history, name).app
58
self.root.cache[path] = h
59
return h(environ, start_response)
63
class BranchesFromFileSystemRoot(object):
64
def __init__(self, folder):
151
67
def __call__(self, environ, start_response):
152
68
environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
153
environ['loggerhead.path_info'] = environ['PATH_INFO']
154
69
if environ['PATH_INFO'].startswith('/static/'):
155
70
segment = path_info_pop(environ)
156
71
assert segment == 'static'
157
72
return static_app(environ, start_response)
158
elif environ['PATH_INFO'] == '/favicon.ico':
159
return favicon_app(environ, start_response)
160
elif environ['PATH_INFO'] == '/robots.txt':
161
return robots_app(environ, start_response)
163
transport = get_transport_for_thread(self.base)
164
return BranchesFromTransportServer(
165
transport, self)(environ, start_response)
168
class UserBranchesFromTransportRoot(object):
170
def __init__(self, base, config):
171
self.graph_cache = lru_cache.LRUCache(10)
173
self._config = config
174
self.trunk_dir = config.get_option('trunk_dir')
176
def __call__(self, environ, start_response):
177
environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
178
environ['loggerhead.path_info'] = environ['PATH_INFO']
179
path_info = environ['PATH_INFO']
180
if path_info.startswith('/static/'):
181
segment = path_info_pop(environ)
182
assert segment == 'static'
183
return static_app(environ, start_response)
184
elif path_info == '/favicon.ico':
185
return favicon_app(environ, start_response)
186
elif environ['PATH_INFO'] == '/robots.txt':
187
return robots_app(environ, start_response)
189
transport = get_transport_for_thread(self.base)
190
# segments starting with ~ are user branches
191
if path_info.startswith('/~'):
192
segment = path_info_pop(environ)
193
return BranchesFromTransportServer(
194
transport.clone(segment[1:]), self, segment)(
195
environ, start_response)
197
return BranchesFromTransportServer(
198
transport.clone(self.trunk_dir), self)(
199
environ, start_response)
74
return BranchesFromFileSystemServer(
75
'', self)(environ, start_response)
77
app = BranchesFromFileSystemRoot('.')
80
app = make_middleware(app)
81
app = make_filter(app, None)
84
httpserver.serve(app, host='127.0.0.1', port='9876')