~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/apps/transport.py

  • Committer: Jelmer Vernooij
  • Date: 2009-06-02 00:09:55 UTC
  • mto: (359.3.1 hpss-writes)
  • mto: This revision was merged to the branch mainline in revision 367.
  • Revision ID: jelmer@samba.org-20090602000955-91nohd46pktp8j8k
Support serving branches over HTTP using the smart server protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import cgi
2
 
import os
3
 
import tempfile
 
1
"""Serve branches at urls that mimic a transport's file system layout."""
4
2
 
5
 
from bzrlib import branch, errors
 
3
from bzrlib import branch, errors, lru_cache, urlutils
 
4
from bzrlib.transport import get_transport
 
5
from bzrlib.transport.http import wsgi
6
6
 
7
7
from paste.request import path_info_pop
8
 
from paste.wsgiwrappers import WSGIRequest, WSGIResponse
9
8
from paste import httpexceptions
 
9
from paste import urlparser
10
10
 
11
11
from loggerhead.apps.branch import BranchWSGIApp
12
12
from loggerhead.apps import favicon_app, static_app
13
 
 
14
 
 
15
 
sql_dir = tempfile.mkdtemp()
16
 
 
17
 
class BranchesFromFileSystemServer(object):
18
 
    def __init__(self, folder, root):
19
 
        self.folder = folder
 
13
from loggerhead.config import LoggerheadConfig
 
14
from loggerhead.controllers.directory_ui import DirectoryUI
 
15
 
 
16
 
 
17
class BranchesFromTransportServer(object):
 
18
 
 
19
    def __init__(self, transport, root, name=None):
 
20
        self.transport = transport
20
21
        self.root = root
21
 
 
22
 
    def directory_listing(self, path, environ, start_response):
23
 
        request = WSGIRequest(environ)
24
 
        response = WSGIResponse()
25
 
        listing = [d for d in os.listdir(path) if not d.startswith('.')]
26
 
        response.headers['Content-Type'] = 'text/html'
27
 
        print >> response, '<html><body>'
28
 
        for d in sorted(listing):
29
 
            if os.path.isdir(os.path.join(path, d)):
30
 
                d = cgi.escape(d)
31
 
                print >> response, '<li><a href="%s/">%s</a></li>' % (d, d)
32
 
        print >> response, '</body></html>'
33
 
        return response(environ, start_response)
34
 
 
35
 
    def app_for_branch(self, b, path):
36
 
        if not self.folder:
37
 
            name = os.path.basename(os.path.abspath(path))
38
 
        else:
39
 
            name = self.folder
40
 
        h = BranchWSGIApp(path, name, {'cachepath': sql_dir})
41
 
        self.root.cache[path] = h
42
 
        return h.app
 
22
        self.name = name
 
23
        self._config = root._config
 
24
 
 
25
    def app_for_branch(self, branch):
 
26
        if not self.name:
 
27
            name = branch._get_nick(local=True)
 
28
            is_root = True
 
29
        else:
 
30
            name = self.name
 
31
            is_root = False
 
32
        branch_app = BranchWSGIApp(
 
33
            branch, name,
 
34
            {'cachepath': self._config.SQL_DIR},
 
35
            self.root.graph_cache, is_root=is_root,
 
36
            use_cdn=self._config.get_option('use_cdn'))
 
37
        return branch_app.app
 
38
 
 
39
    def app_for_non_branch(self, environ):
 
40
        segment = path_info_pop(environ)
 
41
        if segment is None:
 
42
            raise httpexceptions.HTTPMovedPermanently(
 
43
                environ['SCRIPT_NAME'] + '/')
 
44
        elif segment == '':
 
45
            if self.name:
 
46
                name = self.name
 
47
            else:
 
48
                name = '/'
 
49
            return DirectoryUI(environ['loggerhead.static.url'],
 
50
                               self.transport,
 
51
                               name)
 
52
        else:
 
53
            new_transport = self.transport.clone(segment)
 
54
            if self.name:
 
55
                new_name = urlutils.join(self.name, segment)
 
56
            else:
 
57
                new_name = '/' + segment
 
58
            return BranchesFromTransportServer(new_transport, self.root, new_name)
43
59
 
44
60
    def __call__(self, environ, start_response):
45
 
        path = os.path.join(self.root.folder, self.folder)
46
 
        if not os.path.isdir(path):
47
 
            raise httpexceptions.HTTPNotFound()
