~bzr/ubuntu/lucid/bzr/beta-ppa

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2010-08-18 04:26:39 UTC
  • mfrom: (129.1.8 packaging-karmic)
  • Revision ID: mbp@sourcefrog.net-20100818042639-mjoxtngyjwiu05fo
* PPA rebuild for lucid.
* PPA rebuild for karmic.
* PPA rebuild onto jaunty.
* New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
import errno
17
18
import os
18
19
import re
19
20
import stat
20
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
21
import sys
23
22
import time
24
 
import warnings
 
23
import codecs
25
24
 
26
25
from bzrlib.lazy_import import lazy_import
27
26
lazy_import(globals(), """
28
 
import codecs
29
27
from datetime import datetime
30
 
import errno
31
 
from ntpath import (abspath as _nt_abspath,
32
 
                    join as _nt_join,
33
 
                    normpath as _nt_normpath,
34
 
                    realpath as _nt_realpath,
35
 
                    splitdrive as _nt_splitdrive,
36
 
                    )
 
28
import getpass
 
29
import ntpath
37
30
import posixpath
 
31
# We need to import both shutil and rmtree as we export the later on posix
 
32
# and need the former on windows
38
33
import shutil
39
 
from shutil import (
40
 
    rmtree,
41
 
    )
42
 
import signal
 
34
from shutil import rmtree
 
35
import socket
43
36
import subprocess
 
37
# We need to import both tempfile and mkdtemp as we export the later on posix
 
38
# and need the former on windows
44
39
import tempfile
45
 
from tempfile import (
46
 
    mkdtemp,
47
 
    )
 
40
from tempfile import mkdtemp
48
41
import unicodedata
49
42
 
50
43
from bzrlib import (
51
44
    cache_utf8,
52
45
    errors,
 
46
    trace,
53
47
    win32utils,
54
48
    )
55
49
""")
56
50
 
 
51
from bzrlib.symbol_versioning import (
 
52
    deprecated_function,
 
53
    deprecated_in,
 
54
    )
 
55
 
57
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
58
57
# of 2.5
59
58
if sys.version_info < (2, 5):
182
181
    try:
183
182
        return _kind_marker_map[kind]
184
183
    except KeyError:
185
 
        raise errors.BzrError('invalid file kind %r' % kind)
 
184
        # Slightly faster than using .get(, '') when the common case is that
 
185
        # kind will be found
 
186
        return ''
186
187
 
187
188
 
188
189
lexists = getattr(os.path, 'lexists', None)
297
298
    running python.exe under cmd.exe return capital C:\\
298
299
    running win32 python inside a cygwin shell returns lowercase c:\\
299
300
    """
300
 
    drive, path = _nt_splitdrive(path)
 
301
    drive, path = ntpath.splitdrive(path)
301
302
    return drive.upper() + path
302
303
 
303
304
 
304
305
def _win32_abspath(path):
305
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
306
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
306
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
 
307
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
307
308
 
308
309
 
309
310
def _win98_abspath(path):
320
321
    #   /path       => C:/path
321
322
    path = unicode(path)
322
323
    # check for absolute path
323
 
    drive = _nt_splitdrive(path)[0]
 
324
    drive = ntpath.splitdrive(path)[0]
324
325
    if drive == '' and path[:2] not in('//','\\\\'):
325
326
        cwd = os.getcwdu()
326
327
        # we cannot simply os.path.join cwd and path
327
328
        # because os.path.join('C:','/path') produce '/path'
328
329
        # and this is incorrect
329
330
        if path[:1] in ('/','\\'):
330
 
            cwd = _nt_splitdrive(cwd)[0]
 
331
            cwd = ntpath.splitdrive(cwd)[0]
331
332
            path = path[1:]
332
333
        path = cwd + '\\' + path
333
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
334
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
334
335
 
335
336
 
336
337
def _win32_realpath(path):
337
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
338
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
338
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
 
339
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
339
340
 
340
341
 
341
342
def _win32_pathjoin(*args):
342
 
    return _nt_join(*args).replace('\\', '/')
 
343
    return ntpath.join(*args).replace('\\', '/')
343
344
 
344
345
 
345
346
def _win32_normpath(path):
346
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
347
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
347
348
 
348
349
 
349
350
def _win32_getcwd():
388
389
basename = os.path.basename
389
390
split = os.path.split
390
391
splitext = os.path.splitext
391
 
# These were already imported into local scope
 
392
# These were already lazily imported into local scope
392
393
# mkdtemp = tempfile.mkdtemp
393
394
# rmtree = shutil.rmtree
394
395
 
434
435
    getcwd = _mac_getcwd
435
436
 
436
437
 
437
 
def get_terminal_encoding():
 
438
def get_terminal_encoding(trace=False):
438
439
    """Find the best encoding for printing to the screen.
439
440
 
