~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/http.py

  • Committer: Martin Pool
  • Date: 2005-04-29 03:32:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050429033239-43b3a4781828f11d
todo

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 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
 
"""Implementation of Transport over http.
17
 
"""
18
 
 
19
 
from bzrlib.transport import Transport, register_transport
20
 
from bzrlib.errors import (TransportNotPossible, NoSuchFile, 
21
 
                           NonRelativePath, TransportError)
22
 
import os, errno
23
 
from cStringIO import StringIO
24
 
import urllib2
25
 
import urlparse
26
 
 
27
 
from bzrlib.errors import BzrError, BzrCheckError
28
 
from bzrlib.branch import Branch
29
 
from bzrlib.trace import mutter
30
 
 
31
 
 
32
 
def get_url(url):
33
 
    import urllib2
34
 
    mutter("get_url %s" % url)
35
 
    url_f = urllib2.urlopen(url)
36
 
    return url_f
37
 
 
38
 
class HttpTransportError(TransportError):
39
 
    pass
40
 
 
41
 
class HttpTransport(Transport):
42
 
    """This is the transport agent for http:// access.
43
 
    
44
 
    TODO: Implement pipelined versions of all of the *_multi() functions.
45
 
    """
46
 
 
47
 
    def __init__(self, base):
48
 
        """Set the base path where files will be stored."""
49
 
        assert base.startswith('http://') or base.startswith('https://')
50
 
        super(HttpTransport, self).__init__(base)
51
 
        # In the future we might actually connect to the remote host
52
 
        # rather than using get_url
53
 
        # self._connection = None
54
 
        (self._proto, self._host,
55
 
            self._path, self._parameters,
56
 
            self._query, self._fragment) = urlparse.urlparse(self.base)
57
 
 
58
 
    def should_cache(self):
59
 
        """Return True if the data pulled across should be cached locally.
60
 
        """
61
 
        return True
62
 
 
63
 
    def clone(self, offset=None):
64
 
        """Return a new HttpTransport with root at self.base + offset
65
 
        For now HttpTransport does not actually connect, so just return
66
 
        a new HttpTransport object.
67
 
        """
68
 
        if offset is None:
69
 
            return HttpTransport(self.base)
70
 
        else:
71
 
            return HttpTransport(self.abspath(offset))
72
 
 
73
 
    def abspath(self, relpath):
74
 
        """Return the full url to the given relative path.
75
 
        This can be supplied with a string or a list
76
 
        """
77
 
        if isinstance(relpath, basestring):
78
 
            relpath_parts = relpath.split('/')
79
 
        else:
80
 
            # TODO: Don't call this with an array - no magic interfaces
81
 
            relpath_parts = relpath[:]
82
 
        if len(relpath_parts) > 1:
83
 
            if relpath_parts[0] == '':
84
 
                raise ValueError("path %r within branch %r seems to be absolute"
85
 
                                 % (relpath, self._path))
86
 
            if relpath_parts[-1] == '':
87
 
                raise ValueError("path %r within branch %r seems to be a directory"
88
 
                                 % (relpath, self._path))
89
 
        basepath = self._path.split('/')
90
 
        if len(basepath) > 0 and basepath[-1] == '':
91
 
            basepath = basepath[:-1]
92
 
        for p in relpath_parts:
93
 
            if p == '..':
94
 
                if len(basepath) == 0:
95
 
                    # In most filesystems, a request for the parent
96
 
                    # of root, just returns root.
97
 
                    continue
98
 
                basepath.pop()
99
 
            elif p == '.' or p == '':
100
 
                continue # No-op
101
 
            else:
102
 
                basepath.append(p)
103
 
        # Possibly, we could use urlparse.urljoin() here, but
104
 
        # I'm concerned about when it chooses to strip the last
105
 
        # portion of the path, and when it doesn't.
106
 
        path = '/'.join(basepath)
107
 
        return urlparse.urlunparse((self._proto,
108
 
                self._host, path, '', '', ''))
109
 
 
110
 
    def has(self, relpath):
111
 
        """Does the target location exist?
112
 
 
113
 
        TODO: HttpTransport.has() should use a HEAD request,
114
 
        not a full GET request.
115
 
 
116
 
        TODO: This should be changed so that we don't use
117
 
        urllib2 and get an exception, the code path would be
118
 
        cleaner if we just do an http HEAD request, and parse
119
 
        the return code.
120
 
        """
