~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Vincent Ladeuil
  • Date: 2010-10-07 06:08:01 UTC
  • mto: This revision was merged to the branch mainline in revision 5491.
  • Revision ID: v.ladeuil+lp@free.fr-20101007060801-wfdhizfhfmctl8qa
Fix some typos and propose a release planning.

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
279
282
    # copy posixpath.abspath, but use os.getcwdu instead
280
283
    if not posixpath.isabs(path):
281
284
        path = posixpath.join(getcwd(), path)
282
 
    return _posix_normpath(path)
 
285
    return posixpath.normpath(path)
283
286
 
284
287
 
285
288
def _posix_realpath(path):
286
289
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
287
290
 
288
291
 
289
 
def _posix_normpath(path):
290
 
    path = posixpath.normpath(path)
291
 
    # Bug 861008: posixpath.normpath() returns a path normalized according to
292
 
    # the POSIX standard, which stipulates (for compatibility reasons) that two
293
 
    # leading slashes must not be simplified to one, and only if there are 3 or
294
 
    # more should they be simplified as one. So we treat the leading 2 slashes
295
 
    # as a special case here by simply removing the first slash, as we consider
296
 
    # that breaking POSIX compatibility for this obscure feature is acceptable.
297
 
    # This is not a paranoid precaution, as we notably get paths like this when
298
 
    # the repo is hosted at the root of the filesystem, i.e. in "/".    
299
 
    if path.startswith('//'):
300
 
        path = path[1:]
301
 
    return path
302
 
 
303
 
 
304
292
def _win32_fixdrive(path):
305
293
    """Force drive letters to be consistent.
306
294
 
394
382
abspath = _posix_abspath
395
383
realpath = _posix_realpath
396
384
pathjoin = os.path.join
397
 
normpath = _posix_normpath
 
385
normpath = os.path.normpath
398
386
getcwd = os.getcwdu
399
387
rename = os.rename
400
388
dirname = os.path.dirname
404
392
# These were already lazily imported into local scope
405
393
# mkdtemp = tempfile.mkdtemp
406
394
# rmtree = shutil.rmtree
407
 
lstat = os.lstat
408
 
fstat = os.fstat
409
 
 
410
 
def wrap_stat(st):
411
 
    return st
412
 
 
413
395
 
414
396
MIN_ABS_PATHLENGTH = 1
415
397
 
425
407
    getcwd = _win32_getcwd
426
408
    mkdtemp = _win32_mkdtemp
427
409
    rename = _win32_rename
428
 
    try:
429
 
        from bzrlib import _walkdirs_win32
430
 
    except ImportError:
431
 
        pass
432
 
    else:
433
 
        lstat = _walkdirs_win32.lstat
434
 
        fstat = _walkdirs_win32.fstat
435
 
        wrap_stat = _walkdirs_win32.wrap_stat
436
410
 
437
411
    MIN_ABS_PATHLENGTH = 3
438
412
 
941
915
    rps = []
942
916
    for f in ps:
943
917
        if f == '..':
944
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
918
            raise errors.BzrError("sorry, %r not allowed in path" % f)
945
919
        elif (f == '.') or (f == ''):
946
920
            pass
947
921
        else:
952
926
def joinpath(p):
953
927
    for f in p:
954
928
        if (f == '..') or (f is None) or (f == ''):
955
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
929
            raise errors.BzrError("sorry, %r not allowed in path" % f)
956
930
    return pathjoin(*p)
957
931
 
958
932
 
993
967
    # they tend to happen very early in startup when we can't check config
994
968
    # files etc, and also we want to report all failures but not spam the user
995
969
    # with 10 warnings.
 
970
    from bzrlib import trace
996
971
    exception_str = str(exception)
997
972
    if exception_str not in _extension_load_failures:
998
973
        trace.mutter("failed to load compiled extension: %s" % exception_str)
1002
977
def report_extension_load_failures():
1003
978
    if not _extension_load_failures:
1004
979
        return
1005
 
    if config.GlobalStack().get('ignore_missing_extensions'):
 
980
    from bzrlib.config import GlobalConfig
 
981
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
1006
982
        return
1007
983
    # the warnings framework should by default show this only once
1008
984
    from bzrlib.trace import warning
1170
1146
 
1171
1147
    if len(base) < MIN_ABS_PATHLENGTH:
1172
1148
        # must have space for e.g. a drive letter
1173
 
        raise ValueError(gettext('%r is too short to calculate a relative path')
 
1149
        raise ValueError('%r is too short to calculate a relative path'
1174
1150
            % (base,))
1175
1151
 
1176
1152
    rp = abspath(path)
1486
1462
    # a similar effect.
1487
1463
 
1488
1464
    # If BZR_COLUMNS is set, take it, user is always right
1489
 
    # Except if they specified 0 in which case, impose no limit here
1490
1465
    try:
1491
 
        width = int(os.environ['BZR_COLUMNS'])
 
1466
        return int(os.environ['BZR_COLUMNS'])
1492
1467
    except (KeyError, ValueError):
1493
 
        width = None
1494
 
    if width is not None:
1495
 
        if width > 0:
1496
 
            return width
1497
 
        else:
1498
 
            return None
 
1468
        pass
1499
1469
 
1500
1470
    isatty = getattr(sys.stdout, 'isatty', None)
1501
1471
    if isatty is None or not isatty():
1905
1875
        s = os.stat(src)
1906
1876
        chown(dst, s.st_uid, s.st_gid)
1907
1877
    except OSError, e:
1908
 
        trace.warning(
1909
 
            'Unable to copy ownership from "%s" to "%s". '
1910
 
            'You may want to set it manually.', src, dst)
1911
 
        trace.log_exception_quietly()
 
1878
        trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
1912
1879
 
1913
1880
 
1914
1881
def path_prefix_key(path):
2026
1993
# data at once.
2027
1994
MAX_SOCKET_CHUNK = 64 * 1024
2028
1995
 
2029
 
_end_of_stream_errors = [errno.ECONNRESET]
2030
 
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2031
 
    _eno = getattr(errno, _eno, None)
2032
 
    if _eno is not None:
2033
 
        _end_of_stream_errors.append(_eno)
2034
 
del _eno
2035
 
 
2036
 
 
2037
1996
def read_bytes_from_socket(sock, report_activity=None,
2038
1997
        max_read_size=MAX_SOCKET_CHUNK):
2039
1998
    """Read up to max_read_size of bytes from sock and notify of progress.
