~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/memory.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
20
so this is primarily useful for testing.
21
21
"""
22
22
 
 
23
from copy import copy
23
24
import os
24
25
import errno
25
26
import re
26
 
from stat import S_IFREG, S_IFDIR
 
27
from stat import *
27
28
from cStringIO import StringIO
28
 
import warnings
29
29
 
30
30
from bzrlib.errors import TransportError, NoSuchFile, FileExists, LockError
31
31
from bzrlib.trace import mutter
58
58
        if url[-1] != '/':
59
59
            url = url + '/'
60
60
        super(MemoryTransport, self).__init__(url)
61
 
        split = url.find(':') + 3
62
 
        self._scheme = url[:split]
63
 
        self._cwd = url[split:]
 
61
        self._cwd = url[url.find(':') + 3:]
64
62
        # dictionaries from absolute path to file mode
65
63
        self._dirs = {'/':None}
66
64
        self._files = {}
68
66
 
69
67
    def clone(self, offset=None):
70
68
        """See Transport.clone()."""
71
 
        path = self._combine_paths(self._cwd, offset)
72
 
        if len(path) == 0 or path[-1] != '/':
73
 
            path += '/'
74
 
        url = self._scheme + path
 
69
        if offset is None or offset == '':
 
70
            return copy(self)
 
71
        segments = offset.split('/')
 
72
        cwdsegments = self._cwd.split('/')[:-1]
 
73
        while len(segments):
 
74
            segment = segments.pop(0)
 
75
            if segment == '.':
 
76
                continue
 
77
            if segment == '..':
 
78
                if len(cwdsegments) > 1:
 
79
                    cwdsegments.pop()
 
80
                continue
 
81
            cwdsegments.append(segment)
 
82
        url = self.base[:self.base.find(':') + 3] + '/'.join(cwdsegments) + '/'
75
83
        result = MemoryTransport(url)
76
84
        result._dirs = self._dirs
77
85
        result._files = self._files
89
97
        else:
90
98
            return temp_t.base[:-1]
91
99
 
92
 
    def append_file(self, relpath, f, mode=None):
93
 
        """See Transport.append_file()."""
 
100
    def append(self, relpath, f, mode=None):
 
101
        """See Transport.append()."""
94
102
        _abspath = self._abspath(relpath)
95
103
        self._check_parent(_abspath)
96
104
        orig_content, orig_mode = self._files.get(_abspath, ("", None))
108
116
    def has(self, relpath):
109
117
        """See Transport.has()."""
110
118
        _abspath = self._abspath(relpath)
111
 
        return (_abspath in self._files) or (_abspath in self._dirs)
 
119
        return _abspath in self._files or _abspath in self._dirs
112
120
 
113
121
    def delete(self, relpath):
114
122
        """See Transport.delete()."""
124
132
            raise NoSuchFile(relpath)
125
133
        return StringIO(self._files[_abspath][0])
126
134
 
127
 
    def put_file(self, relpath, f, mode=None):
128
 
        """See Transport.put_file()."""
 
135
    def put(self, relpath, f, mode=None):
 
136
        """See Transport.put()."""
129
137
        _abspath = self._abspath(relpath)
130
138
        self._check_parent(_abspath)
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)
 
139
        self._files[_abspath] = (f.read(), mode)
139
140
 
140
141
    def mkdir(self, relpath, mode=None):
141
142
        """See Transport.mkdir()."""
152
153
    def iter_files_recursive(self):
153
154
        for file in self._files:
154
155
            if file.startswith(self._cwd):
155
 
                yield urlutils.escape(file[len(self._cwd):])
 
156
                yield file[len(self._cwd):]
156
157
    
157
158
    def list_dir(self, relpath):
158
159
        """See Transport.list_dir()."""
160
161
        if _abspath != '/' and _abspath not in self._dirs:
161
162
            raise NoSuchFile(relpath)
162
163
        result = []
163
 
 
164
 
        if not _abspath.endswith('/'):
165
 
            _abspath += '/'
166
 
 
167
 
        for path_group in self._files, self._dirs:
168
 
            for path in path_group:
169
 
                if path.startswith(_abspath):
170
 
                    trailing = path[len(_abspath):]
171
 
                    if trailing and '/' not in trailing:
172
 
                        result.append(trailing)
173
 
        return map(urlutils.escape, result)
 
164
        for path in self._files:
 
165
            if (path.startswith(_abspath) and 
 
166
                path[len(_abspath) + 1:].find('/') == -1 and
 
167
                len(path) > len(_abspath)):
 
168
                result.append(path[len(_abspath) + 1:])
 
169
        for path in self._dirs:
 
170
            if (path.startswith(_abspath) and 
 
171
                path[len(_abspath) + 1:].find('/') == -1 and
 
172
                len(path) > len(_abspath) and
 
173
                path[len(_abspath)] == '/'):
 
174
                result.append(path[len(_abspath) + 1:])
 
175
        return result
174
176
 
175
177
    def rename(self, rel_from, rel_to):
176
178
        """Rename a file or directory; fail if the destination exists"""
199
201
        if _abspath in self._files:
200
202
            self._translate_error(IOError(errno.ENOTDIR, relpath), relpath)
201
203
        for path in self._files:
202
 
            if path.startswith(_abspath + '/'):
 
204
            if path.startswith(_abspath):
203
205
                self._translate_error(IOError(errno.ENOTEMPTY, relpath),
204
206
                                      relpath)
205
207
        for path in self._dirs:
206
 
            if path.startswith(_abspath + '/') and path != _abspath:
 
208
            if path.startswith(_abspath) and path != _abspath:
207
209
                self._translate_error(IOError(errno.ENOTEMPTY, relpath), relpath)
208
210
        if not _abspath in self._dirs:
209
211
            raise NoSuchFile(relpath)
233
235
        relpath = urlutils.unescape(relpath)
234
236
        if relpath.find('..') != -1:
235
237
            raise AssertionError('relpath contains ..')
236
 
        if relpath == '':
237
 
            return '/'
238
 
        if relpath[0] == '/':
239
 
            return relpath
240
238
        if relpath == '.':
241
239
            if (self._cwd == '/'):
242
240
                return self._cwd
262
260
    def __del__(self):
263
261
        # Should this warn, or actually try to cleanup?
264
262
        if self.transport:
265
 
            warnings.warn("MemoryLock %r not explicitly unlocked" % (self.path,))
 
263
            warn("MemoryLock %r not explicitly unlocked" % (self.path,))
266
264
            self.unlock()
267
265
 
268
266
    def unlock(self):