/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/local.py

  • Committer: Robert Collins
  • Date: 2006-04-05 05:43:06 UTC
  • mto: This revision was merged to the branch mainline in revision 1638.
  • Revision ID: robertc@robertcollins.net-20060405054306-bfe845e73979aadd
Fix calling relpath() and abspath() on transports at their root.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 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
 
 
17
"""Transport for the local filesystem.
 
18
 
 
19
This is a fairly thin wrapper on regular file IO."""
 
20
 
 
21
import os
 
22
import shutil
 
23
from stat import ST_MODE, S_ISDIR, ST_SIZE
 
24
import tempfile
 
25
import urllib
 
26
 
 
27
from bzrlib.trace import mutter
 
28
from bzrlib.transport import Transport, Server
 
29
from bzrlib.osutils import abspath, realpath, normpath, pathjoin, rename
 
30
 
 
31
 
 
32
class LocalTransport(Transport):
 
33
    """This is the transport agent for local filesystem access."""
 
34
 
 
35
    def __init__(self, base):
 
36
        """Set the base path where files will be stored."""
 
37
        if base.startswith('file://'):
 
38
            base = base[len('file://'):]
 
39
        # realpath is incompatible with symlinks. When we traverse
 
40
        # up we might be able to normpath stuff. RBC 20051003
 
41
        base = normpath(abspath(base))
 
42
        if base[-1] != '/':
 
43
            base = base + '/'
 
44
        super(LocalTransport, self).__init__(base)
 
45
 
 
46
    def should_cache(self):
 
47
        return False
 
48
 
 
49
    def clone(self, offset=None):
 
50
        """Return a new LocalTransport with root at self.base + offset
 
51
        Because the local filesystem does not require a connection, 
 
52
        we can just return a new object.
 
53
        """
 
54
        if offset is None:
 
55
            return LocalTransport(self.base)
 
56
        else:
 
57
            return LocalTransport(self.abspath(offset))
 
58
 
 
59
    def abspath(self, relpath):
 
60
        """Return the full url to the given relative URL."""
 
61
        assert isinstance(relpath, basestring), (type(relpath), relpath)
 
62
        result = normpath(pathjoin(self.base, urllib.unquote(relpath)))
 
63
        #if result[-1] != '/':
 
64
        #    result += '/'
 
65
        return result
 
66
 
 
67
    def relpath(self, abspath):
 
68
        """Return the local path portion from a given absolute path.
 
69
        """
 
70
        from bzrlib.osutils import relpath
 
71
        if abspath is None:
 
72
            abspath = u'.'
 
73
        if len(abspath) > 1 and abspath.endswith('/'):
 
74
            abspath = abspath[:-1]
 
75
        if self.base == '/':
 
76
            root = '/'
 
77
        else:
 
78
            root = self.base[:-1]
 
79
        return relpath(root, abspath)
 
80
 
 
81
    def has(self, relpath):
 
82
        return os.access(self.abspath(relpath), os.F_OK)
 
83
 
 
84
    def get(self, relpath):
 
85
        """Get the file at the given relative path.
 
86
 
 
87
        :param relpath: The relative path to the file
 
88
        """
 
89
        try:
 
90
            path = self.abspath(relpath)
 
91
            return open(path, 'rb')
 
92
        except (IOError, OSError),e:
 
93
            self._translate_error(e, path)
 
94
 
 
95
    def put(self, relpath, f, mode=None):
 
96
        """Copy the file-like or string object into the location.
 
97
 
 
98
        :param relpath: Location to put the contents, relative to base.
 
99
        :param f:       File-like or string object.
 
100
        """
 
101
        from bzrlib.atomicfile import AtomicFile
 
102
 
 
103
        path = relpath
 
104
        try:
 
105
            path = self.abspath(relpath)
 
106
            fp = AtomicFile(path, 'wb', new_mode=mode)
 
107
        except (IOError, OSError),e:
 
108
            self._translate_error(e, path)
 
109
        try:
 
110
            self._pump(f, fp)
 
111
            fp.commit()
 
112
        finally:
 
113
            fp.close()
 
114
 
 
115
    def iter_files_recursive(self):
 
