~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Vincent Ladeuil
  • Date: 2010-07-15 12:37:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5347.
  • Revision ID: v.ladeuil+lp@free.fr-20100715123732-3d41ur2zrficjso3
Delete Revision.get_apparent_author.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
42
42
 
43
43
from bzrlib import (
44
44
    cache_utf8,
45
 
    config,
46
45
    errors,
47
46
    trace,
48
47
    win32utils,
49
48
    )
50
 
from bzrlib.i18n import gettext
51
49
""")
52
50
 
53
51
from bzrlib.symbol_versioning import (
55
53
    deprecated_in,
56
54
    )
57
55
 
58
 
from hashlib import (
59
 
    md5,
60
 
    sha1 as sha,
61
 
    )
 
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
57
# of 2.5
 
58
if sys.version_info < (2, 5):
 
59
    import md5 as _mod_md5
 
60
    md5 = _mod_md5.new
 
61
    import sha as _mod_sha
 
62
    sha = _mod_sha.new
 
63
else:
 
64
    from hashlib import (
 
65
        md5,
 
66
        sha1 as sha,
 
67
        )
62
68
 
63
69
 
64
70
import bzrlib
90
96
        user_encoding = get_user_encoding()
91
97
        return [a.decode(user_encoding) for a in sys.argv[1:]]
92
98
    except UnicodeDecodeError:
93
 
        raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
94
 
            "application locale.").format(a, user_encoding))
 
99
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
100
                                                            "encoding." % a))
95
101
 
96
102
 
97
103
def make_readonly(filename):
191
197
            if e.errno == errno.ENOENT:
192
198
                return False;
193
199
            else:
194
 
                raise errors.BzrError(gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
 
200
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
195
201
 
196
202
 
197
203
def fancy_rename(old, new, rename_func, unlink_func):
263
269
            else:
264
270
                rename_func(tmp_name, new)
265
271
    if failure_exc is not None:
266
 
        try:
267
 
            raise failure_exc[0], failure_exc[1], failure_exc[2]
268
 
        finally:
269
 
            del failure_exc
 
272
        raise failure_exc[0], failure_exc[1], failure_exc[2]
270
273
 
271
274
 
272
275
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
389
392
# These were already lazily imported into local scope
390
393
# mkdtemp = tempfile.mkdtemp
391
394
# rmtree = shutil.rmtree
392
 
lstat = os.lstat
393
 
fstat = os.fstat
394
 
 
395
 
def wrap_stat(st):
396
 
    return st
397
 
 
398
395
 
399
396
MIN_ABS_PATHLENGTH = 1
400
397
 
410
407
    getcwd = _win32_getcwd
411
408
    mkdtemp = _win32_mkdtemp
412
409
    rename = _win32_rename
413
 
    try:
414
 
        from bzrlib import _walkdirs_win32
415
 
    except ImportError:
416
 
        pass
417
 
    else:
418
 
        lstat = _walkdirs_win32.lstat
419
 
        fstat = _walkdirs_win32.fstat
420
 
        wrap_stat = _walkdirs_win32.wrap_stat
421
410
 
422
411
    MIN_ABS_PATHLENGTH = 3
423
412
 
926
915
    rps = []
927
916
    for f in ps:
928
917
        if f == '..':
929
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
918
            raise errors.BzrError("sorry, %r not allowed in path" % f)
930
919
        elif (f == '.') or (f == ''):
931
920
            pass
932
921
        else:
937
926
def joinpath(p):
938
927
    for f in p:
939
928
        if (f == '..') or (f is None) or (f == ''):
940
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
929
            raise errors.BzrError("sorry, %r not allowed in path" % f)
941
930
    return pathjoin(*p)
942
931
 
943
932
 
978
967
    # they tend to happen very early in startup when we can't check config
979
968
    # files etc, and also we want to report all failures but not spam the user
980
969
    # with 10 warnings.
 
970
    from bzrlib import trace
981
971
    exception_str = str(exception)
982
972
    if exception_str not in _extension_load_failures:
983
973
        trace.mutter("failed to load compiled extension: %s" % exception_str)
987
977
def report_extension_load_failures():
988
978
    if not _extension_load_failures:
989
979
        return
990
 
    if config.GlobalStack().get('ignore_missing_extensions'):
 
980
    from bzrlib.config import GlobalConfig
 
981
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
991
982
        return
992
983
    # the warnings framework should by default show this only once
993
984
    from bzrlib.trace import warning
1155
1146
 
1156
1147
    if len(base) < MIN_ABS_PATHLENGTH:
1157
1148
        # must have space for e.g. a drive letter
1158
 
        raise ValueError(gettext('%r is too short to calculate a relative path')
 
1149
        raise ValueError('%r is too short to calculate a relative path'
1159
1150
            % (base,))
1160
1151
 
1161
1152
    rp = abspath(path)
1471
1462
    # a similar effect.
1472
1463
 
1473
1464
    # If BZR_COLUMNS is set, take it, user is always right
1474
 
    # Except if they specified 0 in which case, impose no limit here
1475
1465
    try:
1476
 
        width = int(os.environ['BZR_COLUMNS'])
 
1466
        return int(os.environ['BZR_COLUMNS'])
1477
1467
    except (KeyError, ValueError):
1478
 
        width = None
1479
 
    if width is not None:
1480
 
        if width > 0:
1481
 
            return width
1482
 
        else:
1483
 
            return None
 
1468
        pass
1484
1469
 
1485
1470
    isatty = getattr(sys.stdout, 'isatty', None)
1486
1471
    if isatty is None or not isatty():
1890
1875
        s = os.stat(src)
1891
1876
        chown(dst, s.st_uid, s.st_gid)
1892
1877
    except OSError, e:
1893
 
        trace.warning(
1894
 
            'Unable to copy ownership from "%s" to "%s". '
1895
 
            'You may want to set it manually.', src, dst)
1896
 
        trace.log_exception_quietly()
 
1878
        trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
1897
1879
 
1898
1880
 
1899
1881
def path_prefix_key(path):
2011
1993
# data at once.
2012
1994
MAX_SOCKET_CHUNK = 64 * 1024
2013
1995
 
2014
 
_end_of_stream_errors = [errno.ECONNRESET]
2015
 
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2016
 
    _eno = getattr(errno, _eno, None)
2017
 
    if _eno is not None:
2018
 
        _end_of_stream_errors.append(_eno)
2019
 
del _eno
2020
 
 
2021
 
 
2022
1996
def read_bytes_from_socket(sock, report_activity=None,
2023
1997
        max_read_size=MAX_SOCKET_CHUNK):
2024
1998
    """Read up to max_read_size of bytes from sock and notify of progress.
