~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2009-04-27 03:27:46 UTC
  • mto: This revision was merged to the branch mainline in revision 4304.
  • Revision ID: robertc@robertcollins.net-20090427032746-vqmcsfbsbvbm04sk
Fixup tests broken by cleaning up the layering.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 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
21
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
22
import sys
23
23
import time
24
 
import warnings
25
24
 
26
25
from bzrlib.lazy_import import lazy_import
27
26
lazy_import(globals(), """
39
38
from shutil import (
40
39
    rmtree,
41
40
    )
42
 
import signal
43
 
import subprocess
44
41
import tempfile
45
42
from tempfile import (
46
43
    mkdtemp,
72
69
from bzrlib import symbol_versioning
73
70
 
74
71
 
75
 
# Cross platform wall-clock time functionality with decent resolution.
76
 
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
77
 
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
78
 
# synchronized with ``time.time()``, this is only meant to be used to find
79
 
# delta times by subtracting from another call to this function.
80
 
timer_func = time.time
81
 
if sys.platform == 'win32':
82
 
    timer_func = time.clock
83
 
 
84
72
# On win32, O_BINARY is used to indicate the file should
85
73
# be opened in binary mode, rather than text mode.
86
74
# On other platforms, O_BINARY doesn't exist, because
89
77
O_BINARY = getattr(os, 'O_BINARY', 0)
90
78
 
91
79
 
92
 
def get_unicode_argv():
93
 
    try:
94
 
        user_encoding = get_user_encoding()
95
 
        return [a.decode(user_encoding) for a in sys.argv[1:]]
96
 
    except UnicodeDecodeError:
97
 
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
98
 
                                                            "encoding." % a))
99
 
 
100
 
 
101
80
def make_readonly(filename):
102
81
    """Make a filename read-only."""
103
82
    mod = os.lstat(filename).st_mode
118
97
 
119
98
    :param paths: A container (and hence not None) of paths.
120
99
    :return: A set of paths sufficient to include everything in paths via
121
 
        is_inside, drawn from the paths parameter.
 
100
        is_inside_any, drawn from the paths parameter.
122
101
    """
123
 
    if len(paths) < 2:
124
 
        return set(paths)
125
 
 
126
 
    def sort_key(path):
127
 
        return path.split('/')
128
 
    sorted_paths = sorted(list(paths), key=sort_key)
129
 
 
130
 
    search_paths = [sorted_paths[0]]
131
 
    for path in sorted_paths[1:]:
132
 
        if not is_inside(search_paths[-1], path):
133
 
            # This path is unique, add it
134
 
            search_paths.append(path)
135
 
 
136
 
    return set(search_paths)
 
102
    search_paths = set()
 
103
    paths = set(paths)
 
104
    for path in paths:
 
105
        other_paths = paths.difference([path])
 
106
        if not is_inside_any(other_paths, path):
 
107
            # this is a top level path, we must check it.
 
108
            search_paths.add(path)
 
109
    return search_paths
137
110
 
138
111
 
139
112
_QUOTE_RE = None
179
152
    try:
180
153
        return _kind_marker_map[kind]
181
154
    except KeyError:
182
 
        # Slightly faster than using .get(, '') when the common case is that
183
 
        # kind will be found
184
 
        return ''
 
155
        raise errors.BzrError('invalid file kind %r' % kind)
185
156
 
186
157
 
187
158
lexists = getattr(os.path, 'lexists', None)
204
175
    :param old: The old path, to rename from
205
176
    :param new: The new path, to rename to
206
177
    :param rename_func: The potentially non-atomic rename function
207
 
    :param unlink_func: A way to delete the target file if the full rename
208
 
        succeeds
 
178
    :param unlink_func: A way to delete the target file if the full rename succeeds
209
179
    """
 
180
 
210
181
    # sftp rename doesn't allow overwriting, so play tricks:
211
182
    base = os.path.basename(new)
212
183
    dirname = os.path.dirname(new)
213
 
    # callers use different encodings for the paths so the following MUST
214
 
    # respect that. We rely on python upcasting to unicode if new is unicode
215
 
    # and keeping a str if not.
216
 
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
217
 
                                      os.getpid(), rand_chars(10))
 
184
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
218
185
    tmp_name = pathjoin(dirname, tmp_name)
219
186
 
220
187
    # Rename the file out of the way, but keep track if it didn't exist
240
207
    else:
241
208
        file_existed = True
242
209
 
243
 
    failure_exc = None
244
210
    success = False
245
211
    try:
246
212
        try:
252
218
            # source and target may be aliases of each other (e.g. on a
253
219
            # case-insensitive filesystem), so we may have accidentally renamed
254
220
            # source by when we tried to rename target
255
 
            failure_exc = sys.exc_info()
256
 
            if (file_existed and e.errno in (None, errno.ENOENT)
257
 
                and old.lower() == new.lower()):
258
 
                # source and target are the same file on a case-insensitive
259
 
                # filesystem, so we don't generate an exception
260
 
                failure_exc = None
 
221
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
222
                raise
261
223
    finally:
262
224
        if file_existed:
263
225
            # If the file used to exist, rename it back into place
266
228
                unlink_func(tmp_name)
267
229
            else:
268
230
                rename_func(tmp_name, new)
269
 
    if failure_exc is not None:
270
 
        raise failure_exc[0], failure_exc[1], failure_exc[2]
271
231
 
272
232
 
273
233
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
424
384
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
425
385
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
426
386
        return shutil.rmtree(path, ignore_errors, onerror)
427
 
 
428
 
    f = win32utils.get_unicode_argv     # special function or None
429
 
    if f is not None:
430
 
        get_unicode_argv = f
431
 
 
432
387
elif sys.platform == 'darwin':
433
388
    getcwd = _mac_getcwd
434
389
 
711
666
    return offset.days * 86400 + offset.seconds
712
667
 
713
668
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
714
 
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
715
 
 
716
669
 
717
670
def format_date(t, offset=0, timezone='original', date_fmt=None,
718
671
                show_offset=True):
732
685
    date_str = time.strftime(date_fmt, tt)
733
686
    return date_str + offset_str
734
687
 
735
 
 
736
 
# Cache of formatted offset strings
737
 
_offset_cache = {}
738
 
 
739
 
 
740
 
def format_date_with_offset_in_original_timezone(t, offset=0,
741
 
    _cache=_offset_cache):
742
 
    """Return a formatted date string in the original timezone.
743
 
 
744
 
    This routine may be faster then format_date.
745
 
 
746
 
    :param t: Seconds since the epoch.
747
 
    :param offset: Timezone offset in seconds east of utc.
748
 
    """
749
 
    if offset is None:
750
 
        offset = 0
751
 
    tt = time.gmtime(t + offset)
752
 
    date_fmt = _default_format_by_weekday_num[tt[6]]
753
 
    date_str = time.strftime(date_fmt, tt)
754
 
    offset_str = _cache.get(offset, None)
755
 
    if offset_str is None:
756
 
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
757
 
        _cache[offset] = offset_str
758
 
    return date_str + offset_str
759
 
 
760
 
 
761
688
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
762
689
                      show_offset=True):
763
690
    """Return an unicode date string formatted according to the current locale.
774
701
               _format_date(t, offset, timezone, date_fmt, show_offset)
775
702
    date_str = time.strftime(date_fmt, tt)
776
703
    if not isinstance(date_str, unicode):
777
 
        date_str = date_str.decode(get_user_encoding(), 'replace')
 
704
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
778
705
    return date_str + offset_str
779
706
 
780
 
 
781
707
def _format_date(t, offset, timezone, date_fmt, show_offset):
782
708
    if timezone == 'utc':
783
709
        tt = time.gmtime(t)
921
847
    return pathjoin(*p)
922
848
 
923
849
 
924
 
def parent_directories(filename):
925
 
    """Return the list of parent directories, deepest first.
926
 
    
927
 
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
928
 
    """
929
 
    parents = []
930
 
    parts = splitpath(dirname(filename))
931
 
    while parts:
932
 
        parents.append(joinpath(parts))
933
 
        parts.pop()
934
 
    return parents
935
 
 
936
 
 
937
 
_extension_load_failures = []
938
 
 
939
 
 
940
 
def failed_to_load_extension(exception):
941
 
    """Handle failing to load a binary extension.
942
 
 
943
 
    This should be called from the ImportError block guarding the attempt to
944
 
    import the native extension.  If this function returns, the pure-Python
945
 
    implementation should be loaded instead::
946
 
 
947
 
    >>> try:
948
 
    >>>     import bzrlib._fictional_extension_pyx
949
 
    >>> except ImportError, e:
950
 
    >>>     bzrlib.osutils.failed_to_load_extension(e)
951
 
    >>>     import bzrlib._fictional_extension_py
952
 
    """
953
 
    # NB: This docstring is just an example, not a doctest, because doctest
954
 
    # currently can't cope with the use of lazy imports in this namespace --
955
 
    # mbp 20090729
956
 
    
957
 
    # This currently doesn't report the failure at the time it occurs, because
958
 
    # they tend to happen very early in startup when we can't check config
959
 
    # files etc, and also we want to report all failures but not spam the user
960
 
    # with 10 warnings.
961
 
    from bzrlib import trace
962
 
    exception_str = str(exception)
963
 
    if exception_str not in _extension_load_failures:
964
 
        trace.mutter("failed to load compiled extension: %s" % exception_str)
965
 
        _extension_load_failures.append(exception_str)
966
 
 
967
 
 
968
 
def report_extension_load_failures():
969
 
    if not _extension_load_failures:
970
 
        return
971
 
    from bzrlib.config import GlobalConfig
972
 
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
973
 
        return
974
 
    # the warnings framework should by default show this only once
975
 
    from bzrlib.trace import warning
976
 
    warning(
977
 
        "bzr: warning: some compiled extensions could not be loaded; "
978
 
        "see <https://answers.launchpad.net/bzr/+faq/703>")
979
 
    # we no longer show the specific missing extensions here, because it makes
980
 
    # the message too long and scary - see
981
 
    # https://bugs.launchpad.net/bzr/+bug/430529
982
 
 
983
 
 
984
850
try:
985
851
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
986
 
except ImportError, e:
987
 
    failed_to_load_extension(e)
 
852
except ImportError:
988
853
    from bzrlib._chunks_to_lines_py import chunks_to_lines
989
854
 
990
855
 
1028
893
        shutil.copyfile(src, dest)
1029
894
 
1030
895
 
 
896
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
897
# Forgiveness than Permission (EAFP) because:
 
898
# - root can damage a solaris file system by using unlink,
 
899
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
900
#   EACCES, OSX: EPERM) when invoked on a directory.
1031
901
def delete_any(path):
1032
 
    """Delete a file, symlink or directory.  
1033
 
    
1034
 
    Will delete even if readonly.
1035
 
    """
1036
 
    try:
1037
 
       _delete_file_or_dir(path)
1038
 
    except (OSError, IOError), e:
1039
 
        if e.errno in (errno.EPERM, errno.EACCES):
1040
 
            # make writable and try again
1041
 
            try:
1042
 
                make_writable(path)
1043
 
            except (OSError, IOError):
1044
 
                pass
1045
 
            _delete_file_or_dir(path)
1046
 
        else:
1047
 
            raise
1048
 
 
1049
 
 
1050
 
def _delete_file_or_dir(path):
1051
 
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1052
 
    # Forgiveness than Permission (EAFP) because:
1053
 
    # - root can damage a solaris file system by using unlink,
1054
 
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1055
 
    #   EACCES, OSX: EPERM) when invoked on a directory.
 
902
    """Delete a file or directory."""
1056
903
    if isdir(path): # Takes care of symlinks
1057
904
        os.rmdir(path)
1058
905
    else:
1078
925
            and sys.platform not in ('cygwin', 'win32'))
