~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-06-18 21:07:10 UTC
  • mfrom: (2490.2.27 graphwalker)
  • Revision ID: pqm@pqm.ubuntu.com-20070618210710-6y8wzcqiw2kvxdiy
Better merge base selection and graph API

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
        bytes = f.read()
 
132
        if type(bytes) is not str:
 
133
            # Although not strictly correct, we raise UnicodeEncodeError to be
 
134
            # compatible with other transports.
 
135
            raise UnicodeEncodeError(
 
136
                'undefined', bytes, 0, 1,
 
137
                'put_file must be given a file of bytes, not unicode.')
 
138
        self._files[_abspath] = (bytes, mode)
154
139
 
155
140
    def mkdir(self, relpath, mode=None):
156
141
        """See Transport.mkdir()."""
160
145
            raise FileExists(relpath)
161
146
        self._dirs[_abspath]=mode
162
147
 
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
148
    def listable(self):
171
149
        """See Transport.listable."""
172
150
        return True
175
153
        for file in self._files:
176
154
            if file.startswith(self._cwd):
177
155
                yield urlutils.escape(file[len(self._cwd):])
178
 
 
 
156
    
179
157
    def list_dir(self, relpath):
180
158
        """See Transport.list_dir()."""
181
159
        _abspath = self._abspath(relpath)
214
192
                    del container[path]
215
193
        do_renames(self._files)
216
194
        do_renames(self._dirs)
217
 
 
 
195
    
218
196
    def rmdir(self, relpath):
219
197
        """See Transport.rmdir."""
220
198
        _abspath = self._abspath(relpath)
235
213
        """See Transport.stat()."""
236
214
        _abspath = self._abspath(relpath)
237
215
        if _abspath in self._files:
238
 
            return MemoryStat(len(self._files[_abspath][0]), False,
 
216
            return MemoryStat(len(self._files[_abspath][0]), False, 
239
217
                              self._files[_abspath][1])
240
218
        elif _abspath in self._dirs:
241
219
            return MemoryStat(0, True, self._dirs[_abspath])
253
231
    def _abspath(self, relpath):
254
232
        """Generate an internal absolute path."""
255
233
        relpath = urlutils.unescape(relpath)
256
 
        if relpath[:1] == '/':
 
234
        if relpath.find('..') != -1:
 
235
            raise AssertionError('relpath contains ..')
 
236
        if relpath == '':
 
237
            return '/'
 
238
        if relpath[0] == '/':
257
239
            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)
 
240
        if relpath == '.':
 
241
            if (self._cwd == '/'):
 
242
                return self._cwd
 
243
            return self._cwd[:-1]
 
244
        if relpath.endswith('/'):
 
245
            relpath = relpath[:-1]
 
246
        if relpath.startswith('./'):
 
247
            relpath = relpath[2:]
 
248
        return self._cwd + relpath
272
249
 
273
250
 
274
251
class _MemoryLock(object):
275
252
    """This makes a lock."""
276
253
 
277
254
    def __init__(self, path, transport):
 
255
        assert isinstance(transport, MemoryTransport)
278
256
        self.path = path
279
257
        self.transport = transport
280
258
        if self.path in self.transport._locks:
281
259
            raise LockError('File %r already locked' % (self.path,))
282
260
        self.transport._locks[self.path] = self
283
261
 
 
262
    def __del__(self):
 
263
        # Should this warn, or actually try to cleanup?
 
264
        if self.transport:
 
265
            warnings.warn("MemoryLock %r not explicitly unlocked" % (self.path,))
 
266
            self.unlock()
 
267
 
284
268
    def unlock(self):
285
269
        del self.transport._locks[self.path]
286
270
        self.transport = None
287
271
 
288
272
 
289
 
class MemoryServer(transport.Server):
 
273
class MemoryServer(Server):
290
274
    """Server for the MemoryTransport for testing with."""
291
275
 
292
 
    def start_server(self):
 
276
    def setUp(self):
 
277
        """See bzrlib.transport.Server.setUp."""
293
278
        self._dirs = {'/':None}
294
279
        self._files = {}
295
280
        self._locks = {}
296
281
        self._scheme = "memory+%s:///" % id(self)
297
282
        def memory_factory(url):
298
 
            from bzrlib.transport import memory
299
 
            result = memory.MemoryTransport(url)
 
283
            result = MemoryTransport(url)
300
284
            result._dirs = self._dirs
301
285
            result._files = self._files
302
286
            result._locks = self._locks
303
287
            return result
304
 
        self._memory_factory = memory_factory
305
 
        transport.register_transport(self._scheme, self._memory_factory)
 
288
        register_transport(self._scheme, memory_factory)
306
289
 
307
 
    def stop_server(self):
 
290
    def tearDown(self):
 
291
        """See bzrlib.transport.Server.tearDown."""
308
292
        # unregister this server
309
 
        transport.unregister_transport(self._scheme, self._memory_factory)
310
293
 
311
294
    def get_url(self):
312
295
        """See bzrlib.transport.Server.get_url."""
313
296
        return self._scheme
314
297
 
315
 
    def get_bogus_url(self):
316
 
        raise NotImplementedError
317
 
 
318
298
 
319
299
def get_test_permutations():
320
300
    """Return the permutations to be used in testing."""