~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/apps/filesystem.py

  • Committer: Michael Hudson
  • Date: 2009-03-07 03:13:41 UTC
  • mfrom: (294.1.2 annotate-indexerror)
  • Revision ID: michael.hudson@canonical.com-20090307031341-sy37dnqu6i9a0xb7
* fix a trivial mistake with the display of renamed files
* allow for the fact that pygments strips trailing whitespace from files.
  (bug #338762)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2011 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
 
1
"""Serve branches at urls that mimic the file system layout."""
 
2
 
 
3
import os
 
4
import tempfile
 
5
 
 
6
from bzrlib import branch, errors, lru_cache
26
7
 
27
8
from paste.request import path_info_pop
28
9
from paste import httpexceptions
29
10
from paste import urlparser
30
11
 
31
 
from loggerhead import util
32
12
from loggerhead.apps.branch import BranchWSGIApp
33
 
from loggerhead.apps import favicon_app, robots_app, static_app
 
13
from loggerhead.apps import favicon_app, static_app
34
14
from loggerhead.controllers.directory_ui import DirectoryUI
35
15
 
36
 
# TODO: Use bzrlib.ui.bool_from_string(), added in bzr 1.18
37
 
_bools = {
38
 
    'yes': True, 'no': False,
39
 
    'on': True, 'off': False,
40
 
    '1': True, '0': False,
41
 
    'true': True, 'false': False,
42
 
    }
43
 
 
44
 
class BranchesFromTransportServer(object):
45
 
 
46
 
    def __init__(self, transport, root, name=None):
47
 
        self.transport = transport
 
16
sql_dir = tempfile.mkdtemp(prefix='loggerhead-cache-')
 
17
 
 
18
 
 
19
class BranchesFromFileSystemServer(object):
 
20
 
 
21
    def __init__(self, path, root, name=None):
 
22
        self.path = path
48
23
        self.root = root
49
24
        self.name = name
50
 
        self._config = root._config
51
25
 
52
26
    def app_for_branch(self, branch):
53
27
        if not self.name:
54
 
            name = branch._get_nick(local=True)
 
28
            name = branch.get_config().get_nickname()
55
29
            is_root = True
56
30
        else:
57
31
            name = self.name
58
32
            is_root = False
59
33
        branch_app = BranchWSGIApp(
60
 
            branch,
61
 
            name,
62
 
            {'cachepath': self._config.SQL_DIR},
63
 
            self.root.graph_cache,
64
 
            is_root=is_root,
65
 
            use_cdn=self._config.get_option('use_cdn'),
66
 
            )
 
34
            branch, name, {'cachepath': sql_dir}, self.root.graph_cache,
 
35
            is_root=is_root)
67
36
        return branch_app.app
68
37
 
69
38
    def app_for_non_branch(self, environ):
70
39
        segment = path_info_pop(environ)
71
40
        if segment is None:
72
 
            raise httpexceptions.HTTPMovedPermanently.relative_redirect(
73
 
                environ['SCRIPT_NAME'] + '/', environ)
 
41
            raise httpexceptions.HTTPMovedPermanently(
 
42
                environ['SCRIPT_NAME'] + '/')
74
43
        elif segment == '':
75
44
            if self.name:
76
45
                name = self.name
77
46
            else:
78
47
                name = '/'
79
 
            return DirectoryUI(
80
 
                environ['loggerhead.static.url'], self.transport, name)
 
48
            return DirectoryUI(environ['loggerhead.static.url'],
 
49
                               self.path,
 
50
                               name)
81
51
        else:
82
 
            new_transport = self.transport.clone(segment)
 
52
            new_path = os.path.join(self.path, segment)
83
53
            if self.name:
84
 
                new_name = urlutils.join(self.name, segment)
 
54
                new_name = os.path.join(self.name, segment)
85
55
            else:
86
56
                new_name = '/' + segment
87
 
            return BranchesFromTransportServer(new_transport, self.root, new_name)
88
 
 
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')
94
 
        else:
95
 
            # TODO: Use something here that uses the transport API
96
 
            # rather than relying on the local filesystem API.
97
 
            base = self.transport.base
98
 
            try:
99
 
                path = util.local_path_from_url(base)
100
 
            except errors.InvalidURL:
101
 
                raise httpexceptions.HTTPNotFound()
102
 
            else:
103
 
                return urlparser.make_static(None, path)
104
 
 
105
 
    def check_serveable(self, config):
106
 
        value = config.get_user_option('http_serve')
107
 
        if value is None:
108
 
            return
109
 
        elif not _bools.get(value.lower(), True):
 
57
            return BranchesFromFileSystemServer(new_path, self.root, new_name)
 
58
 
 
59
    def __call__(self, environ, start_response):
 