116
        """Iter the relative paths of files in the transports sub-tree."""
 
117
        queue = list(self.list_dir(u'.'))
 
118
        while queue:
 
119
            relpath = queue.pop(0)
 
120
            st = self.stat(relpath)
 
121
            if S_ISDIR(st[ST_MODE]):
 
122
                for i, basename in enumerate(self.list_dir(relpath)):
 
123
                    queue.insert(i, relpath+'/'+basename)
 
124
            else:
 
125
                yield relpath
 
126
 
 
127
    def mkdir(self, relpath, mode=None):
 
128
        """Create a directory at the given path."""
 
129
        path = relpath
 
130
        try:
 
131
            path = self.abspath(relpath)
 
132
            os.mkdir(path)
 
133
            if mode is not None:
 
134
                os.chmod(path, mode)
 
135
        except (IOError, OSError),e:
 
136
            self._translate_error(e, path)
 
137
 
 
138
    def append(self, relpath, f):
 
139
        """Append the text in the file-like object into the final
 
140
        location.
 
141
        """
 
142
        try:
 
143
            fp = open(self.abspath(relpath), 'ab')
 
144
        except (IOError, OSError),e:
 
145
            self._translate_error(e, relpath)
 
146
        # win32 workaround (tell on an unwritten file returns 0)
 
147
        fp.seek(0, 2)
 
148
        result = fp.tell()
 
149
        self._pump(f, fp)
 
150
        return result
 
151
 
 
152
    def copy(self, rel_from, rel_to):
 
153
        """Copy the item at rel_from to the location at rel_to"""
 
154
        import shutil
 
155
        path_from = self.abspath(rel_from)
 
156
        path_to = self.abspath(rel_to)
 
157
        try:
 
158
            shutil.copy(path_from, path_to)
 
159
        except (IOError, OSError),e:
 
160
            # TODO: What about path_to?
 
161
            self._translate_error(e, path_from)
 
162
 
 
163
    def rename(self, rel_from, rel_to):
 
164
        path_from = self.abspath(rel_from)
 
165
        try:
 
166
            # *don't* call bzrlib.osutils.rename, because we want to 
 
167
            # detect errors on rename
 
168
            os.rename(path_from, self.abspath(rel_to))
 
169
        except (IOError, OSError),e:
 
170
            # TODO: What about path_to?
 
171
            self._translate_error(e, path_from)
 
172
 
 
173
    def move(self, rel_from, rel_to):
 
174
        """Move the item at rel_from to the location at rel_to"""
 
175
        path_from = self.abspath(rel_from)
 
176
        path_to = self.abspath(rel_to)
 
177
 
 
178
        try:
 
179
            # this version will delete the destination if necessary
 
180
            rename(path_from, path_to)
 
181
        except (IOError, OSError),e:
 
182
            # TODO: What about path_to?
 
183
            self._translate_error(e, path_from)
 
184
 
 
185
    def delete(self, relpath):
 
186
        """Delete the item at relpath"""
 
187
        path = relpath
 
188
        try:
 
189
            path = self.abspath(relpath)
 
190
            os.remove(path)
 
191
        except (IOError, OSError),e:
 
192
            # TODO: What about path_to?
 
193
            self._translate_error(e, path)
 
194
 
 
195
    def copy_to(self, relpaths, other, mode=None, pb=None):
 
196
        """Copy a set of entries from self into another Transport.
 
197
 
 
198
        :param relpaths: A list/generator of entries to be copied.
 
199
        """
 
200
        if isinstance(other, LocalTransport):
 
201
            # Both from & to are on the local filesystem
 
202
            # Unfortunately, I can't think of anything faster than just
 
203
            # copying them across, one by one :(
 
204
            import shutil
 
205
 
 
206
            total = self._get_total(relpaths)
 
207
            count = 0
 
208
            for path in relpaths:
 
209
                self._update_pb(pb, 'copy-to', count, total)
 
210
                try:
 
211
                    mypath = self.abspath(path)
 
212
                    otherpath = other.abspath(path)
 
213
                    shutil.copy(mypath, otherpath)
 
214
                    if mode is not None:
 
215
                        os.chmod(otherpath, mode)
 
