~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/local.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012, 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
"""Transport for the local filesystem.
18
18
 
19
19
This is a fairly thin wrapper on regular file IO.
20
20
"""
21
21
 
22
 
from __future__ import absolute_import
23
 
 
24
22
import os
25
 
from stat import ST_MODE, S_ISDIR, S_IMODE
 
23
from stat import ST_MODE, S_ISDIR, ST_SIZE, S_IMODE
26
24
import sys
27
25
 
28
26
from bzrlib.lazy_import import lazy_import
35
33
    osutils,
36
34
    urlutils,
37
35
    symbol_versioning,
 
36
    transport,
38
37
    )
 
38
from bzrlib.trace import mutter
39
39
from bzrlib.transport import LateReadError
40
40
""")
41
41
 
42
 
from bzrlib import transport
43
 
 
44
 
 
45
 
_append_flags = os.O_CREAT | os.O_APPEND | os.O_WRONLY | osutils.O_BINARY | osutils.O_NOINHERIT
46
 
_put_non_atomic_flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | osutils.O_BINARY | osutils.O_NOINHERIT
47
 
 
48
 
 
49
 
class LocalTransport(transport.Transport):
 
42
from bzrlib.transport import Transport, Server
 
43
 
 
44
 
 
45
_append_flags = os.O_CREAT | os.O_APPEND | os.O_WRONLY | osutils.O_BINARY
 
46
_put_non_atomic_flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | osutils.O_BINARY
 
47
 
 
48
 
 
49
class LocalTransport(Transport):
50
50
    """This is the transport agent for local filesystem access."""
51
51
 
52
52
    def __init__(self, base):
53
53
        """Set the base path where files will be stored."""
54
54
        if not base.startswith('file://'):
55
 
            raise AssertionError("not a file:// url: %r" % base)
 
55
            symbol_versioning.warn(
 
56
                "Instantiating LocalTransport with a filesystem path"
 
57
                " is deprecated as of bzr 0.8."
 
58
                " Please use bzrlib.transport.get_transport()"
 
59
                " or pass in a file:// url.",
 
60
                 DeprecationWarning,
 
61
                 stacklevel=2
 
62
                 )
 
63
            base = urlutils.local_path_to_url(base)
56
64
        if base[-1] != '/':
57
65
            base = base + '/'
58
 
 
59
 
        # Special case : windows has no "root", but does have
60
 
        # multiple lettered drives inside it. #240910
61
 
        if sys.platform == 'win32' and base == 'file:///':
62
 
            base = ''
63
 
            self._local_base = ''
64
 
            super(LocalTransport, self).__init__(base)
65
 
            return
66
 
 
67
66
        super(LocalTransport, self).__init__(base)
68
67
        self._local_base = urlutils.local_path_from_url(base)
69
 
        if self._local_base[-1] != '/':
70
 
            self._local_base = self._local_base + '/'
71
68
 
72
69
    def clone(self, offset=None):
73
70
        """Return a new LocalTransport with root at self.base + offset
74
 
        Because the local filesystem does not require a connection,
 
71
        Because the local filesystem does not require a connection, 
75
72
        we can just return a new object.
76
73
        """
77
74
        if offset is None:
93
90
         - relative_reference is url escaped.
94
91
        """
95
92
        if relative_reference in ('.', ''):
96
 
            # _local_base normally has a trailing slash; strip it so that stat
97
 
            # on a transport pointing to a symlink reads the link not the
98
 
            # referent but be careful of / and c:\
99
 
            return osutils.split(self._local_base)[0]
 
93
            return self._local_base
100
94
        return self._local_base + urlutils.unescape(relative_reference)
101
95
 
102
96
    def abspath(self, relpath):
103
97
        """Return the full url to the given relative URL."""
104
98
        # TODO: url escape the result. RBC 20060523.
 
99
        assert isinstance(relpath, basestring), (type(relpath), relpath)
105
100
        # jam 20060426 Using normpath on the real path, because that ensures
106
101
        #       proper handling of stuff like
107
102
        path = osutils.normpath(osutils.pathjoin(
108
103
                    self._local_base, urlutils.unescape(relpath)))
109
 
        # on windows, our _local_base may or may not have a drive specified
110
 
        # (ie, it may be "/" or "c:/foo").
111
 
        # If 'relpath' is '/' we *always* get back an abspath without
112
 
        # the drive letter - but if our transport already has a drive letter,
113
 
        # we want our abspaths to have a drive letter too - so handle that
114
 
        # here.
115
 
        if (sys.platform == "win32" and self._local_base[1:2] == ":"
116
 
            and path == '/'):
117
 
            path = self._local_base[:3]
118
 
 
119
104
        return urlutils.local_path_to_url(path)
120
105
 
121
106
    def local_abspath(self, relpath):
124
109
        This function only exists for the LocalTransport, since it is
125
110
        the only one that has direct local access.
126
111
        This is mostly for stuff like WorkingTree which needs to know
127
 
        the local working directory.  The returned path will always contain
