/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: John Arbash Meinel
  • Date: 2011-04-20 09:46:28 UTC
  • mfrom: (5609.33.4 2.3)
  • mto: (5609.33.5 2.3)
  • mto: This revision was merged to the branch mainline in revision 5811.
  • Revision ID: john@arbash-meinel.com-20110420094628-l0bafq1lwb6ib1v2
Merge lp:bzr/2.3 @ 5640 so we can update the release notes (aka NEWS)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
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
961
969
    # with 10 warnings.
962
 
    from bzrlib import trace
963
970
    exception_str = str(exception)
964
971
    if exception_str not in _extension_load_failures:
965
972
        trace.mutter("failed to load compiled extension: %s" % exception_str)
1030
1037
 
1031
1038
 
1032
1039
def delete_any(path):
1033
 
    """Delete a file, symlink or directory.  
1034
 
    
 
1040
    """Delete a file, symlink or directory.
 
1041
 
1035
1042
    Will delete even if readonly.
1036
1043
    """
1037
1044
    try:
1123
1130
 
1124
1131
 
1125
1132
def relpath(base, path):
1126
 
    """Return path relative to base, or raise exception.
 
1133
    """Return path relative to base, or raise PathNotChild exception.
1127
1134
 
1128
1135
    The path may be either an absolute path or a path relative to the
1129
1136
    current working directory.
1131
1138
    os.path.commonprefix (python2.4) has a bad bug that it works just
1132
1139
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1133
1140
    avoids that problem.
 
1141
 
 
1142
    NOTE: `base` should not have a trailing slash otherwise you'll get
 
1143
    PathNotChild exceptions regardless of `path`.
1134
1144
    """
1135
1145
 
1136
1146
    if len(base) < MIN_ABS_PATHLENGTH:
1223
1233
    # but for now, we haven't optimized...
1224
1234
    return [canonical_relpath(base, p) for p in paths]
1225
1235
 
 
1236
 
 
1237
def decode_filename(filename):
 
1238
    """Decode the filename using the filesystem encoding
 
1239
 
 
1240
    If it is unicode, it is returned.
 
1241
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1242
    fails, a errors.BadFilenameEncoding exception is raised.
 
1243
    """
 
1244
    if type(filename) is unicode:
 
1245
        return filename
 
1246
    try:
 
1247
        return filename.decode(_fs_enc)
 
1248
    except UnicodeDecodeError:
 
1249
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1250
 
 
1251
 
1226
1252
def safe_unicode(unicode_or_utf8_string):
1227
1253
    """Coerce unicode_or_utf8_string into unicode.
1228
1254
 
1311
1337
def normalizes_filenames():
1312
1338
    """Return True if this platform normalizes unicode filenames.
1313
1339
 
1314
 
    Mac OSX does, Windows/Linux do not.
 
1340
    Only Mac OSX.
1315
1341
    """
1316
1342
    return _platform_normalizes_filenames
1317
1343
 
1322
1348
    On platforms where the system normalizes filenames (Mac OSX),
1323
1349
    you can access a file by any path which will normalize correctly.
1324
1350
    On platforms where the system does not normalize filenames
1325
 
    (Windows, Linux), you have to access a file by its exact path.
 
1351
    (everything else), you have to access a file by its exact path.
1326
1352
 
1327
1353
    Internally, bzr only supports NFC normalization, since that is
1328
1354
    the standard for XML documents.
1357
1383
        platform or Python version.
1358
1384
    """
1359
1385
    try:
 
1386
        import signal
1360
1387
        siginterrupt = signal.siginterrupt
 
1388
    except ImportError:
 
1389
        # This python implementation doesn't provide signal support, hence no
 
1390
        # handler exists
 
1391
        return None
1361
1392
    except AttributeError:
1362
1393
        # siginterrupt doesn't exist on this platform, or for this version
1363
1394
        # of Python.
1430
1461
    # a similar effect.
1431
1462
 
1432
1463
    # If BZR_COLUMNS is set, take it, user is always right
 
1464
    # Except if they specified 0 in which case, impose no limit here
1433
1465
    try:
1434
 
        return int(os.environ['BZR_COLUMNS'])
 
1466
        width = int(os.environ['BZR_COLUMNS'])
1435
1467
    except (KeyError, ValueError):
1436
 
        pass
 
1468
        width = None
 
1469
    if width is not None:
 
1470
        if width > 0:
 
1471
            return width
 
1472
        else:
 
1473
            return None
1437
1474
 
1438
1475
    isatty = getattr(sys.stdout, 'isatty', None)
1439
1476
    if isatty is None or not isatty():
1629
1666
        dirblock = []
1630
1667
        append = dirblock.append
1631
1668
        try:
1632
 
            names = sorted(_listdir(top))
 
1669
            names = sorted(map(decode_filename, _listdir(top)))
1633
1670
        except OSError, e:
1634
1671
            if not _is_error_enotdir(e):
1635
1672
                raise
1824
1861
            real_handlers[kind](abspath, relpath)