1079
926
 
1080
927
 
1081
 
def readlink(abspath):
1082
 
    """Return a string representing the path to which the symbolic link points.
1083
 
 
1084
 
    :param abspath: The link absolute unicode path.
1085
 
 
1086
 
    This his guaranteed to return the symbolic link in unicode in all python
1087
 
    versions.
1088
 
    """
1089
 
    link = abspath.encode(_fs_enc)
1090
 
    target = os.readlink(link)
1091
 
    target = target.decode(_fs_enc)
1092
 
    return target
1093
 
 
1094
 
 
1095
928
def contains_whitespace(s):
1096
929
    """True if there are any whitespace characters in s."""
1097
930
    # string.whitespace can include '\xa0' in certain locales, because it is
1141
974
 
1142
975
    s = []
1143
976
    head = rp
1144
 
    while True:
1145
 
        if len(head) <= len(base) and head != base:
1146
 
            raise errors.PathNotChild(rp, base)
 
977
    while len(head) >= len(base):
1147
978
        if head == base:
1148
979
            break
1149
 
        head, tail = split(head)
 
980
        head, tail = os.path.split(head)
1150
981
        if tail:
1151
 
            s.append(tail)
 
982
            s.insert(0, tail)
 
983
    else:
 
984
        raise errors.PathNotChild(rp, base)