128
 
        forward slashes as the path separator, regardless of the platform.
129
 
 
 
112
        the local working directory.
 
113
        
130
114
        This function is quite expensive: it calls realpath which resolves
131
115
        symlinks.
132
116
        """
140
124
        if abspath is None:
141
125
            abspath = u'.'
142
126
 
143
 
        return urlutils.file_relpath(self.base, abspath)
 
127
        return urlutils.file_relpath(
 
128
            urlutils.strip_trailing_slash(self.base),
 
129
            urlutils.strip_trailing_slash(abspath))
144
130
 
145
131
    def has(self, relpath):
146
132
        return os.access(self._abspath(relpath), os.F_OK)
155
141
            transport._file_streams[canonical_url].flush()
156
142
        try:
157
143
            path = self._abspath(relpath)
158
 
            return osutils.open_file(path, 'rb')
 
144
            return open(path, 'rb')
159
145
        except (IOError, OSError),e:
160
146
            if e.errno == errno.EISDIR:
161
147
                return LateReadError(relpath)
166
152
 
167
153
        :param relpath: Location to put the contents, relative to base.
168
154
        :param f:       File-like object.
169
 
        :param mode: The mode for the newly created file,
 
155
        :param mode: The mode for the newly created file, 
170
156
                     None means just use the default
171
157
        """
172
158
 
184
170
            fp.close()
185
171
        return length
186
172
 
187
 
    def put_bytes(self, relpath, raw_bytes, mode=None):
 
173
    def put_bytes(self, relpath, bytes, mode=None):
188
174
        """Copy the string into the location.
189
175
 
190
176
        :param relpath: Location to put the contents, relative to base.
191
 
        :param raw_bytes:   String
 
177
        :param bytes:   String
192
178
        """
193
 
        if not isinstance(raw_bytes, str):
194
 
            raise TypeError(
195
 
                'raw_bytes must be a plain string, not %s' % type(raw_bytes))
 
179
 
196
180
        path = relpath
197
181
        try:
198
182
            path = self._abspath(relpath)
201
185
        except (IOError, OSError),e:
202
186
            self._translate_error(e, path)
203
187
        try:
204
 
            if bytes:
205
 
                fp.write(raw_bytes)
 
188
            fp.write(bytes)
206
189
            fp.commit()
207
190
        finally:
208
191
            fp.close()
251
234
            if mode is not None and mode != S_IMODE(st.st_mode):
252
235
                # Because of umask, we may still need to chmod the file.
253
236
                # But in the general case, we won't have to
254
 
                osutils.chmod_if_possible(abspath, mode)
 
237
                os.chmod(abspath, mode)
255
238
            writer(fd)
256
239
        finally:
257
240
            os.close(fd)
283
266
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
284
267
                             create_parent_dir=False, dir_mode=None):
285
268
        def writer(fd):
286
 
            if bytes:
287
 
                os.write(fd, bytes)
 
269
            os.write(fd, bytes)
288
270
        self._put_non_atomic_helper(relpath, writer, mode=mode,
289
271
                                    create_parent_dir=create_parent_dir,
290
272
                                    dir_mode=dir_mode)
310
292
            local_mode = mode
311
293
        try:
312
294
            os.mkdir(abspath, local_mode)
 
295
            if mode is not None:
 
296
                # It is probably faster to just do the chmod, rather than
 
297
                # doing a stat, and then trying to compare
 
298
                os.chmod(abspath, mode)
313
299
        except (IOError, OSError),e:
314
300
            self._translate_error(e, abspath)
315
 
        if mode is not None:
316
 
            try:
317
 
                osutils.chmod_if_possible(abspath, mode)
318
 
            except (IOError, OSError), e:
319
 
                self._translate_error(e, abspath)
320
301
 
321
302
    def mkdir(self, relpath, mode=None):
322
303
        """Create a directory at the given path."""
324
305
 
325
306
    def open_write_stream(self, relpath, mode=None):
326
307
        """See Transport.open_write_stream."""
 
308
        # initialise the file
 
309
        self.put_bytes_non_atomic(relpath, "", mode=mode)
327
310
        abspath = self._abspath(relpath)
328
 
        try:
329
 
            handle = osutils.open_file(abspath, 'wb')
330
 
        except (IOError, OSError),e:
331
 
            self._translate_error(e, abspath)
332
 
        handle.truncate()
 
311
        handle = open(abspath, 'wb')
333
312
        if mode is not None:
334
313
            self._check_mode_and_size(abspath, handle.fileno(), mode)
335
314
        transport._file_streams[self.abspath(relpath)] = handle
354
333
        if mode is not None and mode != S_IMODE(st.st_mode):
355
334
            # Because of umask, we may still need to chmod the file.
356
335
            # But in the general case, we won't have to
357
 
            osutils.chmod_if_possible(file_abspath, mode)
 
336
            os.chmod(file_abspath, mode)
358
337
        return st.st_size
359
338
 