60
        if not os.path.isdir(self.path):
110
61
            raise httpexceptions.HTTPNotFound()
111
 
 
112
 
    def __call__(self, environ, start_response):
113
 
        path = environ['PATH_INFO']
114
62
        try:
115
 
            b = branch.Branch.open_from_transport(self.transport)
 
63
            b = branch.Branch.open(self.path)
116
64
        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
65
            return self.app_for_non_branch(environ)(environ, start_response)
123
66
        else:
124
 
            self.check_serveable(b.get_config())
125
 
            if path.startswith('/.bzr'):
126
 
                return self.app_for_bazaar_data(path)(environ, start_response)
127
 
            else:
128
 
                return self.app_for_branch(b)(environ, start_response)
129
 
 
130
 
 
131
 
_transport_store = threading.local()
132
 
 
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
141
 
    return transport
142
 
 
143
 
 
144
 
class BranchesFromTransportRoot(object):
145
 
 
146
 
    def __init__(self, base, config):
147
 
        self.graph_cache = lru_cache.LRUCache(10)
148
 
        self.base = base
149
 
        self._config = config
 
67
            return self.app_for_branch(b)(environ, start_response)
 
68
 
 
69
 
 
70
class BranchesFromFileSystemRoot(object):
 
71
 
 
72
    def __init__(self, folder):
 
73
        self.graph_cache = lru_cache.LRUCache()
 
74
        self.folder = folder
150
75
 
151
76
    def __call__(self, environ, start_response):
152
77
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
153
 
        environ['loggerhead.path_info'] = environ['PATH_INFO']
154
78
        if environ['PATH_INFO'].startswith('/static/'):
155
79
            segment = path_info_pop(environ)
156
80
            assert segment == 'static'
157
81
            return static_app(environ, start_response)
158
82
        elif environ['PATH_INFO'] == '/favicon.ico':
159
83
            return favicon_app(environ, start_response)
160
 
        elif environ['PATH_INFO'] == '/robots.txt':
161
 
            return robots_app(environ, start_response)
 
84
        elif '/.bzr/' in environ['PATH_INFO']:
 
85
            app = urlparser.make_static(None, self.folder)
 
86
            return app(environ, start_response)
162
87
        else:
163
 
            transport = get_transport_for_thread(self.base)
164
 
            return BranchesFromTransportServer(
165
 
                transport, self)(environ, start_response)
166
 
 
167
 
 
168
 
class UserBranchesFromTransportRoot(object):
169
 
 
170
 
    def __init__(self, base, config):
171
 
        self.graph_cache = lru_cache.LRUCache(10)
172
 
        self.base = base
173
 
        self._config = config
174
 
        self.trunk_dir = config.get_option('trunk_dir')
 
88
            return BranchesFromFileSystemServer(
 
89
                self.folder, self)(environ, start_response)
 
90
 
 
91
 
 
92
class UserBranchesFromFileSystemRoot(object):
 
93
 
 
94
    def __init__(self, folder, trunk_dir):
 
95
        self.graph_cache = lru_cache.LRUCache()
 
96
        self.folder = folder
 
97
        self.trunk_dir = trunk_dir
175
98
 
176
99
    def __call__(self, environ, start_response):
177
100
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
178
 
        environ['loggerhead.path_info'] = environ['PATH_INFO']
179
 
        path_info = environ['PATH_INFO']
 
101
        path_info= environ['PATH_INFO']
180
102
        if path_info.startswith('/static/'):
181
103
            segment = path_info_pop(environ)
182
104
            assert segment == 'static'
183
105
            return static_app(environ, start_response)
184
106
        elif path_info == '/favicon.ico':
185
107
            return favicon_app(environ, start_response)
186
 
        elif environ['PATH_INFO'] == '/robots.txt':
187
 
            return robots_app(environ, start_response)
188
108
        else:
189
 
            transport = get_transport_for_thread(self.base)
190
109
            # segments starting with ~ are user branches
191
110
            if path_info.startswith('/~'):
192
111
                segment = path_info_pop(environ)
193
 
                return BranchesFromTransportServer(
194
 
                    transport.clone(segment[1:]), self, segment)(
195
 
                    environ, start_response)
 
112
                new_path = os.path.join(self.folder, segment[1:])
 
113
                return BranchesFromFileSystemServer(
 
114
                    new_path, self, segment)(environ, start_response)
196
115
            else:
197
 
                return BranchesFromTransportServer(
198
 
                    transport.clone(self.trunk_dir), self)(
199
 
                    environ, start_response)
 
116
                new_path = os.path.join(self.folder, self.trunk_dir)
 
117
                return BranchesFromFileSystemServer(
 
118
                    new_path, self)(environ, start_response)