~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Vincent Ladeuil
  • Date: 2012-01-05 16:19:30 UTC
  • mto: This revision was merged to the branch mainline in revision 6437.
  • Revision ID: v.ladeuil+lp@free.fr-20120105161930-bh6bwqnt9tvv902f
Tweak news entry to conflict on merge.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
lazy_import(globals(), """
29
29
from datetime import datetime
30
30
import getpass
31
 
import locale
32
31
import ntpath
33
32
import posixpath
34
33
import select
55
54
""")
56
55
 
57
56
from bzrlib.symbol_versioning import (
58
 
    DEPRECATED_PARAMETER,
59
57
    deprecated_function,
60
58
    deprecated_in,
61
 
    deprecated_passed,
62
 
    warn as warn_deprecated,
63
59
    )
64
60
 
65
61
from hashlib import (
949
945
    return os.fstat(f.fileno())[stat.ST_SIZE]
950
946
 
951
947
 
952
 
# Alias os.urandom to support platforms (which?) without /dev/urandom and 
953
 
# override if it doesn't work. Avoid checking on windows where there is
954
 
# significant initialisation cost that can be avoided for some bzr calls.
955
 
 
956
 
rand_bytes = os.urandom
957
 
 
958
 
if rand_bytes.__module__ != "nt":
 
948
# Define rand_bytes based on platform.
 
949
try:
 
950
    # Python 2.4 and later have os.urandom,
 
951
    # but it doesn't work on some arches
 
952
    os.urandom(1)
 
953
    rand_bytes = os.urandom
 
954
except (NotImplementedError, AttributeError):
 
955
    # If python doesn't have os.urandom, or it doesn't work,
 
956
    # then try to first pull random data from /dev/urandom
959
957
    try:
960
 
        rand_bytes(1)
961
 
    except NotImplementedError:
 
958
        rand_bytes = file('/dev/urandom', 'rb').read
 
959
    # Otherwise, use this hack as a last resort
 
960
    except (IOError, OSError):
962
961
        # not well seeded, but better than nothing
963
962
        def rand_bytes(n):
964
963
            import random
1980
1979
_cached_user_encoding = None
1981
1980
 
1982
1981
 
1983
 
def get_user_encoding(use_cache=DEPRECATED_PARAMETER):
 
1982
def get_user_encoding(use_cache=True):
1984
1983
    """Find out what the preferred user encoding is.
1985
1984
 
1986
1985
    This is generally the encoding that is used for command line parameters
1987
1986
    and file contents. This may be different from the terminal encoding
1988
1987
    or the filesystem encoding.
1989
1988
 
 
1989
    :param  use_cache:  Enable cache for detected encoding.
 
1990
                        (This parameter is turned on by default,
 
1991
                        and required only for selftesting)
 
1992
 
1990
1993
    :return: A string defining the preferred user encoding
1991
1994
    """
1992
1995
    global _cached_user_encoding
1993
 
    if deprecated_passed(use_cache):
1994
 
        warn_deprecated("use_cache should only have been used for tests",
1995
 
            DeprecationWarning, stacklevel=2) 
1996
 
    if _cached_user_encoding is not None:
 
1996
    if _cached_user_encoding is not None and use_cache:
1997
1997
        return _cached_user_encoding
1998
1998
 
1999
 
    if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2000
 
        # Use the existing locale settings and call nl_langinfo directly
2001
 
        # rather than going through getpreferredencoding. This avoids
2002
 
        # <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2003
 
        # possibility of the setlocale call throwing an error.
2004
 
        user_encoding = locale.nl_langinfo(locale.CODESET)
 
1999
    if sys.platform == 'darwin':
 
2000
        # python locale.getpreferredencoding() always return
 
2001
        # 'mac-roman' on darwin. That's a lie.
 
2002
        sys.platform = 'posix'
 
2003
        try:
 
2004
            if os.environ.get('LANG', None) is None:
 
2005
                # If LANG is not set, we end up with 'ascii', which is bad
 
2006
                # ('mac-roman' is more than ascii), so we set a default which
 
2007
                # will give us UTF-8 (which appears to work in all cases on
 
2008
                # OSX). Users are still free to override LANG of course, as
 
2009
                # long as it give us something meaningful. This work-around
 
2010
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
2011
                # work with them too -- vila 20080908
 
2012
                os.environ['LANG'] = 'en_US.UTF-8'
 
2013
            import locale
 
2014
        finally:
 
2015
            sys.platform = 'darwin'
2005
2016
    else:
2006
 
        # GZ 2011-12-19: On windows could call GetACP directly instead.
2007
 
        user_encoding = locale.getpreferredencoding(False)
 
2017
        import locale
2008
2018
 
2009
2019
    try:
2010
 
        user_encoding = codecs.lookup(user_encoding).name
2011
 
    except LookupError:
2012
 
        if user_encoding not in ("", "cp0"):
 
2020
        user_encoding = locale.getpreferredencoding()
 
2021
    except locale.Error, e:
 
2022
        sys.stderr.write('bzr: warning: %s\n'
 
2023
                         '  Could not determine what text encoding to use.\n'
 
2024
                         '  This error usually means your Python interpreter\n'
 
2025
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
2026
                         "  Continuing with ascii encoding.\n"
 
2027
                         % (e, os.environ.get('LANG')))
 
2028
        user_encoding = 'ascii'
 
2029
 
 
2030
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
2031
    # treat that as ASCII, and not support printing unicode characters to the
 
2032
    # console.
 
2033
    #
 
2034
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
2035
    if user_encoding in (None, 'cp0', ''):
 
2036
        user_encoding = 'ascii'
 
2037
    else:
 
2038
        # check encoding
 
2039
        try:
 
2040
            codecs.lookup(user_encoding)
 
2041
        except LookupError:
2013
2042
            sys.stderr.write('bzr: warning:'
2014
2043
                             ' unknown encoding %s.'
2015
2044
                             ' Continuing with ascii encoding.\n'
2016
2045
                             % user_encoding
2017
2046
                            )
2018
 
        user_encoding = 'ascii'
2019
 
    else:
2020
 
        # Get 'ascii' when setlocale has not been called or LANG=C or unset.
2021
 
        if user_encoding == 'ascii':
2022
 
            if sys.platform == 'darwin':
2023
 
                # OSX is special-cased in Python to have a UTF-8 filesystem
2024
 
                # encoding and previously had LANG set here if not present.
2025
 
                user_encoding = 'utf-8'
2026
 
            # GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2027
 
            #                for some other posix platforms as well.
2028
 
 
2029
 
    _cached_user_encoding = user_encoding
 
2047
            user_encoding = 'ascii'
 
2048
 
 
2049
    if use_cache:
 
2050
        _cached_user_encoding = user_encoding
 
2051
 
2030
2052
    return user_encoding
2031
2053
 
2032
2054
 
2034
2056
    return get_terminal_encoding()
2035
2057
 
2036
2058
 
 
2059
_message_encoding = None
 
2060
 
 
2061
 
 
2062
def get_message_encoding():
 
2063
    """Return the encoding used for messages
 
2064
 
 
2065
    While the message encoding is a general setting it should usually only be
 
2066
    needed for decoding system error strings such as from OSError instances.
 
2067
    """
 
2068
    global _message_encoding
 
2069
    if _message_encoding is None:
 
2070
        if os.name == "posix":
 
2071
            import locale
 
2072
            # This is a process-global setting that can change, but should in
 
2073
            # general just get set once at process startup then be constant.
 
2074
            _message_encoding = locale.getlocale(locale.LC_MESSAGES)[1]
 
2075
        else:
 
2076
            # On windows want the result of GetACP() which this boils down to.
 
2077
            _message_encoding = get_user_encoding()
 
2078
    return _message_encoding or "ascii"
 
2079
        
 
2080
 
2037
2081
def get_host_name():
2038
2082
    """Return the current unicode host name.
2039
2083
 
2041
2085
    behaves inconsistently on different platforms.
2042
2086
    """
2043
2087
    if sys.platform == "win32":
 
2088
        import win32utils
2044
2089
        return win32utils.get_host_name()
2045
2090
    else:
2046
2091
        import socket