440
441
    This attempts to check both sys.stdout and sys.stdin to see
446
447
 
447
448
    On my standard US Windows XP, the preferred encoding is
448
449
    cp1252, but the console is cp437
 
450
 
 
451
    :param trace: If True trace the selected encoding via mutter().
449
452
    """
450
453
    from bzrlib.trace import mutter
451
454
    output_encoding = getattr(sys.stdout, 'encoding', None)
453
456
        input_encoding = getattr(sys.stdin, 'encoding', None)
454
457
        if not input_encoding:
455
458
            output_encoding = get_user_encoding()
456
 
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
459
            if trace:
 
460
                mutter('encoding stdout as osutils.get_user_encoding() %r',
457
461
                   output_encoding)
458
462
        else:
459
463
            output_encoding = input_encoding
460
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
464
            if trace:
 
465
                mutter('encoding stdout as sys.stdin encoding %r',
 
466
                    output_encoding)
461
467
    else:
462
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
468
        if trace:
 
469
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
463
470
    if output_encoding == 'cp0':
464
471
        # invalid encoding (cp0 means 'no codepage' on Windows)
465
472
        output_encoding = get_user_encoding()
466
 
        mutter('cp0 is invalid encoding.'
 
473
        if trace:
 
474
            mutter('cp0 is invalid encoding.'
467
475
               ' encoding stdout as osutils.get_user_encoding() %r',
468
476
               output_encoding)
469
477
    # check encoding
495
503
def isdir(f):
496
504
    """True if f is an accessible directory."""
497
505
    try:
498
 
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
506
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
499
507
    except OSError:
500
508
        return False
501
509
 
503
511
def isfile(f):
504
512
    """True if f is a regular file."""
505
513
    try:
506
 
        return S_ISREG(os.lstat(f)[ST_MODE])
 
514
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
507
515
    except OSError:
508
516
        return False
509
517
 
510
518
def islink(f):
511
519
    """True if f is a symlink."""
512
520
    try:
513
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
521
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
514
522
    except OSError:
515
523
        return False
516
524
 
856
864
 
857
865
def filesize(f):
858
866
    """Return size of given open file."""
859
 
    return os.fstat(f.fileno())[ST_SIZE]
 
867
    return os.fstat(f.fileno())[stat.ST_SIZE]
860
868
 
861
869
 
862
870
# Define rand_bytes based on platform.
924
932
 
925
933
def parent_directories(filename):
926
934
    """Return the list of parent directories, deepest first.
927
 
    
 
935
 
928
936
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
929
937
    """
930
938
    parents = []
954
962
    # NB: This docstring is just an example, not a doctest, because doctest
955
963
    # currently can't cope with the use of lazy imports in this namespace --
956
964
    # mbp 20090729
957
 
    
 
965
 
958
966
    # This currently doesn't report the failure at the time it occurs, because
959
967
    # they tend to happen very early in startup when we can't check config
960
968
    # files etc, and also we want to report all failures but not spam the user
1030
1038
 
1031
1039
 
1032
1040
def delete_any(path):
1033
 
    """Delete a file, symlink or directory.  
1034
 
    
 
1041
    """Delete a file, symlink or directory.
 
1042
 
1035
1043
    Will delete even if readonly.
1036
1044
    """
1037
1045
    try:
1123
1131
 
1124
1132
 
1125
1133
def relpath(base, path):
1126
 
    """Return path relative to base, or raise exception.
 
1134
    """Return path relative to base, or raise PathNotChild exception.
1127
1135
 
1128
1136
    The path may be either an absolute path or a path relative to the
1129
1137
    current working directory.
1131
1139
    os.path.commonprefix (python2.4) has a bad bug that it works just
1132
1140
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1133
1141
    avoids that problem.
 
1142
 
 
1143
    NOTE: `base` should not have a trailing slash otherwise you'll get
 
1144
    PathNotChild exceptions regardless of `path`.
1134
1145
    """
1135
1146
 
1136
1147
    if len(base) < MIN_ABS_PATHLENGTH:
1223
1234
    # but for now, we haven't optimized...
1224
1235
    return [canonical_relpath(base, p) for p in paths]
1225
1236
 
 
1237
 
 
1238
def decode_filename(filename):
 
1239
    """Decode the filename using the filesystem encoding
 
1240
 
 
1241
    If it is unicode, it is returned.
 
1242
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1243
    fails, a errors.BadFilenameEncoding exception is raised.
 
1244
    """
 
1245
    if type(filename) is unicode:
 
1246
        return filename
 
1247
    try:
 
1248
        return filename.decode(_fs_enc)
 
1249
    except UnicodeDecodeError:
 
1250
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1251
 
 
1252
 
1226
1253
def safe_unicode(unicode_or_utf8_string):
1227
1254
    """Coerce unicode_or_utf8_string into unicode.
