~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to wsgitest.py

  • Committer: Michael Hudson
  • Date: 2008-06-15 06:43:31 UTC
  • mto: This revision was merged to the branch mainline in revision 164.
  • Revision ID: michael.hudson@canonical.com-20080615064331-9ex9xf7ttzky1xco
basic functionality complete

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009 Canonical Ltd.
2
 
#
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.
7
 
#
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.
12
 
#
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
16
 
#
17
 
"""Serve branches at urls that mimic a transport's file system layout."""
18
 
 
19
 
import threading
20
 
 
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
26
 
 
27
 
from paste.request import path_info_pop
28
 
from paste import httpexceptions
29
 
from paste import urlparser
30
 
 
31
 
from loggerhead.apps.branch import BranchWSGIApp
32
 
from loggerhead.apps import favicon_app, static_app
33
 
from loggerhead.controllers.directory_ui import DirectoryUI
34
 
 
35
 
_bools = {
36
 
    'yes': True, 'no': False,
37
 
    'on': True, 'off': False,
38
 
    '1': True, '0': False,
39
 
    'true': True, 'false': False,
40
 
    }
41
 
 
42
 
class BranchesFromTransportServer(object):
43
 
 
44
 
    def __init__(self, transport, root, name=None):
45
 
        self.transport = transport
46
 
        self.root = root
47
 
        self.name = name
48
 
        self._config = root._config
49
 
 
50
 
    def app_for_branch(self, branch):
51
 
        if not self.name:
52
 
            name = branch._get_nick(local=True)
53
 
            is_root = True
54
 
        else:
55
 
            name = self.name
56
 
            is_root = False
57
 
        branch_app = BranchWSGIApp(
58
 
            branch, name,
59
 
            {'cachepath': self._config.SQL_DIR},
60
 
            self.root.graph_cache, is_root=is_root,
61
 
            use_cdn=self._config.get_option('use_cdn'))
62
 
        return branch_app.app
63
 
 
64
 
    def app_for_non_branch(self, environ):
65
 
        segment = path_info_pop(environ)
66
 
        if segment is None:
67
 
            raise httpexceptions.HTTPMovedPermanently(
68
 
                environ['SCRIPT_NAME'] + '/')
69
 
        elif segment == '':
70
 
            if self.name:
71
 
                name = self.name
72
 
            else:
73
 
                name = '/'
74
 
            return DirectoryUI(
75
 
                environ['loggerhead.static.url'], self.transport, name)
76
 
        else:
77
 
            new_transport = self.transport.clone(segment)
78
 
            if self.name:
79
 
                new_name = urlutils.join(self.name, segment)
80
 
            else:
81
 
                new_name = '/' + segment
82
 
            return BranchesFromTransportServer(new_transport, self.root, new_name)
83
 
 
84
 
    def app_for_bazaar_data(self, relpath):
85
 
        if relpath == '/.bzr/smart':
86
 
            root_transport = get_transport_for_thread(self.root.base)
87
 
            wsgi_app = wsgi.SmartWSGIApp(root_transport)
88
 
            return wsgi.RelpathSetter(wsgi_app, '', 'loggerhead.path_info')
89
 
        else:
90
 
            # TODO: Use something here that uses the transport API
91
 
            # rather than relying on the local filesystem API.
92
 
            base = self.transport.base
93
 
            readonly_prefix = 'readonly+'
94
 
            if base.startswith(readonly_prefix):
95
 
                base = base[len(readonly_prefix):]
96
 
            try:
97
 
                path = urlutils.local_path_from_url(base)
98
 
            except errors.InvalidURL:
99
 
                raise httpexceptions.HTTPNotFound()
100
 
            else:
101
 
                return urlparser.make_static(None, path)
102
 
 
103
 
    def check_serveable(self, config):
104
 
        value = config.get_user_option('http_serve')
105
 
        if value is None:
106
 
            return
107
 
        elif not _bools.get(value.lower(), True):
108
 
            raise httpexceptions.HTTPNotFound()
109
 
 
110
 
    def __call__(self, environ, start_response):
111
 
        path = environ['PATH_INFO']
112
 
        try:
113
 
            b = branch.Branch.open_from_transport(self.transport)
114
 
        except errors.NotBranchError:
