/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: John Arbash Meinel
  • Date: 2006-05-02 20:46:11 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060502204611-02caa5c20fb84ef8
Moved url functions into bzrlib.urlutils

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