1228
1255
 
1311
1338
def normalizes_filenames():
1312
1339
    """Return True if this platform normalizes unicode filenames.
1313
1340
 
1314
 
    Mac OSX does, Windows/Linux do not.
 
1341
    Only Mac OSX.
1315
1342
    """
1316
1343
    return _platform_normalizes_filenames
1317
1344
 
1322
1349
    On platforms where the system normalizes filenames (Mac OSX),
1323
1350
    you can access a file by any path which will normalize correctly.
1324
1351
    On platforms where the system does not normalize filenames
1325
 
    (Windows, Linux), you have to access a file by its exact path.
 
1352
    (everything else), you have to access a file by its exact path.
1326
1353
 
1327
1354
    Internally, bzr only supports NFC normalization, since that is
1328
1355
    the standard for XML documents.
1357
1384
        platform or Python version.
1358
1385
    """
1359
1386
    try:
 
1387
        import signal
1360
1388
        siginterrupt = signal.siginterrupt
 
1389
    except ImportError:
 
1390
        # This python implementation doesn't provide signal support, hence no
 
1391
        # handler exists
 
1392
        return None
1361
1393
    except AttributeError:
1362
1394
        # siginterrupt doesn't exist on this platform, or for this version
1363
1395
        # of Python.
1629
1661
        dirblock = []
1630
1662
        append = dirblock.append
1631
1663
        try:
1632
 
            names = sorted(_listdir(top))
 
1664
            names = sorted(map(decode_filename, _listdir(top)))
1633
1665
        except OSError, e:
1634
1666
            if not _is_error_enotdir(e):
1635
1667
                raise
1824
1856
            real_handlers[kind](abspath, relpath)
1825
1857
 
1826
1858
 
 
1859
def copy_ownership_from_path(dst, src=None):
 
1860
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1861
 
 
1862
    If src is None, the containing directory is used as source. If chown
 
1863
    fails, the error is ignored and a warning is printed.
 
1864
    """
 
1865
    chown = getattr(os, 'chown', None)
 
1866
    if chown is None:
 
1867
        return
 
1868
 
 
1869
    if src == None:
 
1870
        src = os.path.dirname(dst)
 
1871
        if src == '':
 
1872
            src = '.'
 
1873
 
 
1874
    try:
 
1875
        s = os.stat(src)
 
1876
        chown(dst, s.st_uid, s.st_gid)
 
1877
    except OSError, e:
 
1878
        trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
 
1879
 
 
1880
 
1827
1881
def path_prefix_key(path):
1828
1882
    """Generate a prefix-order path key for path.
1829
1883
 
1915
1969
    return user_encoding
1916
1970
 
1917
1971
 
 
1972
def get_diff_header_encoding():
 
1973
    return get_terminal_encoding()
 
1974
 
 
1975
 
1918
1976
def get_host_name():
1919
1977
    """Return the current unicode host name.
1920
1978
 
1929
1987
        return socket.gethostname().decode(get_user_encoding())
1930
1988
 
1931
1989
 
1932
 
def recv_all(socket, bytes):
 
1990
# We must not read/write any more than 64k at a time from/to a socket so we
 
1991
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
1992
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
1993
# data at once.
 
1994
MAX_SOCKET_CHUNK = 64 * 1024
 
1995
 
 
1996
def read_bytes_from_socket(sock, report_activity=None,
 
1997
        max_read_size=MAX_SOCKET_CHUNK):
 
1998
    """Read up to max_read_size of bytes from sock and notify of progress.
 
1999
 
 
2000
    Translates "Connection reset by peer" into file-like EOF (return an
 
2001
    empty string rather than raise an error), and repeats the recv if
 
2002
    interrupted by a signal.
 
2003
    """
 
2004
    while 1:
 
2005
        try:
 
2006
            bytes = sock.recv(max_read_size)
 
2007
        except socket.error, e:
 
2008
            eno = e.args[0]
 
2009
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
 
2010
                # The connection was closed by the other side.  Callers expect
 
2011
                # an empty string to signal end-of-stream.
 
2012
                return ""
 
2013
            elif eno == errno.EINTR:
 
2014
                # Retry the interrupted recv.
 
2015
                continue
 
2016
            raise
 
2017
        else:
 
2018
            if report_activity is not None:
 
2019
                report_activity(len(bytes), 'read')
 
2020
            return bytes
 
2021
 
 
2022
 
 
2023
def recv_all(socket, count):
1933
2024
    """Receive an exact number of bytes.
1934
2025
 
1935
2026
    Regular Socket.recv() may return less than the requested number of bytes,
1936
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
2027
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1937
2028
    on all platforms, but this should work everywhere.  This will return
1938
2029
    less than the requested amount if the remote end closes.
1939
2030
 
1940
2031
    This isn't optimized and is intended mostly for use in testing.
1941
2032
    """
