~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2010-06-28 02:41:22 UTC
  • mto: This revision was merged to the branch mainline in revision 5324.
  • Revision ID: robertc@robertcollins.net-20100628024122-g951fzp74f3u6wst
Sanity check that new_trace_file in pop_log_file is valid, and also fix a test that monkey patched get_terminal_encoding.

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
18
18
import os
19
19
import re
20
20
import stat
 
21
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
22
import sys
22
23
import time
23
24
import codecs
26
27
lazy_import(globals(), """
27
28
from datetime import datetime
28
29
import getpass
29
 
import ntpath
 
30
from ntpath import (abspath as _nt_abspath,
 
31
                    join as _nt_join,
 
32
                    normpath as _nt_normpath,
 
33
                    realpath as _nt_realpath,
 
34
                    splitdrive as _nt_splitdrive,
 
35
                    )
30
36
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
33
37
import shutil
34
 
from shutil import rmtree
 
38
from shutil import (
 
39
    rmtree,
 
40
    )
35
41
import socket
36
42
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
39
43
import tempfile
40
 
from tempfile import mkdtemp
 
44
from tempfile import (
 
45
    mkdtemp,
 
46
    )
41
47
import unicodedata
42
48
 
43
49
from bzrlib import (
53
59
    deprecated_in,
54
60
    )
55
61
 
56
 
from hashlib import (
57
 
    md5,
58
 
    sha1 as sha,
59
 
    )
 
62
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
63
# of 2.5
 
64
if sys.version_info < (2, 5):
 
65
    import md5 as _mod_md5
 
66
    md5 = _mod_md5.new
 
67
    import sha as _mod_sha
 
68
    sha = _mod_sha.new
 
69
else:
 
70
    from hashlib import (
 
71
        md5,
 
72
        sha1 as sha,
 
73
        )
60
74
 
61
75
 
62
76
import bzrlib
88
102
        user_encoding = get_user_encoding()
89
103
        return [a.decode(user_encoding) for a in sys.argv[1:]]
90
104
    except UnicodeDecodeError:
91
 
        raise errors.BzrError("Parameter %r encoding is unsupported by %s "
92
 
            "application locale." % (a, user_encoding))
 
105
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
106
                                                            "encoding." % a))
93
107
 
94
108
 
95
109
def make_readonly(filename):
261
275
            else:
262
276
                rename_func(tmp_name, new)
263
277
    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
 
278
        raise failure_exc[0], failure_exc[1], failure_exc[2]
268
279
 
269
280
 
270
281
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
293
304
    running python.exe under cmd.exe return capital C:\\
294
305
    running win32 python inside a cygwin shell returns lowercase c:\\
295
306
    """
296
 
    drive, path = ntpath.splitdrive(path)
 
307
    drive, path = _nt_splitdrive(path)
297
308
    return drive.upper() + path
298
309
 
299
310
 
300
311
def _win32_abspath(path):
301
 
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
302
 
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
 
312
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
313
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
303
314
 
304
315
 
305
316
def _win98_abspath(path):
316
327
    #   /path       => C:/path
317
328
    path = unicode(path)
318
329
    # check for absolute path
319
 
    drive = ntpath.splitdrive(path)[0]
 
330
    drive = _nt_splitdrive(path)[0]
320
331
    if drive == '' and path[:2] not in('//','\\\\'):
321
332
        cwd = os.getcwdu()
322
333
        # we cannot simply os.path.join cwd and path
323
334
        # because os.path.join('C:','/path') produce '/path'
324
335
        # and this is incorrect
325
336
        if path[:1] in ('/','\\'):
326
 
            cwd = ntpath.splitdrive(cwd)[0]
 
337
            cwd = _nt_splitdrive(cwd)[0]
327
338
            path = path[1:]
328
339
        path = cwd + '\\' + path
329
 
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
 
340
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
330
341
 
331
342
 
332
343
def _win32_realpath(path):
333
 
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
334
 
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
 
344
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
345
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
335
346
 
336
347
 
337
348
def _win32_pathjoin(*args):
338
 
    return ntpath.join(*args).replace('\\', '/')
 
349
    return _nt_join(*args).replace('\\', '/')
339
350
 
340
351
 
341
352
def _win32_normpath(path):
342
 
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
 
353
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
343
354
 
344
355
 
345
356
def _win32_getcwd():
384
395
basename = os.path.basename
385
396
split = os.path.split
386
397
splitext = os.path.splitext
387
 
# These were already lazily imported into local scope
 
398
# These were already imported into local scope
388
399
# mkdtemp = tempfile.mkdtemp
389
400
# rmtree = shutil.rmtree
390
 
lstat = os.lstat
391
 
fstat = os.fstat
392
 
 
393
 
def wrap_stat(st):
394
 
    return st
395
 
 
396
401
 
397
402
MIN_ABS_PATHLENGTH = 1
398
403
 
408
413
    getcwd = _win32_getcwd
409
414
    mkdtemp = _win32_mkdtemp
410
415
    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
416
 
420
417
    MIN_ABS_PATHLENGTH = 3
421
418
 
512
509
def isdir(f):
513
510
    """True if f is an accessible directory."""
514
511
    try:
515
 
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
 
512
        return S_ISDIR(os.lstat(f)[ST_MODE])
516
513
    except OSError:
517
514
        return False
518
515
 
520
517
def isfile(f):
521
518
    """True if f is a regular file."""
522
519
    try:
523
 
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
 
520
        return S_ISREG(os.lstat(f)[ST_MODE])
524
521
    except OSError:
525
522
        return False
526
523
 
527
524
def islink(f):
528
525
    """True if f is a symlink."""
529
526
    try:
530
 
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
 
527
        return S_ISLNK(os.lstat(f)[ST_MODE])
531
528
    except OSError:
532
529
        return False
533
530
 
873
870
 
874
871
def filesize(f):
875
872
    """Return size of given open file."""
876
 
    return os.fstat(f.fileno())[stat.ST_SIZE]
 
873
    return os.fstat(f.fileno())[ST_SIZE]
877
874
 
878
875
 
879
876
# Define rand_bytes based on platform.
976
973
    # they tend to happen very early in startup when we can't check config
977
974
    # files etc, and also we want to report all failures but not spam the user
978
975
    # with 10 warnings.
 
976
    from bzrlib import trace
979
977
    exception_str = str(exception)
980
978
    if exception_str not in _extension_load_failures:
981
979
        trace.mutter("failed to load compiled extension: %s" % exception_str)
1470
1468
    # a similar effect.
1471
1469
 
1472
1470
    # 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
1471
    try:
1475
 
        width = int(os.environ['BZR_COLUMNS'])
 
1472
        return int(os.environ['BZR_COLUMNS'])
1476
1473
    except (KeyError, ValueError):
1477
 
        width = None
1478
 
    if width is not None:
1479
 
        if width > 0:
1480
 
            return width
1481
 
        else:
1482
 
            return None
 
1474
        pass
1483
1475
 
1484
1476
    isatty = getattr(sys.stdout, 'isatty', None)
1485
1477
    if isatty is None or not isatty():
1889
1881
        s = os.stat(src)
1890
1882
        chown(dst, s.st_uid, s.st_gid)
1891
1883
    except OSError, e:
1892
 
        trace.warning(
1893
 
            'Unable to copy ownership from "%s" to "%s". '
1894
 
            'You may want to set it manually.', src, dst)
1895
 
        trace.log_exception_quietly()
 
1884
        trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
1896
1885
 
1897
1886
 
1898
1887
def path_prefix_key(path):
2010
1999
# data at once.
2011
2000
MAX_SOCKET_CHUNK = 64 * 1024
2012
2001
 
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
2002
def read_bytes_from_socket(sock, report_activity=None,
2022
2003
        max_read_size=MAX_SOCKET_CHUNK):
2023
2004
    """Read up to max_read_size of bytes from sock and notify of progress.
2031
2012
            bytes = sock.recv(max_read_size)
2032
2013
        except socket.error, e:
2033
2014
            eno = e.args[0]
2034
 
            if eno in _end_of_stream_errors:
 
2015
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2035
2016
                # The connection was closed by the other side.  Callers expect
2036
2017
                # an empty string to signal end-of-stream.
2037
2018
                return ""
2090
2071
            report_activity(sent, 'write')
2091
2072
 
2092
2073
 
2093
 
def connect_socket(address):
2094
 
    # Slight variation of the socket.create_connection() function (provided by
2095
 
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
2096
 
    # provide it for previous python versions. Also, we don't use the timeout
2097
 
    # parameter (provided by the python implementation) so we don't implement
2098
 
    # it either).
2099
 
    err = socket.error('getaddrinfo returns an empty list')
2100
 
    host, port = address
2101
 
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2102
 
        af, socktype, proto, canonname, sa = res
2103
 
        sock = None
2104
 
        try:
2105
 
            sock = socket.socket(af, socktype, proto)
2106
 
            sock.connect(sa)
2107
 
            return sock
2108
 
 
2109
 
        except socket.error, err:
2110
 
            # 'err' is now the most recent error
2111
 
            if sock is not None:
2112
 
                sock.close()
2113
 
    raise err
2114
 
 
2115
 
 
2116
2074
def dereference_path(path):
2117
2075
    """Determine the real path to a file.
2118
2076
 
2211
2169
            raise
2212
2170
 
2213
2171
 
2214
 
@deprecated_function(deprecated_in((2, 2, 0)))
2215
2172
def re_compile_checked(re_string, flags=0, where=""):
2216
2173
    """Return a compiled re, or raise a sensible error.
2217
2174
 
2227
2184
        re_obj = re.compile(re_string, flags)
2228
2185
        re_obj.search("")
2229
2186
        return re_obj
2230
 
    except errors.InvalidPattern, e:
 
2187
    except re.error, e:
2231
2188
        if where:
2232
2189
            where = ' in ' + where
2233
2190
        # despite the name 'error' is a type
2234
 
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
2235
 
            % (where, e.msg))
 
2191
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
 
2192
            % (where, re_string, e))
2236
2193
 
2237
2194
 
2238
2195
if sys.platform == "win32":
2252
2209
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2253
2210
        return ch
2254
2211
 
 
2212
 
2255
2213
if sys.platform == 'linux2':
2256
2214
    def _local_concurrency():
2257
 
        try:
2258
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2259
 
        except (ValueError, OSError, AttributeError):
2260
 
            return None
 
2215
        concurrency = None
 
2216
        prefix = 'processor'
 
2217
        for line in file('/proc/cpuinfo', 'rb'):
 
2218
            if line.startswith(prefix):
 
2219
                concurrency = int(line[line.find(':')+1:]) + 1
 
2220
        return concurrency
2261
2221
elif sys.platform == 'darwin':
2262
2222
    def _local_concurrency():
2263
2223
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2264
2224
                                stdout=subprocess.PIPE).communicate()[0]
2265
 
elif "bsd" in sys.platform:
 
2225
elif sys.platform[0:7] == 'freebsd':
2266
2226
    def _local_concurrency():
2267
2227
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2268
2228
                                stdout=subprocess.PIPE).communicate()[0]
2296
2256
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2297
2257
    if concurrency is None:
2298
2258
        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()
 
2259
            concurrency = _local_concurrency()
 
2260
        except (OSError, IOError):
 
2261
            pass
2308
2262
    try:
2309
2263
        concurrency = int(concurrency)
2310
2264
    except (TypeError, ValueError):
2381
2335
    except UnicodeDecodeError:
2382
2336
        raise errors.BzrError("Can't decode username as %s." % \
2383
2337
                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
2338
    return username
2397
 
 
2398
 
 
2399
 
def available_backup_name(base, exists):
2400
 
    """Find a non-existing backup file name.
2401
 
 
2402
 
    This will *not* create anything, this only return a 'free' entry.  This
2403
 
    should be used for checking names in a directory below a locked
2404
 
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2405
 
    Leap) and generally discouraged.
2406
 
 
2407
 
    :param base: The base name.
2408
 
 
2409
 
    :param exists: A callable returning True if the path parameter exists.
2410
 
    """
2411
 
    counter = 1
2412
 
    name = "%s.~%d~" % (base, counter)
2413
 
    while exists(name):
2414
 
        counter += 1
2415
 
        name = "%s.~%d~" % (base, counter)
2416
 
    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