115
 
            if path.startswith('/.bzr'):
116
 
                self.check_serveable(LocationConfig(self.transport.base))
117
 
                return self.app_for_bazaar_data(path)(environ, start_response)
118
 
            if not self.transport.listable() or not self.transport.has('.'):
119
 
                raise httpexceptions.HTTPNotFound()
120
 
            return self.app_for_non_branch(environ)(environ, start_response)
121
 
        else:
122
 
            self.check_serveable(b.get_config())
123
 
            if path.startswith('/.bzr'):
124
 
                return self.app_for_bazaar_data(path)(environ, start_response)
125
 
            else:
126
 
                return self.app_for_branch(b)(environ, start_response)
127
 
 
128
 
 
129
 
_transport_store = threading.local()
130
 
 
131
 
def get_transport_for_thread(base):
132
 
    """ """
133
 
    thread_transports = getattr(_transport_store, 'transports', None)
134
 
    if thread_transports is None:
135
 
        thread_transports = _transport_store.transports = {}
136
 
    if base in thread_transports:
137
 
        return thread_transports[base]
138
 
    transport = get_transport(base)
139
 
    thread_transports[base] = transport
140
 
    return transport
141
 
 
142
 
 
143
 
class BranchesFromTransportRoot(object):
144
 
 
145
 
    def __init__(self, base, config):
146
 
        self.graph_cache = lru_cache.LRUCache(10)
147
 
        self.base = base
148
 
        self._config = config
149
 
 
150
 
    def __call__(self, environ, start_response):
151
 
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
152
 
        environ['loggerhead.path_info'] = environ['PATH_INFO']
153
 
        if environ['PATH_INFO'].startswith('/static/'):
154
 
            segment = path_info_pop(environ)
155
 
            assert segment == 'static'
156
 
            return static_app(environ, start_response)
157
 
        elif environ['PATH_INFO'] == '/favicon.ico':
158
 
            return favicon_app(environ, start_response)
159
 
        else:
160
 
            transport = get_transport_for_thread(self.base)
161
 
            return BranchesFromTransportServer(
162
 
                transport, self)(environ, start_response)
163
 
 
164
 
 
165
 
class UserBranchesFromTransportRoot(object):
166
 
 
167
 
    def __init__(self, base, config):
168
 
        self.graph_cache = lru_cache.LRUCache(10)
169
 
        self.base = base
170
 
        self._config = config
171
 
        self.trunk_dir = config.get_option('trunk_dir')
172
 
 
173
 
    def __call__(self, environ, start_response):
174
 
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
175
 
        environ['loggerhead.path_info'] = environ['PATH_INFO']
176
 
        path_info = environ['PATH_INFO']
177
 
        if path_info.startswith('/static/'):
178
 
            segment = path_info_pop(environ)
179
 
            assert segment == 'static'
180
 
            return static_app(environ, start_response)
181
 
        elif path_info == '/favicon.ico':
182
 
            return favicon_app(environ, start_response)
183
 
        else:
184
 
            transport = get_transport_for_thread(self.base)
185
 
            # segments starting with ~ are user branches
186
 
            if path_info.startswith('/~'):
187
 
                segment = path_info_pop(environ)
188
 
                return BranchesFromTransportServer(
189
 
                    transport.clone(segment[1:]), self, segment)(
190
 
                    environ, start_response)
191
 
            else:
192
 
                return BranchesFromTransportServer(
193
 
                    transport.clone(self.trunk_dir), self)(
194
 
                    environ, start_response)
 
1
from loggerhead.history import History
 
2
from loggerhead.wsgiapp import BranchWSGIApp
 
3
 
 
4
h = History.from_folder('.')
 
5
 
 
6
app = BranchWSGIApp(h)
 
7
 
 
8
 
 
9
from paste import httpserver
 
10
from paste.evalexception import EvalException
 
11
from paste.httpexceptions import make_middleware
 
12
from paste.translogger import make_filter
 
13
 
 
14
app = app.app
 
15
for w in EvalException, make_middleware:
 
16
    app = w(app)
 
17
 
 
18
app = make_filter(app, None)
 
19
 
 
20
httpserver.serve(app, host='127.0.0.1', port='9876')
 
21