~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/remotebranch.py

Refactored the export code to make it easier to add new export formats.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
 
 
3
 
# Copyright (C) 2005 Canonical Ltd
4
 
 
5
 
# This program is free software; you can redistribute it and/or modify
6
 
# it under the terms of the GNU General Public License as published by
7
 
# the Free Software Foundation; either version 2 of the License, or
8
 
# (at your option) any later version.
9
 
 
10
 
# This program is distributed in the hope that it will be useful,
11
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 
# GNU General Public License for more details.
14
 
 
15
 
# You should have received a copy of the GNU General Public License
16
 
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 
 
19
 
 
20
 
"""Proxy object for access to remote branches.
21
 
 
22
 
At the moment remote branches are only for HTTP and only for read
23
 
access.
24
 
"""
25
 
 
26
 
 
27
 
import gzip
28
 
from cStringIO import StringIO
29
 
import os
30
 
import urllib2
31
 
 
32
 
from bzrlib.errors import BzrError, BzrCheckError
33
 
from bzrlib.branch import Branch, BZR_BRANCH_FORMAT
34
 
from bzrlib.trace import mutter
35
 
from bzrlib.xml import serializer_v4
36
 
 
37
 
 
38
 
ENABLE_URLGRABBER = False
39
 
 
40
 
from bzrlib.errors import BzrError, NoSuchRevision
41
 
 
42
 
class GetFailed(BzrError):
43
 
    def __init__(self, url, status):
44
 
        BzrError.__init__(self, "Get %s failed with status %s" % (url, status))
45
 
        self.url = url
46
 
        self.status = status
47
 
 
48
 
if ENABLE_URLGRABBER:
49
 
    import util.urlgrabber
50
 
    import util.urlgrabber.keepalive
51
 
    util.urlgrabber.keepalive.DEBUG = 0
52
 
    def get_url(path, compressed=False):
53
 
        try:
54
 
            url = path
55
 
            if compressed:
56
 
                url += '.gz'
57
 
            mutter("grab url %s" % url)
58
 
            url_f = util.urlgrabber.urlopen(url, keepalive=1, close_connection=0)
59
 
            if url_f.status != 200:
60
 
                raise GetFailed(url, url_f.status)
61
 
            if not compressed:
62
 
                return url_f
63
 
            else:
64
 
                return gzip.GzipFile(fileobj=StringIO(url_f.read()))
65
 
        except urllib2.URLError, e:
66
 
            raise BzrError("remote fetch failed: %r: %s" % (url, e))
67
 
else:
68
 
    def get_url(url, compressed=False):
69
 
        import urllib2
70
 
        if compressed:
71
 
            url += '.gz'
72
 
        mutter("get_url %s" % url)
73
 
        url_f = urllib2.urlopen(url)
74
 
        if compressed:
75
 
            return gzip.GzipFile(fileobj=StringIO(url_f.read()))
76
 
        else:
77
 
            return url_f
78
 
 
79
 
 
80
 
 
81
 
def _find_remote_root(url):
82
 
    """Return the prefix URL that corresponds to the branch root."""
83
 
    orig_url = url
84
 
    while True:
85
 
        try:
86
 
            ff = get_url(url + '/.bzr/branch-format')
87
 
 
88
 
            fmt = ff.read()
89
 
            ff.close()
90
 
 
91
 
            fmt = fmt.rstrip('\r\n')
92
 
            if fmt != BZR_BRANCH_FORMAT.rstrip('\r\n'):
93
 
                raise BzrError("sorry, branch format %r not supported at url %s"
94
 
                               % (fmt, url))
95
 
            
96
 
            return url
97
 
        except urllib2.URLError:
98
 
            pass
99
 
 
100
 
        try:
101
 
            idx = url.rindex('/')
102
 
        except ValueError:
103
 
            raise BzrError('no branch root found for URL %s' % orig_url)
104
 
 
105
 
        url = url[:idx]        
106
 
 
107
 
 
108
 
class RemoteBranch(Branch):
109
 
    def __init__(self, baseurl, find_root=True):
110
 
        """Create new proxy for a remote branch."""
111
 
        if find_root:
112
 
            self.base = _find_remote_root(baseurl)
113
 
        else:
114
 
            self.base = baseurl
115
 
            self._check_format()
116
 
 
117
 
        self.inventory_store = RemoteStore(baseurl + '/.bzr/inventory-store/')
118
 
        self.text_store = RemoteStore(baseurl + '/.bzr/text-store/')
119
 
        self.revision_store = RemoteStore(baseurl + '/.bzr/revision-store/')
120
 
 
121
 
    def __str__(self):
122
 
        b = getattr(self, 'baseurl', 'undefined')
123
 
        return '%s(%r)' % (self.__class__.__name__, b)
124
 
 
125
 
    __repr__ = __str__
126
 
 
127
 
    def setup_caching(self, cache_root):
128
 
        """Set up cached stores located under cache_root"""
129
 
        from bzrlib.meta_store import CachedStore
130
 
        for store_name in ('inventory_store', 'text_store', 'revision_store'):
131
 
            if not isinstance(getattr(self, store_name), CachedStore):
132
 
                cache_path = os.path.join(cache_root, store_name)
133
 
                os.mkdir(cache_path)
134
 
                new_store = CachedStore(getattr(self, store_name), cache_path)
135
 
                setattr(self, store_name, new_store)
136
 
 
137
 
    def controlfile(self, filename, mode):
138
 
        if mode not in ('rb', 'rt', 'r'):
139
 
            raise BzrError("file mode %r not supported for remote branches" % mode)
140
 
        return get_url(self.base + '/.bzr/' + filename, False)
141
 
 
142
 
 
143
 
    def lock_read(self):
144
 
        # no locking for remote branches yet
145
 
        pass
146
 
 
147
 
    def lock_write(self):
148
 
        from errors import LockError
149
 
        raise LockError("write lock not supported for remote branch %s"
150
 
                        % self.base)
151
 
 
152
 
    def unlock(self):
153
 
        pass
154
 
    
155
 
 
156
 
    def relpath(self, path):
157
 
        if not path.startswith(self.base):
158
 
            raise BzrError('path %r is not under base URL %r'
159
 
                           % (path, self.base))
160
 
        pl = len(self.base)
161
 
        return path[pl:].lstrip('/')
162
 
 
163
 
 
164
 
    def get_revision(self, revision_id):
165
 
        try:
166
 
            revf = self.revision_store[revision_id]
167
 
        except KeyError:
168
 
            raise NoSuchRevision(self, revision_id)
169
 
        r = serializer_v4.read_revision(revf)
170
 
        if r.revision_id != revision_id:
171
 
            raise BzrCheckError('revision stored as {%s} actually contains {%s}'
172
 
                                % (revision_id, r.revision_id))
173
 
        return r
174
 
 
175
 
 
176
 
class RemoteStore(object):
177
 
    def __init__(self, baseurl):
178
 
        self._baseurl = baseurl
179
 
        
180
 
 
181
 
    def _path(self, name):
182
 
        if '/' in name:
183
 
            raise ValueError('invalid store id', name)
184
 
        return self._baseurl + '/' + name
185
 
        
186
 
    def __getitem__(self, fileid):
187
 
        p = self._path(fileid)
188
 
        try:
189
 
            return get_url(p, compressed=True)
190
 
        except:
191
 
            raise KeyError(fileid)
192
 
    
193
 
 
194