~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-01-11 19:11:29 UTC
  • mfrom: (5555.3.1 local_work)
  • Revision ID: pqm@pqm.ubuntu.com-20110111191129-qxzw738fmkm0run9
(vila) Add icons for tbzrcommand (iwata)

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
53
53
    deprecated_in,
54
54
    )
55
55
 
56
 
from hashlib import (
57
 
    md5,
58
 
    sha1 as sha,
59
 
    )
 
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
        )
60
68
 
61
69
 
62
70
import bzrlib
88
96
        user_encoding = get_user_encoding()
89
97
        return [a.decode(user_encoding) for a in sys.argv[1:]]
90
98
    except UnicodeDecodeError:
91
 
        raise errors.BzrError("Parameter %r encoding is unsupported by %s "
92
 
            "application locale." % (a, user_encoding))
 
99
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
100
                                                            "encoding." % a))
93
101
 
94
102
 
95
103
def make_readonly(filename):
261
269
            else:
262
270
                rename_func(tmp_name, new)
263
271
    if failure_exc is not None:
264
 
        try:
265
 
            raise failure_exc[0], failure_exc[1], failure_exc[2]
266
 
        finally:
267
 
            del failure_exc
 
272
        raise failure_exc[0], failure_exc[1], failure_exc[2]
268
273
 
269
274
 
270
275
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
387
392
# These were already lazily imported into local scope
388
393
# mkdtemp = tempfile.mkdtemp
389
394
# rmtree = shutil.rmtree
390
 
lstat = os.lstat
391
 
fstat = os.fstat
392
 
 
393
 
def wrap_stat(st):
394
 
    return st
395
 
 
396
395
 
397
396
MIN_ABS_PATHLENGTH = 1
398
397
 
408
407
    getcwd = _win32_getcwd
409
408
    mkdtemp = _win32_mkdtemp
410
409
    rename = _win32_rename
411
 
    try:
412
 
        from bzrlib import _walkdirs_win32
413
 
    except ImportError:
414
 
        pass
415
 
    else:
416
 
        lstat = _walkdirs_win32.lstat
417
 
        fstat = _walkdirs_win32.fstat
418
 
        wrap_stat = _walkdirs_win32.wrap_stat
419
410
 
420
411
    MIN_ABS_PATHLENGTH = 3
421
412
 
1470
1461
    # a similar effect.
1471
1462
 
1472
1463
    # If BZR_COLUMNS is set, take it, user is always right
1473
 
    # Except if they specified 0 in which case, impose no limit here
1474
1464
    try:
1475
 
        width = int(os.environ['BZR_COLUMNS'])
 
1465
        return int(os.environ['BZR_COLUMNS'])
1476
1466
    except (KeyError, ValueError):
1477
 
        width = None
1478
 
    if width is not None:
1479
 
        if width > 0:
1480
 
            return width
1481
 
        else:
1482
 
            return None
 
1467
        pass
1483
1468
 
1484
1469
    isatty = getattr(sys.stdout, 'isatty', None)
1485
1470
    if isatty is None or not isatty():
2010
1995
# data at once.
2011
1996
MAX_SOCKET_CHUNK = 64 * 1024
2012
1997
 
2013
 
_end_of_stream_errors = [errno.ECONNRESET]
2014
 
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2015
 
    _eno = getattr(errno, _eno, None)
2016
 
    if _eno is not None:
2017
 
        _end_of_stream_errors.append(_eno)
2018
 
del _eno
2019
 
 
2020
 
 
2021
1998
def read_bytes_from_socket(sock, report_activity=None,
2022
1999
        max_read_size=MAX_SOCKET_CHUNK):