2047
2006
            bytes = sock.recv(max_read_size)
2048
2007
        except socket.error, e:
2049
2008
            eno = e.args[0]
2050
 
            if eno in _end_of_stream_errors:
 
2009
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2051
2010
                # The connection was closed by the other side.  Callers expect
2052
2011
                # an empty string to signal end-of-stream.
2053
2012
                return ""
2194
2153
    return file_kind_from_stat_mode(mode)
2195
2154
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2196
2155
 
2197
 
def file_stat(f, _lstat=os.lstat):
 
2156
 
 
2157
def file_kind(f, _lstat=os.lstat):
2198
2158
    try:
2199
 
        # XXX cache?
2200
 
        return _lstat(f)
 
2159
        return file_kind_from_stat_mode(_lstat(f).st_mode)
2201
2160
    except OSError, e:
2202
2161
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2203
2162
            raise errors.NoSuchFile(f)
2204
2163
        raise
2205
2164
 
2206
 
def file_kind(f, _lstat=os.lstat):
2207
 
    stat_value = file_stat(f, _lstat)
2208
 
    return file_kind_from_stat_mode(stat_value.st_mode)
2209
2165
 
2210
2166
def until_no_eintr(f, *a, **kw):
2211
2167
    """Run f(*a, **kw), retrying if an EINTR error occurs.
2271
2227
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2272
2228
        return ch
2273
2229
 
2274
 
if sys.platform.startswith('linux'):
 
2230
 
 
2231
if sys.platform == 'linux2':
2275
2232
    def _local_concurrency():
2276
 
        try:
2277
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2278
 
        except (ValueError, OSError, AttributeError):
2279
 
            return None
 
2233
        concurrency = None
 
2234
        prefix = 'processor'
 
2235
        for line in file('/proc/cpuinfo', 'rb'):
 
2236
            if line.startswith(prefix):
 
2237
                concurrency = int(line[line.find(':')+1:]) + 1
 
2238
        return concurrency
2280
2239
elif sys.platform == 'darwin':
2281
2240
    def _local_concurrency():
2282
2241
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2283
2242
                                stdout=subprocess.PIPE).communicate()[0]
2284
 
elif "bsd" in sys.platform:
 
2243
elif sys.platform[0:7] == 'freebsd':
2285
2244
    def _local_concurrency():
2286
2245
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2287
2246
                                stdout=subprocess.PIPE).communicate()[0]
2315
2274
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2316
2275
    if concurrency is None:
2317
2276
        try:
2318
 
            import multiprocessing
2319
 
        except ImportError:
2320
 
            # multiprocessing is only available on Python >= 2.6
2321
 
            try:
2322
 
                concurrency = _local_concurrency()
2323
 
            except (OSError, IOError):
2324
 
                pass
2325
 
        else:
2326
 
            concurrency = multiprocessing.cpu_count()
 
2277
            concurrency = _local_concurrency()
 
2278
        except (OSError, IOError):
 
2279
            pass
2327
2280
    try:
2328
2281
        concurrency = int(concurrency)
2329
2282
    except (TypeError, ValueError):
2400
2353
    except UnicodeDecodeError:
2401
2354
        raise errors.BzrError("Can't decode username as %s." % \
2402
2355
                user_encoding)
2403
 
    except ImportError, e:
2404
 
        if sys.platform != 'win32':
2405
 
            raise
2406
 
        if str(e) != 'No module named pwd':
2407
 
            raise
2408
 
        # https://bugs.launchpad.net/bzr/+bug/660174
2409
 
        # getpass.getuser() is unable to return username on Windows
2410
 
        # if there is no USERNAME environment variable set.
2411
 
        # That could be true if bzr is running as a service,
2412
 
        # e.g. running `bzr serve` as a service on Windows.
2413
 
        # We should not fail with traceback in this case.
2414
 
        username = u'UNKNOWN'
2415
2356
    return username
2416
 
 
2417
 
 
2418
 
def available_backup_name(base, exists):
2419
 
    """Find a non-existing backup file name.