360
339
    def append_file(self, relpath, f, mode=None):
372
351
        file_abspath, fd = self._get_append_file(relpath, mode=mode)
373
352
        try:
374
353
            result = self._check_mode_and_size(file_abspath, fd, mode=mode)
375
 
            if bytes:
376
 
                os.write(fd, bytes)
 
354
            os.write(fd, bytes)
377
355
        finally:
378
356
            os.close(fd)
379
357
        return result
399
377
 
400
378
    def rename(self, rel_from, rel_to):
401
379
        path_from = self._abspath(rel_from)
402
 
        path_to = self._abspath(rel_to)
403
380
        try:
404
 
            # *don't* call bzrlib.osutils.rename, because we want to
405
 
            # detect conflicting names on rename, and osutils.rename tries to
406
 
            # mask cross-platform differences there
407
 
            os.rename(path_from, path_to)
 
381
            # *don't* call bzrlib.osutils.rename, because we want to 
 
382
            # detect errors on rename
 
383
            os.rename(path_from, self._abspath(rel_to))
408
384
        except (IOError, OSError),e:
409
385
            # TODO: What about path_to?
410
386
            self._translate_error(e, path_from)
453
429
                    otherpath = other._abspath(path)
454
430
                    shutil.copy(mypath, otherpath)
455
431
                    if mode is not None:
456
 
                        osutils.chmod_if_possible(otherpath, mode)
 
432
                        os.chmod(otherpath, mode)
457
433
                except (IOError, OSError),e:
458
434
                    self._translate_error(e, path)
459
435
                count += 1
483
459
        path = relpath
484
460
        try:
485
461
            path = self._abspath(relpath)
486
 
            return os.lstat(path)
 
462
            return os.stat(path)
487
463
        except (IOError, OSError),e:
488
464
            self._translate_error(e, path)
489
465
 
517
493
        except (IOError, OSError),e:
518
494
            self._translate_error(e, path)
519
495
 
520
 
    if osutils.host_os_dereferences_symlinks():
521
 
        def readlink(self, relpath):
522
 
            """See Transport.readlink."""
523
 
            return osutils.readlink(self._abspath(relpath))
524
 
 
525
 
    if osutils.hardlinks_good():
526
 
        def hardlink(self, source, link_name):
527
 
            """See Transport.link."""
528
 
            try:
529
 
                os.link(self._abspath(source), self._abspath(link_name))
530
 
            except (IOError, OSError), e:
531
 
                self._translate_error(e, source)
532
 
 
533
 
    if osutils.has_symlinks():
534
 
        def symlink(self, source, link_name):
535
 
            """See Transport.symlink."""
536
 
            abs_link_dirpath = urlutils.dirname(self.abspath(link_name))
537
 
            source_rel = urlutils.file_relpath(
538
 
                abs_link_dirpath, self.abspath(source))
539
 
 
540
 
            try:
541
 
                os.symlink(source_rel, self._abspath(link_name))
542
 
            except (IOError, OSError), e:
543
 
                self._translate_error(e, source_rel)
544
 
 
545
496
    def _can_roundtrip_unix_modebits(self):
546
497
        if sys.platform == 'win32':
547
498
            # anyone else?
560
511
        self._local_base = urlutils._win32_local_path_from_url(base)
561
512
 
562
513
    def abspath(self, relpath):
563
 
        path = osutils._win32_normpath(osutils.pathjoin(
 
514
        assert isinstance(relpath, basestring), (type(relpath), relpath)
 
515
        path = osutils.normpath(osutils.pathjoin(
564
516
                    self._local_base, urlutils.unescape(relpath)))
565
517
        return urlutils._win32_local_path_to_url(path)
566
518
 
567
519
    def clone(self, offset=None):
568
520
        """Return a new LocalTransport with root at self.base + offset
569
 
        Because the local filesystem does not require a connection,
 
521
        Because the local filesystem does not require a connection, 
570
522
        we can just return a new object.
571
523
        """
572
524
        if offset is None:
581
533
            return EmulatedWin32LocalTransport(abspath)
582
534
 
583
535
 
 
536
class LocalURLServer(Server):
 
537
    """A pretend server for local transports, using file:// urls.
 
538
    
 
539
    Of course no actual server is required to access the local filesystem, so
 
540
    this just exists to tell the test code how to get to it.
 
541
    """
 
542
 
 
543
    def setUp(self):
 
544
        """Setup the server to service requests.
 
545
        
 
546
        :param decorated_transport: ignored by this implementation.
 
547
        """
 
548
 
 
549
    def get_url(self):
 
550
        """See Transport.Server.get_url."""
 
551
        return urlutils.local_path_to_url('')
 
552
 
 
553
 
584
554
def get_test_permutations():
585
555
    """Return the permutations to be used in testing."""
586
 
    from bzrlib.tests import test_server
587
 
    return [(LocalTransport, test_server.LocalURLServer),]
 
556
    return [
 
557
            (LocalTransport, LocalURLServer),
 
558
            ]