1825
1862
 
1826
1863
 
 
1864
def copy_ownership_from_path(dst, src=None):
 
1865
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1866
 
 
1867
    If src is None, the containing directory is used as source. If chown
 
1868
    fails, the error is ignored and a warning is printed.
 
1869
    """
 
1870
    chown = getattr(os, 'chown', None)
 
1871
    if chown is None:
 
1872
        return
 
1873
 
 
1874
    if src == None:
 
1875
        src = os.path.dirname(dst)
 
1876
        if src == '':
 
1877
            src = '.'
 
1878
 
 
1879
    try:
 
1880
        s = os.stat(src)
 
1881
        chown(dst, s.st_uid, s.st_gid)
 
1882
    except OSError, e:
 
1883
        trace.warning(
 
1884
            'Unable to copy ownership from "%s" to "%s". '
 
1885
            'You may want to set it manually.', src, dst)
 
1886
        trace.log_exception_quietly()
 
1887
 
 
1888
 
1827
1889
def path_prefix_key(path):
1828
1890
    """Generate a prefix-order path key for path.
1829
1891
 
1915
1977
    return user_encoding
1916
1978
 
1917
1979
 
 
1980
def get_diff_header_encoding():
 
1981
    return get_terminal_encoding()
 
1982
 
 
1983
 
1918
1984
def get_host_name():
1919
1985
    """Return the current unicode host name.
1920
1986
 
1929
1995
        return socket.gethostname().decode(get_user_encoding())
1930
1996
 
1931
1997
 
1932
 
def recv_all(socket, bytes):
 
1998
# We must not read/write any more than 64k at a time from/to a socket so we
 
1999
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
2000
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
2001
# data at once.
 
2002
MAX_SOCKET_CHUNK = 64 * 1024
 
2003
 
 
2004
_end_of_stream_errors = [errno.ECONNRESET]
 
2005
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
 
2006
    _eno = getattr(errno, _eno, None)
 
2007
    if _eno is not None:
 
2008
        _end_of_stream_errors.append(_eno)
 
2009
del _eno
 
2010
 
 
2011
 
 
2012
def read_bytes_from_socket(sock, report_activity=None,
 
2013
        max_read_size=MAX_SOCKET_CHUNK):
 
2014
    """Read up to max_read_size of bytes from sock and notify of progress.
 
2015
 
 
2016
    Translates "Connection reset by peer" into file-like EOF (return an
 
2017
    empty string rather than raise an error), and repeats the recv if
 
2018
    interrupted by a signal.
 
2019
    """
 
2020
    while 1:
 
2021
        try:
 
2022
            bytes = sock.recv(max_read_size)
 
2023
        except socket.error, e:
 
2024
            eno = e.args[0]
 
2025
            if eno in _end_of_stream_errors:
 
2026
                # The connection was closed by the other side.  Callers expect
 
2027
                # an empty string to signal end-of-stream.
 
2028
                return ""
 
2029
            elif eno == errno.EINTR:
 
2030
                # Retry the interrupted recv.
 
2031
                continue
 
2032
            raise
 
2033
        else:
 
2034
            if report_activity is not None:
 
2035
                report_activity(len(bytes), 'read')
 
2036
            return bytes
 
2037
 
 
2038
 
 
2039
def recv_all(socket, count):
1933
2040
    """Receive an exact number of bytes.
1934
2041
 
1935
2042
    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
 
2043
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1937
2044
    on all platforms, but this should work everywhere.  This will return
1938
2045
    less than the requested amount if the remote end closes.
1939
2046
 
1940
2047
    This isn't optimized and is intended mostly for use in testing.
1941
2048
    """
1942
2049
    b = ''
1943
 
    while len(b) < bytes:
1944
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
2050
    while len(b) < count:
 
2051
        new = read_bytes_from_socket(socket, None, count - len(b))
1945
2052
        if new == '':
1946
2053
            break # eof
1947
2054
        b += new
1948
2055
    return b
1949
2056
 
1950
2057
 
1951
 
def send_all(socket, bytes, report_activity=None):
 
2058
def send_all(sock, bytes, report_activity=None):
1952
2059
    """Send all bytes on a socket.
1953
2060
 
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.
 
2061
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2062
    some platforms, and catches EINTR which may be thrown if the send is
 
2063
    interrupted by a signal.
 
2064
 
 
2065
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2066
    and provides activity reporting.
1956
2067
 
1957
2068
    :param report_activity: Call this as bytes are read, see
1958
2069
        Transport._report_activity