1152
985
 
1153
986
    if s:
1154
 
        return pathjoin(*reversed(s))
 
987
        return pathjoin(*s)
1155
988
    else:
1156
989
        return ''
1157
990
 
1184
1017
    bit_iter = iter(rel.split('/'))
1185
1018
    for bit in bit_iter:
1186
1019
        lbit = bit.lower()
1187
 
        try:
1188
 
            next_entries = _listdir(current)
1189
 
        except OSError: # enoent, eperm, etc
1190
 
            # We can't find this in the filesystem, so just append the
1191
 
            # remaining bits.
1192
 
            current = pathjoin(current, bit, *list(bit_iter))
1193
 
            break
1194
 
        for look in next_entries:
 
1020
        for look in _listdir(current):
1195
1021
            if lbit == look.lower():
1196
1022
                current = pathjoin(current, look)
1197
1023
                break
1201
1027
            # the target of a move, for example).
1202
1028
            current = pathjoin(current, bit, *list(bit_iter))
1203
1029
            break
1204
 
    return current[len(abs_base):].lstrip('/')
 
1030
    return current[len(abs_base)+1:]
1205
1031
 
1206
1032
# XXX - TODO - we need better detection/integration of case-insensitive
1207
1033
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1346
1172
    normalized_filename = _inaccessible_normalized_filename
