~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/memory.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-09-16 14:03:54 UTC
  • mfrom: (2017.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060916140354-1a9932f525bb7182
(robertc) Add MemoryTree and TreeBuilder test helpers. Also test behavior of transport.has('/') which caused failures in this when merging, and as a result cleanup the sftp path normalisation logic.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Implementation of Transport that uses memory for its storage.
18
18
 
27
27
from cStringIO import StringIO
28
28
import warnings
29
29
 
30
 
from bzrlib import (
31
 
    transport,
32
 
    urlutils,
33
 
    )
34
 
from bzrlib.errors import (
35
 
    FileExists,
36
 
    LockError,
37
 
    InProcessTransport,
38
 
    NoSuchFile,
39
 
    TransportError,
40
 
    )
 
30
from bzrlib.errors import TransportError, NoSuchFile, FileExists, LockError
41
31
from bzrlib.trace import mutter
42
 
from bzrlib.transport import (
43
 
    AppendBasedFileStream,
44
 
    _file_streams,
45
 
    LateReadError,
46
 
    )
 
32
from bzrlib.transport import (Transport, register_transport, Server)
 
33
import bzrlib.urlutils as urlutils
47
34
 
48
35
 
49
36
 
61
48
            self.st_mode = S_IFDIR | perms
62
49
 
63
50
 
64
 
class MemoryTransport(transport.Transport):
 
51
class MemoryTransport(Transport):
65
52
    """This is an in memory file system for transient data storage."""
66
53
 
67
54
    def __init__(self, url=""):
85
72
        if len(path) == 0 or path[-1] != '/':
86
73
            path += '/'
87
74
        url = self._scheme + path
88
 
        result = self.__class__(url)
 
75
        result = MemoryTransport(url)
89
76
        result._dirs = self._dirs
90
77
        result._files = self._files
91
78
        result._locks = self._locks
130
117
            raise NoSuchFile(relpath)
131
118
        del self._files[_abspath]
132
119
 
133
 
    def external_url(self):
134
 
        """See bzrlib.transport.Transport.external_url."""
135
 
        # MemoryTransport's are only accessible in-process
136
 
        # so we raise here
137
 
        raise InProcessTransport(self)
138
 
 
139
120
    def get(self, relpath):
140
121
        """See Transport.get()."""
141
122
        _abspath = self._abspath(relpath)
142
123
        if not _abspath in self._files:
143
 
            if _abspath in self._dirs:
144
 
                return LateReadError(relpath)
145
 
            else:
146
 
                raise NoSuchFile(relpath)
 
124
            raise NoSuchFile(relpath)
147
125
        return StringIO(self._files[_abspath][0])
148
126
 
149
127
    def put_file(self, relpath, f, mode=None):
150
128
        """See Transport.put_file()."""
151
129
        _abspath = self._abspath(relpath)
152
130
        self._check_parent(_abspath)
153
 
        bytes = f.read()
154
 
        if type(bytes) is not str:
155
 
            # Although not strictly correct, we raise UnicodeEncodeError to be
156
 
            # compatible with other transports.
157
 
            raise UnicodeEncodeError(
158
 
                'undefined', bytes, 0, 1,
159
 
                'put_file must be given a file of bytes, not unicode.')
160
 
        self._files[_abspath] = (bytes, mode)
161
 
        return len(bytes)
 
131
        self._files[_abspath] = (f.read(), mode)
162
132
 
163
133
    def mkdir(self, relpath, mode=None):
164
134
        """See Transport.mkdir()."""
168
138
            raise FileExists(relpath)
169
139
        self._dirs[_abspath]=mode
170
140
 
171
 
    def open_write_stream(self, relpath, mode=None):
172
 
        """See Transport.open_write_stream."""
173
 
        self.put_bytes(relpath, "", mode)
174
 
        result = AppendBasedFileStream(self, relpath)
175
 
        _file_streams[self.abspath(relpath)] = result
176
 
        return result
177
 
 
178
141
    def listable(self):
179
142
        """See Transport.listable."""
180
143
        return True
183
146
        for file in self._files:
184
147
            if file.startswith(self._cwd):
185
148
                yield urlutils.escape(file[len(self._cwd):])
186
 
 
 
149
    
187
150
    def list_dir(self, relpath):
188
151
        """See Transport.list_dir()."""
189
152
        _abspath = self._abspath(relpath)
190
153
        if _abspath != '/' and _abspath not in self._dirs:
191
154
            raise NoSuchFile(relpath)
192
155
        result = []
193
 
 
194
 
        if not _abspath.endswith('/'):
195
 
            _abspath += '/'
196
 
 
197
 
        for path_group in self._files, self._dirs:
198
 
            for path in path_group:
199
 
                if path.startswith(_abspath):
200
 
                    trailing = path[len(_abspath):]
201
 
                    if trailing and '/' not in trailing:
202
 
                        result.append(trailing)
 
156
        for path in self._files:
 
157
            if (path.startswith(_abspath) and 
 
158
                path[len(_abspath) + 1:].find('/') == -1 and
 
159
                len(path) > len(_abspath)):
 
160
                result.append(path[len(_abspath) + 1:])
 
161
        for path in self._dirs:
 
162
            if (path.startswith(_abspath) and 
 
163
                path[len(_abspath) + 1:].find('/') == -1 and
 
164
                len(path) > len(_abspath) and
 
165
                path[len(_abspath)] == '/'):
 
166
                result.append(path[len(_abspath) + 1:])
203
167
        return map(urlutils.escape, result)
204
168
 
205
169
    def rename(self, rel_from, rel_to):
222
186
                    del container[path]
223
187
        do_renames(self._files)
224
188
        do_renames(self._dirs)
225
 
 
 
189
    
226
190
    def rmdir(self, relpath):
227
191
        """See Transport.rmdir."""
228
192
        _abspath = self._abspath(relpath)
229
193
        if _abspath in self._files:
230
194
            self._translate_error(IOError(errno.ENOTDIR, relpath), relpath)
231
195
        for path in self._files:
232
 
            if path.startswith(_abspath + '/'):
 
196
            if path.startswith(_abspath):
233
197
                self._translate_error(IOError(errno.ENOTEMPTY, relpath),
234
198
                                      relpath)
235
199
        for path in self._dirs:
236
 
            if path.startswith(_abspath + '/') and path != _abspath:
 
200
            if path.startswith(_abspath) and path != _abspath:
237
201
                self._translate_error(IOError(errno.ENOTEMPTY, relpath), relpath)
238
202
        if not _abspath in self._dirs:
239
203
            raise NoSuchFile(relpath)
243
207
        """See Transport.stat()."""
244
208
        _abspath = self._abspath(relpath)
245
209
        if _abspath in self._files:
246
 
            return MemoryStat(len(self._files[_abspath][0]), False,
 
210
            return MemoryStat(len(self._files[_abspath][0]), False, 
247
211
                              self._files[_abspath][1])
248
212
        elif _abspath in self._dirs:
249
213
            return MemoryStat(0, True, self._dirs[_abspath])
261
225
    def _abspath(self, relpath):
262
226
        """Generate an internal absolute path."""
263
227
        relpath = urlutils.unescape(relpath)
264
 
        if relpath[:1] == '/':
 
228
        if relpath.find('..') != -1:
 
229
            raise AssertionError('relpath contains ..')
 
230
        if relpath == '':
 
231
            return '/'
 
232
        if relpath[0] == '/':
265
233
            return relpath
266
 
        cwd_parts = self._cwd.split('/')
267
 
        rel_parts = relpath.split('/')
268
 
        r = []
269
 
        for i in cwd_parts + rel_parts:
270
 
            if i == '..':
271
 
                if not r:
272
 
                    raise ValueError("illegal relpath %r under %r"
273
 
                        % (relpath, self._cwd))
274
 
                r = r[:-1]
275
 
            elif i == '.' or i == '':
276
 
                pass
277
 
            else:
278
 
                r.append(i)
279
 
        return '/' + '/'.join(r)
 
234
        if relpath == '.':
 
235
            if (self._cwd == '/'):
 
236
                return self._cwd
 
237
            return self._cwd[:-1]
 
238
        if relpath.endswith('/'):
 
239
            relpath = relpath[:-1]
 
240
        if relpath.startswith('./'):
 
241
            relpath = relpath[2:]
 
242
        return self._cwd + relpath
280
243
 
281
244
 
282
245
class _MemoryLock(object):
283
246
    """This makes a lock."""
284
247
 
285
248
    def __init__(self, path, transport):
 
249
        assert isinstance(transport, MemoryTransport)
286
250
        self.path = path
287
251
        self.transport = transport
288
252
        if self.path in self.transport._locks:
289
253
            raise LockError('File %r already locked' % (self.path,))
290
254
        self.transport._locks[self.path] = self
291
255
 
 
256
    def __del__(self):
 
257
        # Should this warn, or actually try to cleanup?
 
258
        if self.transport:
 
259
            warnings.warn("MemoryLock %r not explicitly unlocked" % (self.path,))
 
260
            self.unlock()
 
261
 
292
262
    def unlock(self):
293
263
        del self.transport._locks[self.path]
294
264
        self.transport = None
295
265
 
296
266
 
297
 
class MemoryServer(transport.Server):
 
267
class MemoryServer(Server):
298
268
    """Server for the MemoryTransport for testing with."""
299
269
 
300
 
    def start_server(self):
 
270
    def setUp(self):
 
271
        """See bzrlib.transport.Server.setUp."""
301
272
        self._dirs = {'/':None}
302
273
        self._files = {}
303
274
        self._locks = {}
304
275
        self._scheme = "memory+%s:///" % id(self)
305
276
        def memory_factory(url):
306
 
            from bzrlib.transport import memory
307
 
            result = memory.MemoryTransport(url)
 
277
            result = MemoryTransport(url)
308
278
            result._dirs = self._dirs
309
279
            result._files = self._files
310
280
            result._locks = self._locks
311
281
            return result
312
 
        self._memory_factory = memory_factory
313
 
        transport.register_transport(self._scheme, self._memory_factory)
 
282
        register_transport(self._scheme, memory_factory)
314
283
 
315
 
    def stop_server(self):
 
284
    def tearDown(self):
 
285
        """See bzrlib.transport.Server.tearDown."""
316
286
        # unregister this server
317
 
        transport.unregister_transport(self._scheme, self._memory_factory)
318
287
 
319
288
    def get_url(self):
320
289
        """See bzrlib.transport.Server.get_url."""
321
290
        return self._scheme
322
291
 
323
 
    def get_bogus_url(self):
324
 
        raise NotImplementedError
325
 
 
326
292
 
327
293
def get_test_permutations():
328
294
    """Return the permutations to be used in testing."""