~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: 2007-03-28 06:58:22 UTC
  • mfrom: (2379.2.3 hpss-chroot)
  • Revision ID: pqm@pqm.ubuntu.com-20070328065822-999550a858a3ced3
(robertc) Fix chroot urls to not expose the url of the transport they are protecting, allowing regular url operations to work on them. (Robert Collins, Andrew Bennetts)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011, 2016 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
 
20
20
so this is primarily useful for testing.
21
21
"""
22
22
 
23
 
from __future__ import absolute_import
24
 
 
25
23
import os
26
24
import errno
 
25
import re
27
26
from stat import S_IFREG, S_IFDIR
28
27
from cStringIO import StringIO
 
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
 
    )
40
 
from bzrlib.transport import (
41
 
    AppendBasedFileStream,
42
 
    _file_streams,
43
 
    LateReadError,
44
 
    )
 
30
from bzrlib.errors import TransportError, NoSuchFile, FileExists, LockError
 
31
from bzrlib.trace import mutter
 
32
from bzrlib.transport import (Transport, register_transport, Server)
 
33
import bzrlib.urlutils as urlutils
45
34
 
46
35
 
47
36
 
59
48
            self.st_mode = S_IFDIR | perms
60
49
 
61
50
 
62
 
class MemoryTransport(transport.Transport):
 
51
class MemoryTransport(Transport):
63
52
    """This is an in memory file system for transient data storage."""
64
53
 
65
54
    def __init__(self, url=""):
79
68
 
80
69
    def clone(self, offset=None):
81
70
        """See Transport.clone()."""
82
 
        path = urlutils.URL._combine_paths(self._cwd, offset)
 
71
        path = self._combine_paths(self._cwd, offset)
83
72
        if len(path) == 0 or path[-1] != '/':
84
73
            path += '/'
85
74
        url = self._scheme + path
86
 
        result = self.__class__(url)
 
75
        result = MemoryTransport(url)
87
76
        result._dirs = self._dirs
88
77
        result._files = self._files
89
78
        result._locks = self._locks
128
117
            raise NoSuchFile(relpath)
129
118
        del self._files[_abspath]
130
119
 
131
 
    def external_url(self):
132
 
        """See bzrlib.transport.Transport.external_url."""
133
 
        # MemoryTransport's are only accessible in-process
134
 
        # so we raise here
135
 
        raise InProcessTransport(self)
136
 
 
137
120
    def get(self, relpath):
138
121
        """See Transport.get()."""
139
122
        _abspath = self._abspath(relpath)
140
123
        if not _abspath in self._files:
141
 
            if _abspath in self._dirs:
142
 
                return LateReadError(relpath)
143
 
            else:
144
 
                raise NoSuchFile(relpath)
 
124
            raise NoSuchFile(relpath)
145
125
        return StringIO(self._files[_abspath][0])
146
126
 
147
127
    def put_file(self, relpath, f, mode=None):
148
128
        """See Transport.put_file()."""
149
129
        _abspath = self._abspath(relpath)
150
130
        self._check_parent(_abspath)
151
 
        raw_bytes = f.read()
152
 
        self._files[_abspath] = (raw_bytes, mode)
153
 
        return len(raw_bytes)
 
131
        self._files[_abspath] = (f.read(), mode)
154
132
 
155
133
    def mkdir(self, relpath, mode=None):
156
134
        """See Transport.mkdir()."""
160
138
            raise FileExists(relpath)
161
139
        self._dirs[_abspath]=mode
162
140
 
163
 
    def open_write_stream(self, relpath, mode=None):
164
 
        """See Transport.open_write_stream."""
165
 
        self.put_bytes(relpath, "", mode)
166
 
        result = AppendBasedFileStream(self, relpath)
167
 
        _file_streams[self.abspath(relpath)] = result
168
 
        return result
169
 
 
170
141
    def listable(self):
171
142
        """See Transport.listable."""
172
143
        return True
175
146
        for file in self._files:
176
147
            if file.startswith(self._cwd):
177
148
                yield urlutils.escape(file[len(self._cwd):])
178
 
 
 
149
    
179
150
    def list_dir(self, relpath):
180
151
        """See Transport.list_dir()."""
181
152
        _abspath = self._abspath(relpath)
214
185
                    del container[path]
215
186
        do_renames(self._files)
216
187
        do_renames(self._dirs)
217
 
 
 
188
    
218
189
    def rmdir(self, relpath):
219
190
        """See Transport.rmdir."""
220
191
        _abspath = self._abspath(relpath)
235
206
        """See Transport.stat()."""
236
207
        _abspath = self._abspath(relpath)
237
208
        if _abspath in self._files:
238
 
            return MemoryStat(len(self._files[_abspath][0]), False,
 
209
            return MemoryStat(len(self._files[_abspath][0]), False, 
239
210
                              self._files[_abspath][1])
240
211
        elif _abspath in self._dirs:
241
212
            return MemoryStat(0, True, self._dirs[_abspath])
253
224
    def _abspath(self, relpath):
254
225
        """Generate an internal absolute path."""
255
226
        relpath = urlutils.unescape(relpath)
256
 
        if relpath[:1] == '/':
 
227
        if relpath.find('..') != -1:
 
228
            raise AssertionError('relpath contains ..')
 
229
        if relpath == '':
 
230
            return '/'
 
231
        if relpath[0] == '/':
257
232
            return relpath
258
 
        cwd_parts = self._cwd.split('/')
259
 
        rel_parts = relpath.split('/')
260
 
        r = []
261
 
        for i in cwd_parts + rel_parts:
262
 
            if i == '..':
263
 
                if not r:
264
 
                    raise ValueError("illegal relpath %r under %r"
265
 
                        % (relpath, self._cwd))
266
 
                r = r[:-1]
267
 
            elif i == '.' or i == '':
268
 
                pass
269
 
            else:
270
 
                r.append(i)
271
 
        return '/' + '/'.join(r)
 
233
        if relpath == '.':
 
234
            if (self._cwd == '/'):
 
235
                return self._cwd
 
236
            return self._cwd[:-1]
 
237
        if relpath.endswith('/'):
 
238
            relpath = relpath[:-1]
 
239
        if relpath.startswith('./'):
 
240
            relpath = relpath[2:]
 
241
        return self._cwd + relpath
272
242
 
273
243
 
274
244
class _MemoryLock(object):
275
245
    """This makes a lock."""
276
246
 
277
247
    def __init__(self, path, transport):
 
248
        assert isinstance(transport, MemoryTransport)
278
249
        self.path = path
279
250
        self.transport = transport
280
251
        if self.path in self.transport._locks:
281
252
            raise LockError('File %r already locked' % (self.path,))
282
253
        self.transport._locks[self.path] = self
283
254
 
 
255
    def __del__(self):
 
256
        # Should this warn, or actually try to cleanup?
 
257
        if self.transport:
 
258
            warnings.warn("MemoryLock %r not explicitly unlocked" % (self.path,))
 
259
            self.unlock()
 
260
 
284
261
    def unlock(self):
285
262
        del self.transport._locks[self.path]
286
263
        self.transport = None
287
264
 
288
265
 
289
 
class MemoryServer(transport.Server):
 
266
class MemoryServer(Server):
290
267
    """Server for the MemoryTransport for testing with."""
291
268
 
292
 
    def start_server(self):
 
269
    def setUp(self):
 
270
        """See bzrlib.transport.Server.setUp."""
293
271
        self._dirs = {'/':None}
294
272
        self._files = {}
295
273
        self._locks = {}
296
274
        self._scheme = "memory+%s:///" % id(self)
297
275
        def memory_factory(url):
298
 
            from bzrlib.transport import memory
299
 
            result = memory.MemoryTransport(url)
 
276
            result = MemoryTransport(url)
300
277
            result._dirs = self._dirs
301
278
            result._files = self._files
302
279
            result._locks = self._locks
303
280
            return result
304
 
        self._memory_factory = memory_factory
305
 
        transport.register_transport(self._scheme, self._memory_factory)
 
281
        register_transport(self._scheme, memory_factory)
306
282
 
307
 
    def stop_server(self):
 
283
    def tearDown(self):
 
284
        """See bzrlib.transport.Server.tearDown."""
308
285
        # unregister this server
309
 
        transport.unregister_transport(self._scheme, self._memory_factory)
310
286
 
311
287
    def get_url(self):
312
288
        """See bzrlib.transport.Server.get_url."""
313
289
        return self._scheme
314
290
 
315
 
    def get_bogus_url(self):
316
 
        raise NotImplementedError
317
 
 
318
291
 
319
292
def get_test_permutations():
320
293
    """Return the permutations to be used in testing."""