1347
1173
 
1348
1174
 
1349
 
default_terminal_width = 80
1350
 
"""The default terminal width for ttys.
1351
 
 
1352
 
This is defined so that higher levels can share a common fallback value when
1353
 
terminal_width() returns None.
1354
 
"""
1355
 
 
1356
 
 
1357
1175
def terminal_width():
1358
 
    """Return terminal width.
1359
 
 
1360
 
    None is returned if the width can't established precisely.
1361
 
 
1362
 
    The rules are:
1363
 
    - if BZR_COLUMNS is set, returns its value
1364
 
    - if there is no controlling terminal, returns None
1365
 
    - if COLUMNS is set, returns its value,
1366
 
 
1367
 
    From there, we need to query the OS to get the size of the controlling
1368
 
    terminal.
1369
 
 
1370
 
    Unices:
1371
 
    - get termios.TIOCGWINSZ
1372
 
    - if an error occurs or a negative value is obtained, returns None
1373
 
 
1374
 
    Windows:
1375
 
    
1376
 
    - win32utils.get_console_size() decides,
1377
 
    - returns None on error (provided default value)
1378
 
    """
1379
 
 
1380
 
    # If BZR_COLUMNS is set, take it, user is always right
1381
 
    try:
1382
 
        return int(os.environ['BZR_COLUMNS'])
1383
 
    except (KeyError, ValueError):
1384
 
        pass
1385
 
 
1386
 
    isatty = getattr(sys.stdout, 'isatty', None)
1387
 
    if  isatty is None or not isatty():
1388
 
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
1389
 
        return None
1390
 
 
1391
 
    # If COLUMNS is set, take it, the terminal knows better (even inside a
1392
 
    # given terminal, the application can decide to set COLUMNS to a lower
1393
 
    # value (splitted screen) or a bigger value (scroll bars))