48
 
        cached = self.root.cache.get(path)
49
 
        if cached is not None:
50
 
            return cached.app(environ, start_response)
51
61
        try:
52
 
            b = branch.Branch.open(path)
 
62
            b = branch.Branch.open_from_transport(self.transport)
53
63
        except errors.NotBranchError:
54
 
            segment = path_info_pop(environ)
55
 
            if segment is None:
56
 
                raise httpexceptions.HTTPMovedPermanently(
57
 
                    environ['SCRIPT_NAME'] + '/')
58
 
            elif segment == '':
59
 
                return self.directory_listing(path, environ, start_response)
60
 
            else:
61
 
                relpath = os.path.join(self.folder, segment)
62
 
                return BranchesFromFileSystemServer(relpath, self.root)(
63
 
                    environ, start_response)
 
64
            if not self.transport.listable() or not self.transport.has('.'):
 
65
                raise httpexceptions.HTTPNotFound()
 
66
            return self.app_for_non_branch(environ)(environ, start_response)
64
67
        else:
65
 
            return self.app_for_branch(b, path)(environ, start_response)
66
 
 
67
 
 
68
 
class BranchesFromFileSystemRoot(object):
69
 
    def __init__(self, folder):
70
 
        self.cache = {}
71
 
        self.folder = folder
 
68
            return self.app_for_branch(b)(environ, start_response)
 
69
 
 
70
 
 
71
class BranchesFromTransportRoot(object):
 
72
 
 
73
    def __init__(self, transport, config):
 
74
        self.graph_cache = lru_cache.LRUCache(10)
 
75
        self.transport = transport
 
76
        self._config = config
 
77
 
72
78
    def __call__(self, environ, start_response):
73
79
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
74
80
        if environ['PATH_INFO'].startswith('/static/'):
77
83
            return static_app(environ, start_response)
78
84
        elif environ['PATH_INFO'] == '/favicon.ico':
79
85
            return favicon_app(environ, start_response)
80
 
        else:
81
 
            return BranchesFromFileSystemServer(
82
 
                '', self)(environ, start_response)
 
86
        elif environ['PATH_INFO'].endswith("/.bzr/smart"):
 
87
            # Only do readonly for now
 
88
            transport = get_transport("readonly+" + self.transport.base)
 
89
            wsgi_app = wsgi.SmartWSGIApp(self.transport)
 
90
            wsgi_app = wsgi.RelpathSetter(wsgi_app, '', 'PATH_INFO')
 
91
            return wsgi_app(environ, start_response)
 
92
        elif '/.bzr/' in environ['PATH_INFO']:
 
93
            # TODO: Use something here that uses the transport API 
 
94
            # rather than relying on the local filesystem API.
 
95
            try:
 
96
                path = urlutils.local_path_from_url(self.transport.base)
 
97
            except errors.InvalidURL:
 
98
                raise httpexceptions.HTTPNotFound()
 
99
            else:
 
100
                app = urlparser.make_static(None, path)
 
101
                return app(environ, start_response)
 
102
        else:
 
103
            return BranchesFromTransportServer(
 
104
                self.transport, self)(environ, start_response)
 
105
 
 
106
 
 
107
class UserBranchesFromTransportRoot(object):
 
108
 
 
109
    def __init__(self, transport, config):
 
110
        self.graph_cache = lru_cache.LRUCache(10)
 
111
        self.transport = transport
 
112
        self._config = config
 
113
        self.trunk_dir = config.get_option('trunk_dir')
 
114
 
 
115
    def __call__(self, environ, start_response):
 
116
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
 
117
        path_info = environ['PATH_INFO']
 
118
        if path_info.startswith('/static/'):
 
119
            segment = path_info_pop(environ)
 
120
            assert segment == 'static'
 
121
            return static_app(environ, start_response)
 
122
        elif path_info == '/favicon.ico':
 
123
            return favicon_app(environ, start_response)
 
124
        else:
 
125
            # segments starting with ~ are user branches
 
126
            if path_info.startswith('/~'):
 
127
                segment = path_info_pop(environ)
 
128
                new_transport = self.transport.clone(segment[1:])
 
129
                return BranchesFromTransportServer(
 
130
                    new_transport, self, segment)(environ, start_response)
 
131
            else:
 
132
                new_transport = self.transport.clone(self.trunk_dir)
 
133
                return BranchesFromTransportServer(
 
134
                    new_transport, self)(environ, start_response)