1942
2033
    b = ''
1943
 
    while len(b) < bytes:
1944
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
2034
    while len(b) < count:
 
2035
        new = read_bytes_from_socket(socket, None, count - len(b))
1945
2036
        if new == '':
1946
2037
            break # eof
1947
2038
        b += new
1948
2039
    return b
1949
2040
 
1950
2041
 
1951
 
def send_all(socket, bytes, report_activity=None):
 
2042
def send_all(sock, bytes, report_activity=None):
1952
2043
    """Send all bytes on a socket.
1953
2044
 
1954
 
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1955
 
    implementation sends no more than 64k at a time, which avoids this problem.
 
2045
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2046
    some platforms, and catches EINTR which may be thrown if the send is
 
2047
    interrupted by a signal.
 
2048
 
 
2049
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2050
    and provides activity reporting.
1956
2051
 
1957
2052
    :param report_activity: Call this as bytes are read, see
1958
2053
        Transport._report_activity
1959
2054
    """
1960
 
    chunk_size = 2**16
1961
 
    for pos in xrange(0, len(bytes), chunk_size):
1962
 
        block = bytes[pos:pos+chunk_size]
1963
 
        if report_activity is not None:
1964
 
            report_activity(len(block), 'write')
1965
 
        until_no_eintr(socket.sendall, block)
 
2055
    sent_total = 0
 
2056
    byte_count = len(bytes)
 
2057
    while sent_total < byte_count:
 
2058
        try:
 
2059
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2060
        except socket.error, e:
 
2061
            if e.args[0] != errno.EINTR:
 
2062
                raise
 
2063
        else:
 
2064
            sent_total += sent
 
2065
            report_activity(sent, 'write')
1966
2066
 
1967
2067
 
1968
2068
def dereference_path(path):
2009
2109
    base = dirname(bzrlib.__file__)
2010
2110
    if getattr(sys, 'frozen', None):    # bzr.exe
2011
2111
        base = abspath(pathjoin(base, '..', '..'))
2012
 
    filename = pathjoin(base, resource_relpath)
2013
 
    return open(filename, 'rU').read()
2014
 
 
 
2112
    f = file(pathjoin(base, resource_relpath), "rU")
 
2113
    try:
 
2114
        return f.read()
 
2115
    finally:
 
2116
        f.close()
2015
2117
 
2016
2118
def file_kind_from_stat_mode_thunk(mode):
2017
2119
    global file_kind_from_stat_mode
2039
2141
 
2040
2142
 
2041
2143
def until_no_eintr(f, *a, **kw):
2042
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
2144
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2145
 
 
2146
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2147
    if EINTR does occur.  This is typically only true for low-level operations
 
2148
    like os.read.  If in any doubt, don't use this.
 
2149
 
 
2150
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2151
    probably code in the Python standard library and other dependencies that
 
2152
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2153
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2154
    directly controls, but it is not a complete solution.
 
2155
    """
2043
2156
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
2044
2157
    while True:
2045
2158
        try:
2049
2162
                continue
2050
2163
            raise
2051
2164
 
 
2165
 
 
2166
@deprecated_function(deprecated_in((2, 2, 0)))
2052
2167
def re_compile_checked(re_string, flags=0, where=""):
2053
2168
    """Return a compiled re, or raise a sensible error.
2054
2169
 
2064
2179
        re_obj = re.compile(re_string, flags)
2065
2180
        re_obj.search("")
2066
2181
        return re_obj
2067
 
    except re.error, e:
 
2182
    except errors.InvalidPattern, e:
2068
2183
        if where:
2069
2184
            where = ' in ' + where
2070
2185
        # despite the name 'error' is a type
2071
 
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2072
 
            % (where, re_string, e))
 
2186
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2187
            % (where, e.msg))
2073
2188
 
2074
2189
 
2075
2190
if sys.platform == "win32":
2165
2280
if sys.platform == 'win32':
2166
2281
    def open_file(filename, mode='r', bufsize=-1):
2167
2282
        """This function is used to override the ``open`` builtin.
2168
 
        
 
2283
 
2169
2284
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2170
2285
        child processes.  Deleting or renaming a closed file opened with this
2171
2286
        function is not blocking child processes.
2204
2319
        return os.fdopen(os.open(filename, flags), mode, bufsize)
2205
2320
else:
2206
2321
    open_file = open
 
2322
 
 
2323
 
 
2324
def getuser_unicode():
 
2325
    """Return the username as unicode.
 
2326
    """
 
2327
    try:
 
2328
        user_encoding = get_user_encoding()
 
2329
        username = getpass.getuser().decode(user_encoding)
 
2330
    except UnicodeDecodeError:
 
2331
        raise errors.BzrError("Can't decode username as %s." % \
 
2332
                user_encoding)
 
2333
    return username