2420
 
 
2421
 
    This will *not* create anything, this only return a 'free' entry.  This
2422
 
    should be used for checking names in a directory below a locked
2423
 
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2424
 
    Leap) and generally discouraged.
2425
 
 
2426
 
    :param base: The base name.
2427
 
 
2428
 
    :param exists: A callable returning True if the path parameter exists.
2429
 
    """
2430
 
    counter = 1
2431
 
    name = "%s.~%d~" % (base, counter)
2432
 
    while exists(name):
2433
 
        counter += 1
2434
 
        name = "%s.~%d~" % (base, counter)
2435
 
    return name
2436
 
 
2437
 
 
2438
 
def set_fd_cloexec(fd):
2439
 
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2440
 
    support for this is not available.
2441
 
    """
2442
 
    try:
2443
 
        import fcntl
2444
 
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2445
 
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2446
 
    except (ImportError, AttributeError):
2447
 
        # Either the fcntl module or specific constants are not present
2448
 
        pass
2449
 
 
2450
 
 
2451
 
def find_executable_on_path(name):
2452
 
    """Finds an executable on the PATH.
2453
 
    
2454
 
    On Windows, this will try to append each extension in the PATHEXT
2455
 
    environment variable to the name, if it cannot be found with the name
2456
 
    as given.
2457
 
    
2458
 
    :param name: The base name of the executable.
2459
 
    :return: The path to the executable found or None.
2460
 
    """
2461
 
    path = os.environ.get('PATH')
2462
 
    if path is None:
2463
 
        return None
2464
 
    path = path.split(os.pathsep)
2465
 
    if sys.platform == 'win32':
2466
 
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2467
 
        exts = [ext.lower() for ext in exts]
2468
 
        base, ext = os.path.splitext(name)
2469
 
        if ext != '':
2470
 
            if ext.lower() not in exts:
2471
 
                return None
2472
 
            name = base
2473
 
            exts = [ext]
2474
 
    else:
2475
 
        exts = ['']
2476
 
    for ext in exts:
2477
 
        for d in path:
2478
 
            f = os.path.join(d, name) + ext
2479
 
            if os.access(f, os.X_OK):
2480
 
                return f
2481
 
    return None
2482
 
 
2483
 
 
2484
 
def _posix_is_local_pid_dead(pid):
2485
 
    """True if pid doesn't correspond to live process on this machine"""
2486
 
    try:
2487
 
        # Special meaning of unix kill: just check if it's there.
2488
 
        os.kill(pid, 0)
2489
 
    except OSError, e:
2490
 
        if e.errno == errno.ESRCH:
2491
 
            # On this machine, and really not found: as sure as we can be
2492
 
            # that it's dead.
2493
 
            return True
2494
 
        elif e.errno == errno.EPERM:
2495
 
            # exists, though not ours
2496
 
            return False
2497
 
        else:
2498
 
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2499
 
            # Don't really know.
2500
 
            return False
2501
 
    else:
2502
 
        # Exists and our process: not dead.
2503
 
        return False
2504
 
 
2505
 
if sys.platform == "win32":
2506
 
    is_local_pid_dead = win32utils.is_local_pid_dead
2507
 
else:
2508
 
    is_local_pid_dead = _posix_is_local_pid_dead
2509
 
 
2510
 
 
2511
 
def fdatasync(fileno):
2512
 
    """Flush file contents to disk if possible.
2513
 
    
2514
 
    :param fileno: Integer OS file handle.
2515
 
    :raises TransportNotPossible: If flushing to disk is not possible.
2516
 
    """
2517
 
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2518
 
    if fn is not None:
2519
 
        fn(fileno)