2023
2000
    """Read up to max_read_size of bytes from sock and notify of progress.
2031
2008
            bytes = sock.recv(max_read_size)
2032
2009
        except socket.error, e:
2033
2010
            eno = e.args[0]
2034
 
            if eno in _end_of_stream_errors:
 
2011
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2035
2012
                # The connection was closed by the other side.  Callers expect
2036
2013
                # an empty string to signal end-of-stream.
2037
2014
                return ""
2252
2229
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2253
2230
        return ch
2254
2231
 
 
2232
 
2255
2233
if sys.platform == 'linux2':
2256
2234
    def _local_concurrency():
2257
 
        try:
2258
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2259
 
        except (ValueError, OSError, AttributeError):
2260
 
            return None
 
2235
        concurrency = None
 
2236
        prefix = 'processor'
 
2237
        for line in file('/proc/cpuinfo', 'rb'):
 
2238
            if line.startswith(prefix):
 
2239
                concurrency = int(line[line.find(':')+1:]) + 1
 
2240
        return concurrency
2261
2241
elif sys.platform == 'darwin':
2262
2242
    def _local_concurrency():
2263
2243
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2264
2244
                                stdout=subprocess.PIPE).communicate()[0]
2265
 
elif "bsd" in sys.platform:
 
2245
elif sys.platform[0:7] == 'freebsd':
2266
2246
    def _local_concurrency():
2267
2247
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2268
2248
                                stdout=subprocess.PIPE).communicate()[0]
2296
2276
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2297
2277
    if concurrency is None:
2298
2278
        try:
2299
 
            import multiprocessing
2300
 
        except ImportError:
2301
 
            # multiprocessing is only available on Python >= 2.6
2302
 
            try:
2303
 
                concurrency = _local_concurrency()
2304
 
            except (OSError, IOError):
2305
 
                pass
2306
 
        else:
2307
 
            concurrency = multiprocessing.cpu_count()
 
2279
            concurrency = _local_concurrency()
 
2280
        except (OSError, IOError):
 
2281
            pass
2308
2282
    try:
2309
2283
        concurrency = int(concurrency)
2310
2284
    except (TypeError, ValueError):
2381
2355
    except UnicodeDecodeError:
2382
2356
        raise errors.BzrError("Can't decode username as %s." % \
2383
2357
                user_encoding)
2384
 
    except ImportError, e:
2385
 
        if sys.platform != 'win32':
2386
 
            raise
2387
 
        if str(e) != 'No module named pwd':
2388
 
            raise
2389
 
        # https://bugs.launchpad.net/bzr/+bug/660174
2390
 
        # getpass.getuser() is unable to return username on Windows
2391
 
        # if there is no USERNAME environment variable set.
2392
 
        # That could be true if bzr is running as a service,
2393
 
        # e.g. running `bzr serve` as a service on Windows.
2394
 
        # We should not fail with traceback in this case.
2395
 
        username = u'UNKNOWN'
2396
2358
    return username
2397
2359
 
2398
2360
 
2414
2376
        counter += 1
2415
2377
        name = "%s.~%d~" % (base, counter)
2416
2378
    return name
2417
 
 
2418
 
 
2419
 
def set_fd_cloexec(fd):
2420
 
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2421
 
    support for this is not available.
2422
 
    """
2423
 
    try:
2424
 
        import fcntl
2425
 
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2426
 
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2427
 
    except (ImportError, AttributeError):
2428
 
        # Either the fcntl module or specific constants are not present
2429
 
        pass
2430
 
 
2431
 
 
2432
 
def find_executable_on_path(name):
2433
 
    """Finds an executable on the PATH.
2434
 
    
2435
 
    On Windows, this will try to append each extension in the PATHEXT
2436
 
    environment variable to the name, if it cannot be found with the name
2437
 
    as given.
2438
 
    
2439
 
    :param name: The base name of the executable.
2440
 
    :return: The path to the executable found or None.
2441
 
    """
2442
 
    path = os.environ.get('PATH')
2443
 
    if path is None:
2444
 
        return None
2445
 
    path = path.split(os.pathsep)
2446
 
    if sys.platform == 'win32':
2447
 
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2448
 
        exts = [ext.lower() for ext in exts]
2449
 
        base, ext = os.path.splitext(name)
2450
 
        if ext != '':
2451
 
            if ext.lower() not in exts:
2452
 
                return None
2453
 
            name = base
2454
 
            exts = [ext]
2455
 
    else:
2456
 
        exts = ['']
2457
 
    for ext in exts:
2458
 
        for d in path:
2459
 
            f = os.path.join(d, name) + ext
2460
 
            if os.access(f, os.X_OK):
2461
 
                return f
2462
 
    return None
2463
 
 
2464
 
 
2465
 
def _posix_is_local_pid_dead(pid):
2466
 
    """True if pid doesn't correspond to live process on this machine"""
2467
 
    try:
2468
 
        # Special meaning of unix kill: just check if it's there.
2469
 
        os.kill(pid, 0)
2470
 
    except OSError, e:
2471
 
        if e.errno == errno.ESRCH:
2472
 
            # On this machine, and really not found: as sure as we can be
2473
 
            # that it's dead.
2474
 
            return True
2475
 
        elif e.errno == errno.EPERM:
2476
 
            # exists, though not ours
2477
 
            return False
2478
 
        else:
2479
 
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2480
 
            # Don't really know.
2481
 
            return False
2482
 
    else:
2483
 
        # Exists and our process: not dead.
2484
 
        return False
2485
 
 
2486
 
if sys.platform == "win32":
2487
 
    is_local_pid_dead = win32utils.is_local_pid_dead
2488
 
else:
2489
 
    is_local_pid_dead = _posix_is_local_pid_dead