1959
2070
    """
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)
 
2071
    sent_total = 0
 
2072
    byte_count = len(bytes)
 
2073
    while sent_total < byte_count:
 
2074
        try:
 
2075
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2076
        except socket.error, e:
 
2077
            if e.args[0] != errno.EINTR:
 
2078
                raise
 
2079
        else:
 
2080
            sent_total += sent
 
2081
            report_activity(sent, 'write')
 
2082
 
 
2083
 
 
2084
def connect_socket(address):
 
2085
    # Slight variation of the socket.create_connection() function (provided by
 
2086
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
 
2087
    # provide it for previous python versions. Also, we don't use the timeout
 
2088
    # parameter (provided by the python implementation) so we don't implement
 
2089
    # it either).
 
2090
    err = socket.error('getaddrinfo returns an empty list')
 
2091
    host, port = address
 
2092
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
 
2093
        af, socktype, proto, canonname, sa = res
 
2094
        sock = None
 
2095
        try:
 
2096
            sock = socket.socket(af, socktype, proto)
 
2097
            sock.connect(sa)
 
2098
            return sock
 
2099
 
 
2100
        except socket.error, err:
 
2101
            # 'err' is now the most recent error
 
2102
            if sock is not None:
 
2103
                sock.close()
 
2104
    raise err
1966
2105
 
1967
2106
 
1968
2107
def dereference_path(path):
2009
2148
    base = dirname(bzrlib.__file__)
2010
2149
    if getattr(sys, 'frozen', None):    # bzr.exe
2011
2150
        base = abspath(pathjoin(base, '..', '..'))
2012
 
    filename = pathjoin(base, resource_relpath)
2013
 
    return open(filename, 'rU').read()
2014
 
 
 
2151
    f = file(pathjoin(base, resource_relpath), "rU")
 
2152
    try:
 
2153
        return f.read()
 
2154
    finally:
 
2155
        f.close()
2015
2156
 
2016
2157
def file_kind_from_stat_mode_thunk(mode):
2017
2158
    global file_kind_from_stat_mode
2039
2180
 
2040
2181
 
2041
2182
def until_no_eintr(f, *a, **kw):
2042
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
2183
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2184
 
 
2185
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2186
    if EINTR does occur.  This is typically only true for low-level operations
 
2187
    like os.read.  If in any doubt, don't use this.
 
2188
 
 
2189
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2190
    probably code in the Python standard library and other dependencies that
 
2191
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2192
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2193
    directly controls, but it is not a complete solution.
 
2194
    """
2043
2195
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
2044
2196
    while True:
2045
2197
        try:
2049
2201
                continue
2050
2202
            raise
2051
2203
 
 
2204
 
 
2205
@deprecated_function(deprecated_in((2, 2, 0)))
2052
2206
def re_compile_checked(re_string, flags=0, where=""):
2053
2207
    """Return a compiled re, or raise a sensible error.
2054
2208
 
2064
2218
        re_obj = re.compile(re_string, flags)
2065
2219
        re_obj.search("")
2066
2220
        return re_obj
2067
 
    except re.error, e:
 
2221
    except errors.InvalidPattern, e:
2068
2222
        if where:
2069
2223
            where = ' in ' + where
2070
2224
        # despite the name 'error' is a type
2071
 
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2072
 
            % (where, re_string, e))
 
2225
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2226
            % (where, e.msg))
2073
2227
 
2074
2228
 
2075
2229
if sys.platform == "win32":
2165
2319
if sys.platform == 'win32':
2166
2320
    def open_file(filename, mode='r', bufsize=-1):
2167
2321
        """This function is used to override the ``open`` builtin.
2168
 
        
 
2322
 
2169
2323
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2170
2324
        child processes.  Deleting or renaming a closed file opened with this
2171
2325
        function is not blocking child processes.
2204
2358
        return os.fdopen(os.open(filename, flags), mode, bufsize)
2205
2359
else:
2206
2360
    open_file = open
 
2361
 
 
2362
 
 
2363
def getuser_unicode():
 
2364
    """Return the username as unicode.
 
2365
    """
 
2366
    try:
 
2367
        user_encoding = get_user_encoding()
 
2368
        username = getpass.getuser().decode(user_encoding)
 
2369
    except UnicodeDecodeError:
 
2370
        raise errors.BzrError("Can't decode username as %s." % \
 
2371
                user_encoding)
 
2372
    return username
 
2373
 
 
2374
 
 
2375
def available_backup_name(base, exists):
 
2376
    """Find a non-existing backup file name.
 
2377
 
 
2378
    This will *not* create anything, this only return a 'free' entry.  This
 
2379
    should be used for checking names in a directory below a locked
 
2380
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
 
2381
    Leap) and generally discouraged.
 
2382
 
 
2383
    :param base: The base name.
 
2384
 
 
2385
    :param exists: A callable returning True if the path parameter exists.
 
2386
    """
 
2387
    counter = 1
 
2388
    name = "%s.~%d~" % (base, counter)
 
2389
    while exists(name):
 
2390
        counter += 1
 
2391
        name = "%s.~%d~" % (base, counter)
 
2392
    return name
 
2393
 
 
2394
 
 
2395
def set_fd_cloexec(fd):
 
2396
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
 
2397
    support for this is not available.
 
2398
    """
 
2399
    try:
 
2400
        import fcntl
 
2401
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
 
2402
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
 
2403
    except (ImportError, AttributeError):
 
2404
        # Either the fcntl module or specific constants are not present
 
2405
        pass