121
 
        try:
122
 
            f = get_url(self.abspath(relpath))
123
 
            # Without the read and then close()
124
 
            # we tend to have busy sockets.
125
 
            f.read()
126
 
            f.close()
127
 
            return True
128
 
        except BzrError:
129
 
            return False
130
 
        except urllib2.URLError:
131
 
            return False
132
 
        except IOError, e:
133
 
            if e.errno == errno.ENOENT:
134
 
                return False
135
 
            raise HttpTransportError(orig_error=e)
136
 
 
137
 
    def get(self, relpath, decode=False):
138
 
        """Get the file at the given relative path.
139
 
 
140
 
        :param relpath: The relative path to the file
141
 
        """
142
 
        try:
143
 
            return get_url(self.abspath(relpath))
144
 
        except (BzrError, urllib2.URLError, IOError), e:
145
 
            raise NoSuchFile(msg = "Error retrieving %s: %s" 
146
 
                             % (self.abspath(relpath), str(e)),
147
 
                             orig_error=e)
148
 
 
149
 
    def put(self, relpath, f):
150
 
        """Copy the file-like or string object into the location.
151
 
 
152
 
        :param relpath: Location to put the contents, relative to base.
153
 
        :param f:       File-like or string object.
154
 
        """
155
 
        raise TransportNotPossible('http PUT not supported')
156
 
 
157
 
    def mkdir(self, relpath):
158
 
        """Create a directory at the given path."""
159
 
        raise TransportNotPossible('http does not support mkdir()')
160
 
 
161
 
    def append(self, relpath, f):
162
 
        """Append the text in the file-like object into the final
163
 
        location.
164
 
        """
165
 
        raise TransportNotPossible('http does not support append()')
166
 
 
167
 
    def copy(self, rel_from, rel_to):
168
 
        """Copy the item at rel_from to the location at rel_to"""
169
 
        raise TransportNotPossible('http does not support copy()')
170
 
 
171
 
    def copy_to(self, relpaths, other, pb=None):
172
 
        """Copy a set of entries from self into another Transport.
173
 
 
174
 
        :param relpaths: A list/generator of entries to be copied.
175
 
 
176
 
        TODO: if other is LocalTransport, is it possible to
177
 
              do better than put(get())?
178
 
        """
179
 
        # At this point HttpTransport might be able to check and see if
180
 
        # the remote location is the same, and rather than download, and
181
 
        # then upload, it could just issue a remote copy_this command.
182
 
        if isinstance(other, HttpTransport):
183
 
            raise TransportNotPossible('http cannot be the target of copy_to()')
184
 
        else:
185
 
            return super(HttpTransport, self).copy_to(relpaths, other, pb=pb)
186
 
 
187
 
    def move(self, rel_from, rel_to):
188
 
        """Move the item at rel_from to the location at rel_to"""
189
 
        raise TransportNotPossible('http does not support move()')
190
 
 
191
 
    def delete(self, relpath):
192
 
        """Delete the item at relpath"""
193
 
        raise TransportNotPossible('http does not support delete()')
194
 
 
195
 
    def listable(self):
196
 
        """See Transport.listable."""
197
 
        return False
198
 
 
199
 
    def stat(self, relpath):
200
 
        """Return the stat information for a file.
201
 
        """
202
 
        raise TransportNotPossible('http does not support stat()')
203
 
 
204
 
    def lock_read(self, relpath):
205
 
        """Lock the given file for shared (read) access.
206
 
        :return: A lock object, which should be passed to Transport.unlock()
207
 
        """
208
 
        # The old RemoteBranch ignore lock for reading, so we will
209
 
        # continue that tradition and return a bogus lock object.
210
 
        class BogusLock(object):
211
 
            def __init__(self, path):
212
 
                self.path = path
213
 
            def unlock(self):
214
 
                pass
215
 
        return BogusLock(relpath)
216
 
 
217
 
    def lock_write(self, relpath):
218
 
        """Lock the given file for exclusive (write) access.
219
 
        WARNING: many transports do not support this, so trying avoid using it
220
 
 
221
 
        :return: A lock object, which should be passed to Transport.unlock()
222
 
        """
223
 
        raise TransportNotPossible('http does not support lock_write()')
224
 
 
225
 
register_transport('http://', HttpTransport)
226
 
register_transport('https://', HttpTransport)