1394
 
    try:
1395
 
        return int(os.environ['COLUMNS'])
1396
 
    except (KeyError, ValueError):
1397
 
        pass
1398
 
 
1399
 
    width, height = _terminal_size(None, None)
1400
 
    if width <= 0:
1401
 
        # Consider invalid values as meaning no width
1402
 
        return None
1403
 
 
1404
 
    return width
1405
 
 
1406
 
 
1407
 
def _win32_terminal_size(width, height):
1408
 
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1409
 
    return width, height
1410
 
 
1411
 
 
1412
 
def _ioctl_terminal_size(width, height):
 
1176
    """Return estimated terminal width."""
 
1177
    if sys.platform == 'win32':
 
1178
        return win32utils.get_console_size()[0]
 
1179
    width = 0
1413
1180
    try:
1414
1181
        import struct, fcntl, termios
1415
1182
        s = struct.pack('HHHH', 0, 0, 0, 0)
1416
1183
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1417
 
        height, width = struct.unpack('HHHH', x)[0:2]
1418
 
    except (IOError, AttributeError):
 
1184
        width = struct.unpack('HHHH', x)[1]
 
1185
    except IOError:
1419
1186
        pass
1420
 
    return width, height
1421
 
 
1422
 
_terminal_size = None
1423
 
"""Returns the terminal size as (width, height).
1424
 
 
1425
 
:param width: Default value for width.
1426
 
:param height: Default value for height.
1427
 
 
1428
 
This is defined specifically for each OS and query the size of the controlling
1429
 
terminal. If any error occurs, the provided default values should be returned.
1430
 
"""
1431
 
if sys.platform == 'win32':
1432
 
    _terminal_size = _win32_terminal_size
1433
 
else:
1434
 
    _terminal_size = _ioctl_terminal_size
1435
 
 
1436
 
 
1437
 
def _terminal_size_changed(signum, frame):
1438
 
    """Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1439
 
    width, height = _terminal_size(None, None)
1440
 
    if width is not None:
1441
 
        os.environ['COLUMNS'] = str(width)
1442
 
 
1443
 
if sys.platform == 'win32':
1444
 
    # Martin (gz) mentioned WINDOW_BUFFER_SIZE_RECORD from ReadConsoleInput but
1445
 
    # I've no idea how to plug that in the current design -- vila 20091216
1446
 
    pass
1447
 
else:
1448
 
    signal.signal(signal.SIGWINCH, _terminal_size_changed)
 
1187
    if width <= 0:
 
1188
        try:
 
1189
            width = int(os.environ['COLUMNS'])
 
1190
        except:
 
1191
            pass
 
1192
    if width <= 0:
 
1193
        width = 80
 
1194
 
 
1195
    return width
1449
1196
 
1450
1197
 
1451
1198
def supports_executable():
1645
1392
            #       for win98 anyway.
1646
1393
            try:
1647
1394
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1395
            except ImportError:
 
1396
                _selected_dir_reader = UnicodeDirReader()
 
1397
            else:
1648
1398
                _selected_dir_reader = Win32ReadDir()
1649
 
            except ImportError:
1650
 
                pass
1651
 
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1399
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1652
1400
            # ANSI_X3.4-1968 is a form of ASCII
 
1401
            _selected_dir_reader = UnicodeDirReader()
 
1402
        else:
1653
1403
            try:
1654
1404
                from bzrlib._readdir_pyx import UTF8DirReader
 
1405
            except ImportError:
 
1406
                # No optimised code path
 
1407
                _selected_dir_reader = UnicodeDirReader()
 
1408
            else:
1655
1409
                _selected_dir_reader = UTF8DirReader()
1656
 
            except ImportError, e:
1657
 
                failed_to_load_extension(e)
1658
 
                pass
1659
 
 
1660
 
    if _selected_dir_reader is None:
1661
 
        # Fallback to the python version
1662
 
        _selected_dir_reader = UnicodeDirReader()
1663
 
 
1664
1410
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1665
1411
    # But we don't actually uses 1-3 in pending, so set them to None
1666
1412
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1966
1712
        try:
1967
1713
            from bzrlib._readdir_pyx import UTF8DirReader
1968
1714
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1969
 
        except ImportError, e:
1970
 
            # This is one time where we won't warn that an extension failed to
1971
 
            # load. The extension is never available on Windows anyway.
 
1715
        except ImportError:
1972
1716
            from bzrlib._readdir_py import (
1973
1717
                _kind_from_mode as file_kind_from_stat_mode
1974
1718
                )
1998
1742
 
1999
1743
def re_compile_checked(re_string, flags=0, where=""):
2000
1744
    """Return a compiled re, or raise a sensible error.