2032
2006
            bytes = sock.recv(max_read_size)
2033
2007
        except socket.error, e:
2034
2008
            eno = e.args[0]
2035
 
            if eno in _end_of_stream_errors:
 
2009
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2036
2010
                # The connection was closed by the other side.  Callers expect
2037
2011
                # an empty string to signal end-of-stream.
2038
2012
                return ""
2091
2065
            report_activity(sent, 'write')
2092
2066
 
2093
2067
 
2094
 
def connect_socket(address):
2095
 
    # Slight variation of the socket.create_connection() function (provided by
2096
 
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
2097
 
    # provide it for previous python versions. Also, we don't use the timeout
2098
 
    # parameter (provided by the python implementation) so we don't implement
2099
 
    # it either).
2100
 
    err = socket.error('getaddrinfo returns an empty list')
2101
 
    host, port = address
2102
 
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2103
 
        af, socktype, proto, canonname, sa = res
2104
 
        sock = None
2105
 
        try:
2106
 
            sock = socket.socket(af, socktype, proto)
2107
 
            sock.connect(sa)
2108
 
            return sock
2109
 
 
2110
 
        except socket.error, err:
2111
 
            # 'err' is now the most recent error
2112
 
            if sock is not None:
2113
 
                sock.close()
2114
 
    raise err
2115
 
 
2116
 
 
2117
2068
def dereference_path(path):
2118
2069
    """Determine the real path to a file.
2119
2070
 
2179
2130
    return file_kind_from_stat_mode(mode)
2180
2131
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2181
2132
 
2182
 
def file_stat(f, _lstat=os.lstat):
 
2133
 
 
2134
def file_kind(f, _lstat=os.lstat):
2183
2135
    try:
2184
 
        # XXX cache?
2185
 
        return _lstat(f)
 
2136
        return file_kind_from_stat_mode(_lstat(f).st_mode)
2186
2137
    except OSError, e:
2187
2138
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2188
2139
            raise errors.NoSuchFile(f)
2189
2140
        raise
2190
2141
 
2191
 
def file_kind(f, _lstat=os.lstat):
2192
 
    stat_value = file_stat(f, _lstat)
2193
 
    return file_kind_from_stat_mode(stat_value.st_mode)
2194
2142
 
2195
2143
def until_no_eintr(f, *a, **kw):
2196
2144
    """Run f(*a, **kw), retrying if an EINTR error occurs.
2256
2204
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2257
2205
        return ch
2258
2206
 
2259
 
if sys.platform.startswith('linux'):
 
2207
 
 
2208
if sys.platform == 'linux2':
2260
2209
    def _local_concurrency():
2261
 
        try:
2262
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2263
 
        except (ValueError, OSError, AttributeError):
2264
 
            return None
 
2210
        concurrency = None
 
2211
        prefix = 'processor'
 
2212
        for line in file('/proc/cpuinfo', 'rb'):
 
2213
            if line.startswith(prefix):
 
2214
                concurrency = int(line[line.find(':')+1:]) + 1
 
2215
        return concurrency
2265
2216
elif sys.platform == 'darwin':
2266
2217
    def _local_concurrency():
2267
2218
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2268
2219
                                stdout=subprocess.PIPE).communicate()[0]
2269
 
elif "bsd" in sys.platform:
 
2220
elif sys.platform[0:7] == 'freebsd':
2270
2221
    def _local_concurrency():
2271
2222
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2272
2223
                                stdout=subprocess.PIPE).communicate()[0]
2300
2251
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2301
2252
    if concurrency is None:
2302
2253
        try:
