~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/local.py

(vila) Make all transport put_bytes() raises TypeError when given unicode
 strings rather than bytes (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Transport for the local filesystem.
 
18
 
 
19
This is a fairly thin wrapper on regular file IO.
 
20
"""
 
21
 
 
22
from __future__ import absolute_import
 
23
 
 
24
import os
 
25
from stat import ST_MODE, S_ISDIR, S_IMODE
 
26
import sys
 
27
 
 
28
from bzrlib.lazy_import import lazy_import
 
29
lazy_import(globals(), """
 
30
import errno
 
31
import shutil
 
32
 
 
33
from bzrlib import (
 
34
    atomicfile,
 
35
    osutils,
 
36
    urlutils,
 
37
    symbol_versioning,
 
38
    )
 
39
from bzrlib.transport import LateReadError
 
40
""")
 
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):
 
50
    """This is the transport agent for local filesystem access."""
 
51
 
 
52
    def __init__(self, base):
 
53
        """Set the base path where files will be stored."""
 
54
        if not base.startswith('file://'):
 
55
            raise AssertionError("not a file:// url: %r" % base)
 
56
        if base[-1] != '/':
 
57
            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
        super(LocalTransport, self).__init__(base)
 
68
        self._local_base = urlutils.local_path_from_url(base)
 
69
        if self._local_base[-1] != '/':
 
70
            self._local_base = self._local_base + '/'
 
71
 
 
72
    def clone(self, offset=None):
 
73
        """Return a new LocalTransport with root at self.base + offset
 
74
        Because the local filesystem does not require a connection,
 
75
        we can just return a new object.
 
76
        """
 
77
        if offset is None:
 
78
            return LocalTransport(self.base)
 
79
        else:
 
80
            abspath = self.abspath(offset)
 
81
            if abspath == 'file://':
 
82
                # fix upwalk for UNC path
 
83
                # when clone from //HOST/path updir recursively
 
84
                # we should stop at least at //HOST part
 
85
                abspath = self.base
 
86
            return LocalTransport(abspath)
 
87
 
 
88
    def _abspath(self, relative_reference):
 
89
        """Return a path for use in os calls.
 
90
 
 
91
        Several assumptions are made:
 
92
         - relative_reference does not contain '..'
 
93
         - relative_reference is url escaped.
 
94
        """
 
95
        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]
 
100
        return self._local_base + urlutils.unescape(relative_reference)
 
101
 
 
102
    def abspath(self, relpath):
 
103
        """Return the full url to the given relative URL."""
 
104
        # TODO: url escape the result. RBC 20060523.
 
105
        # jam 20060426 Using normpath on the real path, because that ensures
 
106
        #       proper handling of stuff like
 
107
        path = osutils.normpath(osutils.pathjoin(
 
108
                    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
        return urlutils.local_path_to_url(path)
 
120
 
 
121
    def local_abspath(self, relpath):
 
122
        """Transform the given relative path URL into the actual path on disk
 
123
 
 
124
        This function only exists for the LocalTransport, since it is
 
125
        the only one that has direct local access.
 
126
        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
 
 
130
        This function is quite expensive: it calls realpath which resolves
 
131
        symlinks.
 
132
        """
 
133
        absurl = self.abspath(relpath)
 
134
        # mutter(u'relpath %s => base: %s, absurl %s', relpath, self.base, absurl)
 
135
        return urlutils.local_path_from_url(absurl)
 
136
 
 
137
    def relpath(self, abspath):
 
138
        """Return the local path portion from a given absolute path.
 
139
        """
 
140
        if abspath is None:
 
141
            abspath = u'.'
 
142
 
 
143
        return urlutils.file_relpath(self.base, abspath)
 
144
 
 
145
    def has(self, relpath):
 
146
        return os.access(self._abspath(relpath), os.F_OK)
 
147
 
 
148
    def get(self, relpath):
 
149
        """Get the file at the given relative path.
 
150
 
 
151
        :param relpath: The relative path to the file
 
152
        """
 
153
        canonical_url = self.abspath(relpath)
 
154
        if canonical_url in transport._file_streams:
 
155
            transport._file_streams[canonical_url].flush()
 
156
        try:
 
157
            path = self._abspath(relpath)
 
158
            return osutils.open_file(path, 'rb')
 
159
        except (IOError, OSError),e:
 
160
            if e.errno == errno.EISDIR:
 
161
                return LateReadError(relpath)
 
162
            self._translate_error(e, path)
 
163
 
 
164
    def put_file(self, relpath, f, mode=None):
 
165
        """Copy the file-like object into the location.
 
166
 
 
167
        :param relpath: Location to put the contents, relative to base.
 
168
        :param f:       File-like object.
 
169
        :param mode: The mode for the newly created file,
 
170
                     None means just use the default
 
171
        """
 
172
 
 
173
        path = relpath
 
174
        try:
 
175
            path = self._abspath(relpath)
 
176
            osutils.check_legal_path(path)
 
177
            fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
 
178
        except (IOError, OSError),e:
 
179
            self._translate_error(e, path)
 
180
        try:
 
181
            length = self._pump(f, fp)
 
182
            fp.commit()
 
183
        finally:
 
184
            fp.close()
 
185
        return length
 
186
 
 
187
    def put_bytes(self, relpath, raw_bytes, mode=None):
 
188
        """Copy the string into the location.
 
189
 
 
190
        :param relpath: Location to put the contents, relative to base.
 
191
        :param raw_bytes:   String
 
192
        """
 
193
        if not isinstance(raw_bytes, str):
 
194
            raise TypeError(
 
195
                'raw_bytes must be a plain string, not %s' % type(raw_bytes))
 
196
        path = relpath
 
197
        try:
 
198
            path = self._abspath(relpath)
 
199
            osutils.check_legal_path(path)
 
200
            fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
 
201
        except (IOError, OSError),e:
 
202
            self._translate_error(e, path)
 
203
        try:
 
204
            if bytes:
 
205
                fp.write(raw_bytes)
 
206
            fp.commit()
 
207
        finally:
 
208
            fp.close()
 
209
 
 
210
    def _put_non_atomic_helper(self, relpath, writer,
 
211
                               mode=None,
 
212
                               create_parent_dir=False,
 
213
                               dir_mode=None):
 
214
        """Common functionality information for the put_*_non_atomic.
 
215
 
 
216
        This tracks all the create_parent_dir stuff.
 
217
 
 
218
        :param relpath: the path we are putting to.
 
219
        :param writer: A function that takes an os level file descriptor
 
220
            and writes whatever data it needs to write there.
 
221
        :param mode: The final file mode.
 
222
        :param create_parent_dir: Should we be creating the parent directory
 
223
            if it doesn't exist?
 
224
        """
 
225
        abspath = self._abspath(relpath)
 
226
        if mode is None:
 
227
            # os.open() will automatically use the umask
 
228
            local_mode = 0666
 
229
        else:
 
230
            local_mode = mode
 
231
        try:
 
232
            fd = os.open(abspath, _put_non_atomic_flags, local_mode)
 
233
        except (IOError, OSError),e:
 
234
            # We couldn't create the file, maybe we need to create
 
235
            # the parent directory, and try again
 
236
            if (not create_parent_dir
 
237
                or e.errno not in (errno.ENOENT,errno.ENOTDIR)):
 
238
                self._translate_error(e, relpath)
 
239
            parent_dir = os.path.dirname(abspath)
 
240
            if not parent_dir:
 
241
                self._translate_error(e, relpath)
 
242
            self._mkdir(parent_dir, mode=dir_mode)
 
243
            # We created the parent directory, lets try to open the
 
244
            # file again
 
245
            try:
 
246
                fd = os.open(abspath, _put_non_atomic_flags, local_mode)
 
247
            except (IOError, OSError), e:
 
248
                self._translate_error(e, relpath)
 
249
        try:
 
250
            st = os.fstat(fd)
 
251
            if mode is not None and mode != S_IMODE(st.st_mode):
 
252
                # Because of umask, we may still need to chmod the file.
 
253
                # But in the general case, we won't have to
 
254
                osutils.chmod_if_possible(abspath, mode)
 
255
            writer(fd)
 
256
        finally:
 
257
            os.close(fd)
 
258
 
 
259
    def put_file_non_atomic(self, relpath, f, mode=None,
 
260
                            create_parent_dir=False,
 
261
                            dir_mode=None):
 
262
        """Copy the file-like object into the target location.
 
263
 
 
264
        This function is not strictly safe to use. It is only meant to
 
265
        be used when you already know that the target does not exist.
 
266
        It is not safe, because it will open and truncate the remote
 
267
        file. So there may be a time when the file has invalid contents.
 
268
 
 
269
        :param relpath: The remote location to put the contents.
 
270
        :param f:       File-like object.
 
271
        :param mode:    Possible access permissions for new file.
 
272
                        None means do not set remote permissions.
 
273
        :param create_parent_dir: If we cannot create the target file because
 
274
                        the parent directory does not exist, go ahead and
 
275
                        create it, and then try again.
 
276
        """
 
277
        def writer(fd):
 
278
            self._pump_to_fd(f, fd)
 
279
        self._put_non_atomic_helper(relpath, writer, mode=mode,
 
280
                                    create_parent_dir=create_parent_dir,
 
281
                                    dir_mode=dir_mode)
 
282
 
 
283
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
 
284
                             create_parent_dir=False, dir_mode=None):
 
285
        def writer(fd):
 
286
            if bytes:
 
287
                os.write(fd, bytes)
 
288
        self._put_non_atomic_helper(relpath, writer, mode=mode,
 
289
                                    create_parent_dir=create_parent_dir,
 
290
                                    dir_mode=dir_mode)
 
291
 
 
292
    def iter_files_recursive(self):
 
293
        """Iter the relative paths of files in the transports sub-tree."""
 
294
        queue = list(self.list_dir(u'.'))
 
295
        while queue:
 
296
            relpath = queue.pop(0)
 
297
            st = self.stat(relpath)
 
298
            if S_ISDIR(st[ST_MODE]):
 
299
                for i, basename in enumerate(self.list_dir(relpath)):
 
300
                    queue.insert(i, relpath+'/'+basename)
 
301
            else:
 
302
                yield relpath
 
303
 
 
304
    def _mkdir(self, abspath, mode=None):
 
305
        """Create a real directory, filtering through mode"""
 
306
        if mode is None:
 
307
            # os.mkdir() will filter through umask
 
308
            local_mode = 0777
 
309
        else:
 
310
            local_mode = mode
 
311
        try:
 
312
            os.mkdir(abspath, local_mode)
 
313
        except (IOError, OSError),e:
 
314
            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
 
 
321
    def mkdir(self, relpath, mode=None):
 
322
        """Create a directory at the given path."""
 
323
        self._mkdir(self._abspath(relpath), mode=mode)
 
324
 
 
325
    def open_write_stream(self, relpath, mode=None):
 
326
        """See Transport.open_write_stream."""
 
327
        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()
 
333
        if mode is not None:
 
334
            self._check_mode_and_size(abspath, handle.fileno(), mode)
 
335
        transport._file_streams[self.abspath(relpath)] = handle
 
336
        return transport.FileFileStream(self, relpath, handle)
 
337
 
 
338
    def _get_append_file(self, relpath, mode=None):
 
339
        """Call os.open() for the given relpath"""
 
340
        file_abspath = self._abspath(relpath)
 
341
        if mode is None:
 
342
            # os.open() will automatically use the umask
 
343
            local_mode = 0666
 
344
        else:
 
345
            local_mode = mode
 
346
        try:
 
347
            return file_abspath, os.open(file_abspath, _append_flags, local_mode)
 
348
        except (IOError, OSError),e:
 
349
            self._translate_error(e, relpath)
 
350
 
 
351
    def _check_mode_and_size(self, file_abspath, fd, mode=None):
 
352
        """Check the mode of the file, and return the current size"""
 
353
        st = os.fstat(fd)
 
354
        if mode is not None and mode != S_IMODE(st.st_mode):
 
355
            # Because of umask, we may still need to chmod the file.
 
356
            # But in the general case, we won't have to
 
357
            osutils.chmod_if_possible(file_abspath, mode)
 
358
        return st.st_size
 
359
 
 
360
    def append_file(self, relpath, f, mode=None):
 
361
        """Append the text in the file-like object into the final location."""
 
362
        file_abspath, fd = self._get_append_file(relpath, mode=mode)
 
363
        try:
 
364
            result = self._check_mode_and_size(file_abspath, fd, mode=mode)
 
365
            self._pump_to_fd(f, fd)
 
366
        finally:
 
367
            os.close(fd)
 
368
        return result
 
369
 
 
370
    def append_bytes(self, relpath, bytes, mode=None):
 
371
        """Append the text in the string into the final location."""
 
372
        file_abspath, fd = self._get_append_file(relpath, mode=mode)
 
373
        try:
 
374
            result = self._check_mode_and_size(file_abspath, fd, mode=mode)
 
375
            if bytes:
 
376
                os.write(fd, bytes)
 
377
        finally:
 
378
            os.close(fd)
 
379
        return result
 
380
 
 
381
    def _pump_to_fd(self, fromfile, to_fd):
 
382
        """Copy contents of one file to another."""
 
383
        BUFSIZE = 32768
 
384
        while True:
 
385
            b = fromfile.read(BUFSIZE)
 
386
            if not b:
 
387
                break
 
388
            os.write(to_fd, b)
 
389
 
 
390
    def copy(self, rel_from, rel_to):
 
391
        """Copy the item at rel_from to the location at rel_to"""
 
392
        path_from = self._abspath(rel_from)
 
393
        path_to = self._abspath(rel_to)
 
394
        try:
 
395
            shutil.copy(path_from, path_to)
 
396
        except (IOError, OSError),e:
 
397
            # TODO: What about path_to?
 
398
            self._translate_error(e, path_from)
 
399
 
 
400
    def rename(self, rel_from, rel_to):
 
401
        path_from = self._abspath(rel_from)
 
402
        path_to = self._abspath(rel_to)
 
403
        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)
 
408
        except (IOError, OSError),e:
 
409
            # TODO: What about path_to?
 
410
            self._translate_error(e, path_from)
 
411
 
 
412
    def move(self, rel_from, rel_to):
 
413
        """Move the item at rel_from to the location at rel_to"""
 
414
        path_from = self._abspath(rel_from)
 
415
        path_to = self._abspath(rel_to)
 
416
 
 
417
        try:
 
418
            # this version will delete the destination if necessary
 
419
            osutils.rename(path_from, path_to)
 
420
        except (IOError, OSError),e:
 
421
            # TODO: What about path_to?
 
422
            self._translate_error(e, path_from)
 
423
 
 
424
    def delete(self, relpath):
 
425
        """Delete the item at relpath"""
 
426
        path = relpath
 
427
        try:
 
428
            path = self._abspath(relpath)
 
429
            os.remove(path)
 
430
        except (IOError, OSError),e:
 
431
            self._translate_error(e, path)
 
432
 
 
433
    def external_url(self):
 
434
        """See bzrlib.transport.Transport.external_url."""
 
435
        # File URL's are externally usable.
 
436
        return self.base
 
437
 
 
438
    def copy_to(self, relpaths, other, mode=None, pb=None):
 
439
        """Copy a set of entries from self into another Transport.
 
440
 
 
441
        :param relpaths: A list/generator of entries to be copied.
 
442
        """
 
443
        if isinstance(other, LocalTransport):
 
444
            # Both from & to are on the local filesystem
 
445
            # Unfortunately, I can't think of anything faster than just
 
446
            # copying them across, one by one :(
 
447
            total = self._get_total(relpaths)
 
448
            count = 0
 
449
            for path in relpaths:
 
450
                self._update_pb(pb, 'copy-to', count, total)
 
451
                try:
 
452
                    mypath = self._abspath(path)
 
453
                    otherpath = other._abspath(path)
 
454
                    shutil.copy(mypath, otherpath)
 
455
                    if mode is not None:
 
456
                        osutils.chmod_if_possible(otherpath, mode)
 
457
                except (IOError, OSError),e:
 
458
                    self._translate_error(e, path)
 
459
                count += 1
 
460
            return count
 
461
        else:
 
462
            return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
 
463
 
 
464
    def listable(self):
 
465
        """See Transport.listable."""
 
466
        return True
 
467
 
 
468
    def list_dir(self, relpath):
 
469
        """Return a list of all files at the given location.
 
470
        WARNING: many transports do not support this, so trying avoid using
 
471
        it if at all possible.
 
472
        """
 
473
        path = self._abspath(relpath)
 
474
        try:
 
475
            entries = os.listdir(path)
 
476
        except (IOError, OSError), e:
 
477
            self._translate_error(e, path)
 
478
        return [urlutils.escape(entry) for entry in entries]
 
479
 
 
480
    def stat(self, relpath):
 
481
        """Return the stat information for a file.
 
482
        """
 
483
        path = relpath
 
484
        try:
 
485
            path = self._abspath(relpath)
 
486
            return os.lstat(path)
 
487
        except (IOError, OSError),e:
 
488
            self._translate_error(e, path)
 
489
 
 
490
    def lock_read(self, relpath):
 
491
        """Lock the given file for shared (read) access.
 
492
        :return: A lock object, which should be passed to Transport.unlock()
 
493
        """
 
494
        from bzrlib.lock import ReadLock
 
495
        path = relpath
 
496
        try:
 
497
            path = self._abspath(relpath)
 
498
            return ReadLock(path)
 
499
        except (IOError, OSError), e:
 
500
            self._translate_error(e, path)
 
501
 
 
502
    def lock_write(self, relpath):
 
503
        """Lock the given file for exclusive (write) access.
 
504
        WARNING: many transports do not support this, so trying avoid using it
 
505
 
 
506
        :return: A lock object, which should be passed to Transport.unlock()
 
507
        """
 
508
        from bzrlib.lock import WriteLock
 
509
        return WriteLock(self._abspath(relpath))
 
510
 
 
511
    def rmdir(self, relpath):
 
512
        """See Transport.rmdir."""
 
513
        path = relpath
 
514
        try:
 
515
            path = self._abspath(relpath)
 
516
            os.rmdir(path)
 
517
        except (IOError, OSError),e:
 
518
            self._translate_error(e, path)
 
519
 
 
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
    def _can_roundtrip_unix_modebits(self):
 
546
        if sys.platform == 'win32':
 
547
            # anyone else?
 
548
            return False
 
549
        else:
 
550
            return True
 
551
 
 
552
 
 
553
class EmulatedWin32LocalTransport(LocalTransport):
 
554
    """Special transport for testing Win32 [UNC] paths on non-windows"""
 
555
 
 
556
    def __init__(self, base):
 
557
        if base[-1] != '/':
 
558
            base = base + '/'
 
559
        super(LocalTransport, self).__init__(base)
 
560
        self._local_base = urlutils._win32_local_path_from_url(base)
 
561
 
 
562
    def abspath(self, relpath):
 
563
        path = osutils._win32_normpath(osutils.pathjoin(
 
564
                    self._local_base, urlutils.unescape(relpath)))
 
565
        return urlutils._win32_local_path_to_url(path)
 
566
 
 
567
    def clone(self, offset=None):
 
568
        """Return a new LocalTransport with root at self.base + offset
 
569
        Because the local filesystem does not require a connection,
 
570
        we can just return a new object.
 
571
        """
 
572
        if offset is None:
 
573
            return EmulatedWin32LocalTransport(self.base)
 
574
        else:
 
575
            abspath = self.abspath(offset)
 
576
            if abspath == 'file://':
 
577
                # fix upwalk for UNC path
 
578
                # when clone from //HOST/path updir recursively
 
579
                # we should stop at least at //HOST part
 
580
                abspath = self.base
 
581
            return EmulatedWin32LocalTransport(abspath)
 
582
 
 
583
 
 
584
def get_test_permutations():
 
585
    """Return the permutations to be used in testing."""
 
586
    from bzrlib.tests import test_server
 
587
    return [(LocalTransport, test_server.LocalURLServer),]