2001
 
 
 
1745
    
2002
1746
    This should only be used when compiling user-supplied REs.
2003
1747
 
2004
1748
    :param re_string: Text form of regular expression.
2005
1749
    :param flags: eg re.IGNORECASE
2006
 
    :param where: Message explaining to the user the context where
 
1750
    :param where: Message explaining to the user the context where 
2007
1751
        it occurred, eg 'log search filter'.
2008
1752
    """
2009
1753
    # from https://bugs.launchpad.net/bzr/+bug/251352
2035
1779
        finally:
2036
1780
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2037
1781
        return ch
2038
 
 
2039
 
 
2040
 
if sys.platform == 'linux2':
2041
 
    def _local_concurrency():
2042
 
        concurrency = None
2043
 
        prefix = 'processor'
2044
 
        for line in file('/proc/cpuinfo', 'rb'):
2045
 
            if line.startswith(prefix):
2046
 
                concurrency = int(line[line.find(':')+1:]) + 1
2047
 
        return concurrency
2048
 
elif sys.platform == 'darwin':
2049
 
    def _local_concurrency():
2050
 
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2051
 
                                stdout=subprocess.PIPE).communicate()[0]
2052
 
elif sys.platform[0:7] == 'freebsd':
2053
 
    def _local_concurrency():
2054
 
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2055
 
                                stdout=subprocess.PIPE).communicate()[0]
2056
 
elif sys.platform == 'sunos5':
2057
 
    def _local_concurrency():
2058
 
        return subprocess.Popen(['psrinfo', '-p',],
2059
 
                                stdout=subprocess.PIPE).communicate()[0]
2060
 
elif sys.platform == "win32":
2061
 
    def _local_concurrency():
2062
 
        # This appears to return the number of cores.
2063
 
        return os.environ.get('NUMBER_OF_PROCESSORS')
2064
 
else:
2065
 
    def _local_concurrency():
2066
 
        # Who knows ?
2067
 
        return None
2068
 
 
2069
 
 
2070
 
_cached_local_concurrency = None
2071
 
 
2072
 
def local_concurrency(use_cache=True):
2073
 
    """Return how many processes can be run concurrently.
2074
 
 
2075
 
    Rely on platform specific implementations and default to 1 (one) if
2076
 
    anything goes wrong.
2077
 
    """
2078
 
    global _cached_local_concurrency
2079
 
 
2080
 
    if _cached_local_concurrency is not None and use_cache:
2081
 
        return _cached_local_concurrency
2082
 
 
2083
 
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2084
 
    if concurrency is None:
2085
 
        try:
2086
 
            concurrency = _local_concurrency()
2087
 
        except (OSError, IOError):
2088
 
            pass
2089
 
    try:
2090
 
        concurrency = int(concurrency)
2091
 
    except (TypeError, ValueError):
2092
 
        concurrency = 1
2093
 
    if use_cache:
2094
 
        _cached_concurrency = concurrency
2095
 
    return concurrency
2096
 
 
2097
 
 
2098
 
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2099
 
    """A stream writer that doesn't decode str arguments."""
2100
 
 
2101
 
    def __init__(self, encode, stream, errors='strict'):
2102
 
        codecs.StreamWriter.__init__(self, stream, errors)
2103
 
        self.encode = encode
2104
 
 
2105
 
    def write(self, object):
2106
 
        if type(object) is str:
2107
 
            self.stream.write(object)
2108
 
        else:
2109
 
            data, _ = self.encode(object, self.errors)
2110
 
            self.stream.write(data)