216
                except (IOError, OSError),e:
 
217
                    self._translate_error(e, path)
 
218
                count += 1
 
219
            return count
 
220
        else:
 
221
            return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
 
222
 
 
223
    def listable(self):
 
224
        """See Transport.listable."""
 
225
        return True
 
226
 
 
227
    def list_dir(self, relpath):
 
228
        """Return a list of all files at the given location.
 
229
        WARNING: many transports do not support this, so trying avoid using
 
230
        it if at all possible.
 
231
        """
 
232
        path = self.abspath(relpath)
 
233
        try:
 
234
            return [urllib.quote(entry) for entry in os.listdir(path)]
 
235
        except (IOError, OSError), e:
 
236
            self._translate_error(e, path)
 
237
 
 
238
    def stat(self, relpath):
 
239
        """Return the stat information for a file.
 
240
        """
 
241
        path = relpath
 
242
        try:
 
243
            path = self.abspath(relpath)
 
244
            return os.stat(path)
 
245
        except (IOError, OSError),e:
 
246
            self._translate_error(e, path)
 
247
 
 
248
    def lock_read(self, relpath):
 
249
        """Lock the given file for shared (read) access.
 
250
        :return: A lock object, which should be passed to Transport.unlock()
 
251
        """
 
252
        from bzrlib.lock import ReadLock
 
253
        path = relpath
 
254
        try:
 
255
            path = self.abspath(relpath)
 
256
            return ReadLock(path)
 
257
        except (IOError, OSError), e:
 
258
            self._translate_error(e, path)
 
259
 
 
260
    def lock_write(self, relpath):
 
261
        """Lock the given file for exclusive (write) access.
 
262
        WARNING: many transports do not support this, so trying avoid using it
 
263
 
 
264
        :return: A lock object, which should be passed to Transport.unlock()
 
265
        """
 
266
        from bzrlib.lock import WriteLock
 
267
        return WriteLock(self.abspath(relpath))
 
268
 
 
269
    def rmdir(self, relpath):
 
270
        """See Transport.rmdir."""
 
271
        path = relpath
 
272
        try:
 
273
            path = self.abspath(relpath)
 
274
            os.rmdir(path)
 
275
        except (IOError, OSError),e:
 
276
            self._translate_error(e, path)
 
277
 
 
278
 
 
279
class ScratchTransport(LocalTransport):
 
280
    """A transport that works in a temporary dir and cleans up after itself.
 
281
    
 
282
    The dir only exists for the lifetime of the Python object.
 
283
    Obviously you should not put anything precious in it.
 
284
    """
 
285
 
 
286
    def __init__(self, base=None):
 
287
        if base is None:
 
288
            base = tempfile.mkdtemp()
 
289
        super(ScratchTransport, self).__init__(base)
 
290
 
 
291
    def __del__(self):
 
292
        shutil.rmtree(self.base, ignore_errors=True)
 
293
        mutter("%r destroyed" % self)
 
294
 
 
295
 
 
296
class LocalRelpathServer(Server):
 
297
    """A pretend server for local transports, using relpaths."""
 
298
 
 
299
    def get_url(self):
 
300
        """See Transport.Server.get_url."""
 
301
        return "."
 
302
 
 
303
 
 
304
class LocalAbspathServer(Server):
 
305
    """A pretend server for local transports, using absolute paths."""
 
306
 
 
307
    def get_url(self):
 
308
        """See Transport.Server.get_url."""
 
309
        return os.path.abspath("")
 
310
 
 
311
 
 
312
class LocalURLServer(Server):
 
313
    """A pretend server for local transports, using file:// urls."""
 
314
 
 
315
    def get_url(self):
 
316
        """See Transport.Server.get_url."""
 
317
        # FIXME: \ to / on windows
 
318
        return "file://%s" % os.path.abspath("")
 
319
 
 
320
 
 
321
def get_test_permutations():
 
322
    """Return the permutations to be used in testing."""
 
323
    return [(LocalTransport, LocalRelpathServer),
 
324
            (LocalTransport, LocalAbspathServer),
 
325
            (LocalTransport, LocalURLServer),
 
326
            ]