2303
 
            import multiprocessing
2304
 
        except ImportError:
2305
 
            # multiprocessing is only available on Python >= 2.6
2306
 
            try:
2307
 
                concurrency = _local_concurrency()
2308
 
            except (OSError, IOError):
2309
 
                pass
2310
 
        else:
2311
 
            concurrency = multiprocessing.cpu_count()
 
2254
            concurrency = _local_concurrency()
 
2255
        except (OSError, IOError):
 
2256
            pass
2312
2257
    try:
2313
2258
        concurrency = int(concurrency)
2314
2259
    except (TypeError, ValueError):
2385
2330
    except UnicodeDecodeError:
2386
2331
        raise errors.BzrError("Can't decode username as %s." % \
2387
2332
                user_encoding)
2388
 
    except ImportError, e:
2389
 
        if sys.platform != 'win32':
2390
 
            raise
2391
 
        if str(e) != 'No module named pwd':
2392
 
            raise
2393
 
        # https://bugs.launchpad.net/bzr/+bug/660174
2394
 
        # getpass.getuser() is unable to return username on Windows
2395
 
        # if there is no USERNAME environment variable set.
2396
 
        # That could be true if bzr is running as a service,
2397
 
        # e.g. running `bzr serve` as a service on Windows.
2398
 
        # We should not fail with traceback in this case.
2399
 
        username = u'UNKNOWN'
2400
2333
    return username
2401
 
 
2402
 
 
2403
 
def available_backup_name(base, exists):
2404
 
    """Find a non-existing backup file name.
2405
 
 
2406
 
    This will *not* create anything, this only return a 'free' entry.  This
2407
 
    should be used for checking names in a directory below a locked
2408
 
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2409
 
    Leap) and generally discouraged.
2410
 
 
2411
 
    :param base: The base name.
2412
 
 
2413
 
    :param exists: A callable returning True if the path parameter exists.
2414
 
    """
2415
 
    counter = 1
2416
 
    name = "%s.~%d~" % (base, counter)
2417
 
    while exists(name):
2418
 
        counter += 1
2419
 
        name = "%s.~%d~" % (base, counter)
2420
 
    return name
2421
 
 
2422
 
 
2423
 
def set_fd_cloexec(fd):
2424
 
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2425
 
    support for this is not available.
2426
 
    """
2427
 
    try:
2428
 
        import fcntl
2429
 
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2430
 
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2431
 
    except (ImportError, AttributeError):
2432
 
        # Either the fcntl module or specific constants are not present
2433
 
        pass
2434
 
 
2435
 
 
2436
 
def find_executable_on_path(name):
2437
 
    """Finds an executable on the PATH.
2438
 
    
2439
 
    On Windows, this will try to append each extension in the PATHEXT
2440
 
    environment variable to the name, if it cannot be found with the name
2441
 
    as given.
2442
 
    
2443
 
    :param name: The base name of the executable.
2444
 
    :return: The path to the executable found or None.
2445
 
    """
2446
 
    path = os.environ.get('PATH')
2447
 
    if path is None:
2448
 
        return None
2449
 
    path = path.split(os.pathsep)
2450
 
    if sys.platform == 'win32':
2451
 
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2452
 
        exts = [ext.lower() for ext in exts]
2453
 
        base, ext = os.path.splitext(name)
2454
 
        if ext != '':
2455
 
            if ext.lower() not in exts:
2456
 
                return None
2457
 
            name = base
2458
 
            exts = [ext]
2459
 
    else:
2460
 
        exts = ['']
2461
 
    for ext in exts:
2462
 
        for d in path:
2463
 
            f = os.path.join(d, name) + ext
2464
 
            if os.access(f, os.X_OK):
2465
 
                return f
2466
 
    return None
2467
 
 
2468
 
 
2469
 
def _posix_is_local_pid_dead(pid):
2470
 
    """True if pid doesn't correspond to live process on this machine"""
2471
 
    try:
2472
 
        # Special meaning of unix kill: just check if it's there.
2473
 
        os.kill(pid, 0)
2474
 
    except OSError, e:
2475
 
        if e.errno == errno.ESRCH:
2476
 
            # On this machine, and really not found: as sure as we can be
2477
 
            # that it's dead.
2478
 
            return True
2479
 
        elif e.errno == errno.EPERM:
2480
 
            # exists, though not ours
2481
 
            return False
2482
 
        else:
2483
 
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2484
 
            # Don't really know.
2485
 
            return False
2486
 
    else:
2487
 
        # Exists and our process: not dead.
2488
 
        return False
2489
 
 
2490
 
if sys.platform == "win32":
2491
 
    is_local_pid_dead = win32utils.is_local_pid_dead
2492
 
else:
2493
 
    is_local_pid_dead = _posix_is_local_pid_dead
2494
 
 
2495
 
 
2496
 
def fdatasync(fileno):
2497
 
    """Flush file contents to disk if possible.
2498
 
    
2499
 
    :param fileno: Integer OS file handle.
2500
 
    :raises TransportNotPossible: If flushing to disk is not possible.
2501
 
    """
2502
 
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2503
 
    if fn is not None:
2504
 
        fn(fileno)