~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to wsgitest.py

  • Committer: Michael Hudson
  • Date: 2008-06-18 01:08:59 UTC
  • mto: This revision was merged to the branch mainline in revision 164.
  • Revision ID: michael.hudson@canonical.com-20080618010859-euunmral6tiuioxh
create loggerhead.apps package, move branch app in there

Show diffs side-by-side

added added

removed removed

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