~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Vincent Ladeuil
  • Date: 2010-04-26 13:51:08 UTC
  • mto: (5184.2.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5185.
  • Revision ID: v.ladeuil+lp@free.fr-20100426135108-vwmfphc2xg1w058c
Random cleanups to catch up with copyright updates in trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2009 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
21
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
22
import sys
23
23
import time
 
24
import codecs
 
25
import warnings
24
26
 
25
27
from bzrlib.lazy_import import lazy_import
26
28
lazy_import(globals(), """
27
 
import codecs
28
29
from datetime import datetime
29
30
import errno
30
31
from ntpath import (abspath as _nt_abspath,
38
39
from shutil import (
39
40
    rmtree,
40
41
    )
 
42
import socket
 
43
import subprocess
41
44
import tempfile
42
45
from tempfile import (
43
46
    mkdtemp,
47
50
from bzrlib import (
48
51
    cache_utf8,
49
52
    errors,
 
53
    trace,
50
54
    win32utils,
51
55
    )
52
56
""")
53
57
 
 
58
from bzrlib.symbol_versioning import (
 
59
    deprecated_function,
 
60
    deprecated_in,
 
61
    )
 
62
 
54
63
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
55
64
# of 2.5
56
65
if sys.version_info < (2, 5):
69
78
from bzrlib import symbol_versioning
70
79
 
71
80
 
 
81
# Cross platform wall-clock time functionality with decent resolution.
 
82
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
 
83
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
 
84
# synchronized with ``time.time()``, this is only meant to be used to find
 
85
# delta times by subtracting from another call to this function.
 
86
timer_func = time.time
 
87
if sys.platform == 'win32':
 
88
    timer_func = time.clock
 
89
 
72
90
# On win32, O_BINARY is used to indicate the file should
73
91
# be opened in binary mode, rather than text mode.
74
92
# On other platforms, O_BINARY doesn't exist, because
75
93
# they always open in binary mode, so it is okay to
76
 
# OR with 0 on those platforms
 
94
# OR with 0 on those platforms.
 
95
# O_NOINHERIT and O_TEXT exists only on win32 too.
77
96
O_BINARY = getattr(os, 'O_BINARY', 0)
 
97
O_TEXT = getattr(os, 'O_TEXT', 0)
 
98
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
 
99
 
 
100
 
 
101
def get_unicode_argv():
 
102
    try:
 
103
        user_encoding = get_user_encoding()
 
104
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
105
    except UnicodeDecodeError:
 
106
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
107
                                                            "encoding." % a))
78
108
 
79
109
 
80
110
def make_readonly(filename):
97
127
 
98
128
    :param paths: A container (and hence not None) of paths.
99
129
    :return: A set of paths sufficient to include everything in paths via
100
 
        is_inside_any, drawn from the paths parameter.
 
130
        is_inside, drawn from the paths parameter.
101
131
    """
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
 
132
    if len(paths) < 2:
 
133
        return set(paths)
 
134
 
 
135
    def sort_key(path):
 
136
        return path.split('/')
 
137
    sorted_paths = sorted(list(paths), key=sort_key)
 
138
 
 
139
    search_paths = [sorted_paths[0]]
 
140
    for path in sorted_paths[1:]:
 
141
        if not is_inside(search_paths[-1], path):
 
142
            # This path is unique, add it
 
143
            search_paths.append(path)
 
144
 
 
145
    return set(search_paths)
110
146
 
111
147
 
112
148
_QUOTE_RE = None
152
188
    try:
153
189
        return _kind_marker_map[kind]
154
190
    except KeyError:
155
 
        raise errors.BzrError('invalid file kind %r' % kind)
 
191
        # Slightly faster than using .get(, '') when the common case is that
 
192
        # kind will be found
 
193
        return ''
156
194
 
157
195
 
158
196
lexists = getattr(os.path, 'lexists', None)
175
213
    :param old: The old path, to rename from
176
214
    :param new: The new path, to rename to
177
215
    :param rename_func: The potentially non-atomic rename function
178
 
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
216
    :param unlink_func: A way to delete the target file if the full rename
 
217
        succeeds
179
218
    """
180
 
 
181
219
    # sftp rename doesn't allow overwriting, so play tricks:
182
220
    base = os.path.basename(new)
183
221
    dirname = os.path.dirname(new)
184
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
222
    # callers use different encodings for the paths so the following MUST
 
223
    # respect that. We rely on python upcasting to unicode if new is unicode
 
224
    # and keeping a str if not.
 
225
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
 
226
                                      os.getpid(), rand_chars(10))
185
227
    tmp_name = pathjoin(dirname, tmp_name)
186
228
 
187
229
    # Rename the file out of the way, but keep track if it didn't exist
207
249
    else:
208
250
        file_existed = True
209
251
 
 
252
    failure_exc = None
210
253
    success = False
211
254
    try:
212
255
        try:
218
261
            # source and target may be aliases of each other (e.g. on a
219
262
            # case-insensitive filesystem), so we may have accidentally renamed
220
263
            # source by when we tried to rename target
221
 
            if not (file_existed and e.errno in (None, errno.ENOENT)):
222
 
                raise
 
264
            failure_exc = sys.exc_info()
 
265
            if (file_existed and e.errno in (None, errno.ENOENT)
 
266
                and old.lower() == new.lower()):
 
267
                # source and target are the same file on a case-insensitive
 
268
                # filesystem, so we don't generate an exception
 
269
                failure_exc = None
223
270
    finally:
224
271
        if file_existed:
225
272
            # If the file used to exist, rename it back into place
228
275
                unlink_func(tmp_name)
229
276
            else:
230
277
                rename_func(tmp_name, new)
 
278
    if failure_exc is not None:
 
279
        raise failure_exc[0], failure_exc[1], failure_exc[2]
231
280
 
232
281
 
233
282
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
384
433
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
385
434
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
386
435
        return shutil.rmtree(path, ignore_errors, onerror)
 
436
 
 
437
    f = win32utils.get_unicode_argv     # special function or None
 
438
    if f is not None:
 
439
        get_unicode_argv = f
 
440
 
387
441
elif sys.platform == 'darwin':
388
442
    getcwd = _mac_getcwd
389
443
 
618
672
def sha_file_by_name(fname):
619
673
    """Calculate the SHA1 of a file by reading the full text"""
620
674
    s = sha()
621
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
675
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
622
676
    try:
623
677
        while True:
624
678
            b = os.read(f, 1<<16)
666
720
    return offset.days * 86400 + offset.seconds
667
721
 
668
722
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
 
723
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
 
724
 
669
725
 
670
726
def format_date(t, offset=0, timezone='original', date_fmt=None,
671
727
                show_offset=True):
685
741
    date_str = time.strftime(date_fmt, tt)
686
742
    return date_str + offset_str
687
743
 
 
744
 
 
745
# Cache of formatted offset strings
 
746
_offset_cache = {}
 
747
 
 
748
 
 
749
def format_date_with_offset_in_original_timezone(t, offset=0,
 
750
    _cache=_offset_cache):
 
751
    """Return a formatted date string in the original timezone.
 
752
 
 
753
    This routine may be faster then format_date.
 
754
 
 
755
    :param t: Seconds since the epoch.
 
756
    :param offset: Timezone offset in seconds east of utc.
 
757
    """
 
758
    if offset is None:
 
759
        offset = 0
 
760
    tt = time.gmtime(t + offset)
 
761
    date_fmt = _default_format_by_weekday_num[tt[6]]
 
762
    date_str = time.strftime(date_fmt, tt)
 
763
    offset_str = _cache.get(offset, None)
 
764
    if offset_str is None:
 
765
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
766
        _cache[offset] = offset_str
 
767
    return date_str + offset_str
 
768
 
 
769
 
688
770
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
689
771
                      show_offset=True):
690
772
    """Return an unicode date string formatted according to the current locale.
701
783
               _format_date(t, offset, timezone, date_fmt, show_offset)
702
784
    date_str = time.strftime(date_fmt, tt)
703
785
    if not isinstance(date_str, unicode):
704
 
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
 
786
        date_str = date_str.decode(get_user_encoding(), 'replace')
705
787
    return date_str + offset_str
706
788
 
 
789
 
707
790
def _format_date(t, offset, timezone, date_fmt, show_offset):
708
791
    if timezone == 'utc':
709
792
        tt = time.gmtime(t)
847
930
    return pathjoin(*p)
848
931
 
849
932
 
 
933
def parent_directories(filename):
 
934
    """Return the list of parent directories, deepest first.
 
935
    
 
936
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
 
937
    """
 
938
    parents = []
 
939
    parts = splitpath(dirname(filename))
 
940
    while parts:
 
941
        parents.append(joinpath(parts))
 
942
        parts.pop()
 
943
    return parents
 
944
 
 
945
 
 
946
_extension_load_failures = []
 
947
 
 
948
 
 
949
def failed_to_load_extension(exception):
 
950
    """Handle failing to load a binary extension.
 
951
 
 
952
    This should be called from the ImportError block guarding the attempt to
 
953
    import the native extension.  If this function returns, the pure-Python
 
954
    implementation should be loaded instead::
 
955
 
 
956
    >>> try:
 
957
    >>>     import bzrlib._fictional_extension_pyx
 
958
    >>> except ImportError, e:
 
959
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
960
    >>>     import bzrlib._fictional_extension_py
 
961
    """
 
962
    # NB: This docstring is just an example, not a doctest, because doctest
 
963
    # currently can't cope with the use of lazy imports in this namespace --
 
964
    # mbp 20090729
 
965
    
 
966
    # This currently doesn't report the failure at the time it occurs, because
 
967
    # they tend to happen very early in startup when we can't check config
 
968
    # files etc, and also we want to report all failures but not spam the user
 
969
    # with 10 warnings.
 
970
    from bzrlib import trace
 
971
    exception_str = str(exception)
 
972
    if exception_str not in _extension_load_failures:
 
973
        trace.mutter("failed to load compiled extension: %s" % exception_str)
 
974
        _extension_load_failures.append(exception_str)
 
975
 
 
976
 
 
977
def report_extension_load_failures():
 
978
    if not _extension_load_failures:
 
979
        return
 
980
    from bzrlib.config import GlobalConfig
 
981
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
 
982
        return
 
983
    # the warnings framework should by default show this only once
 
984
    from bzrlib.trace import warning
 
985
    warning(
 
986
        "bzr: warning: some compiled extensions could not be loaded; "
 
987
        "see <https://answers.launchpad.net/bzr/+faq/703>")
 
988
    # we no longer show the specific missing extensions here, because it makes
 
989
    # the message too long and scary - see
 
990
    # https://bugs.launchpad.net/bzr/+bug/430529
 
991
 
 
992
 
850
993
try:
851
994
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
852
 
except ImportError:
 
995
except ImportError, e:
 
996
    failed_to_load_extension(e)
853
997
    from bzrlib._chunks_to_lines_py import chunks_to_lines
854
998
 
855
999
 
893
1037
        shutil.copyfile(src, dest)
894
1038
 
895
1039
 
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.
901
1040
def delete_any(path):
902
 
    """Delete a file or directory."""
 
1041
    """Delete a file, symlink or directory.  
 
1042
    
 
1043
    Will delete even if readonly.
 
1044
    """
 
1045
    try:
 
1046
       _delete_file_or_dir(path)
 
1047
    except (OSError, IOError), e:
 
1048
        if e.errno in (errno.EPERM, errno.EACCES):
 
1049
            # make writable and try again
 
1050
            try:
 
1051
                make_writable(path)
 
1052
            except (OSError, IOError):
 
1053
                pass
 
1054
            _delete_file_or_dir(path)
 
1055
        else:
 
1056
            raise
 
1057
 
 
1058
 
 
1059
def _delete_file_or_dir(path):
 
1060
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
1061
    # Forgiveness than Permission (EAFP) because:
 
1062
    # - root can damage a solaris file system by using unlink,
 
1063
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
1064
    #   EACCES, OSX: EPERM) when invoked on a directory.
903
1065
    if isdir(path): # Takes care of symlinks
904
1066
        os.rmdir(path)
905
1067
    else:
925
1087
            and sys.platform not in ('cygwin', 'win32'))
926
1088
 
927
1089
 
 
1090
def readlink(abspath):
 
1091
    """Return a string representing the path to which the symbolic link points.
 
1092
 
 
1093
    :param abspath: The link absolute unicode path.
 
1094
 
 
1095
    This his guaranteed to return the symbolic link in unicode in all python
 
1096
    versions.
 
1097
    """
 
1098
    link = abspath.encode(_fs_enc)
 
1099
    target = os.readlink(link)
 
1100
    target = target.decode(_fs_enc)
 
1101
    return target
 
1102
 
 
1103
 
928
1104
def contains_whitespace(s):
929
1105
    """True if there are any whitespace characters in s."""
930
1106
    # string.whitespace can include '\xa0' in certain locales, because it is
974
1150
 
975
1151
    s = []
976
1152
    head = rp
977
 
    while len(head) >= len(base):
 
1153
    while True:
 
1154
        if len(head) <= len(base) and head != base:
 
1155
            raise errors.PathNotChild(rp, base)
978
1156
        if head == base:
979
1157
            break
980
 
        head, tail = os.path.split(head)
 
1158
        head, tail = split(head)
981
1159
        if tail:
982
 
            s.insert(0, tail)
983
 
    else:
984
 
        raise errors.PathNotChild(rp, base)
 
1160
            s.append(tail)
985
1161
 
986
1162
    if s:
987
 
        return pathjoin(*s)
 
1163
        return pathjoin(*reversed(s))
988
1164
    else:
989
1165
        return ''
990
1166
 
1017
1193
    bit_iter = iter(rel.split('/'))
1018
1194
    for bit in bit_iter:
1019
1195
        lbit = bit.lower()
1020
 
        for look in _listdir(current):
 
1196
        try:
 
1197
            next_entries = _listdir(current)
 
1198
        except OSError: # enoent, eperm, etc
 
1199
            # We can't find this in the filesystem, so just append the
 
1200
            # remaining bits.
 
1201
            current = pathjoin(current, bit, *list(bit_iter))
 
1202
            break
 
1203
        for look in next_entries:
1021
1204
            if lbit == look.lower():
1022
1205
                current = pathjoin(current, look)
1023
1206
                break
1027
1210
            # the target of a move, for example).
1028
1211
            current = pathjoin(current, bit, *list(bit_iter))
1029
1212
            break
1030
 
    return current[len(abs_base)+1:]
 
1213
    return current[len(abs_base):].lstrip('/')
1031
1214
 
1032
1215
# XXX - TODO - we need better detection/integration of case-insensitive
1033
 
# file-systems; Linux often sees FAT32 devices, for example, so could
1034
 
# probably benefit from the same basic support there.  For now though, only
1035
 
# Windows gets that support, and it gets it for *all* file-systems!
1036
 
if sys.platform == "win32":
 
1216
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1217
# filesystems), for example, so could probably benefit from the same basic
 
1218
# support there.  For now though, only Windows and OSX get that support, and
 
1219
# they get it for *all* file-systems!
 
1220
if sys.platform in ('win32', 'darwin'):
1037
1221
    canonical_relpath = _cicp_canonical_relpath
1038
1222
else:
1039
1223
    canonical_relpath = relpath
1051
1235
    """Coerce unicode_or_utf8_string into unicode.
1052
1236
 
1053
1237
    If it is unicode, it is returned.
1054
 
    Otherwise it is decoded from utf-8. If a decoding error
1055
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped
1056
 
    as a BzrBadParameter exception.
 
1238
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1239
    wrapped in a BzrBadParameterNotUnicode exception.
1057
1240
    """
1058
1241
    if isinstance(unicode_or_utf8_string, unicode):
1059
1242
        return unicode_or_utf8_string
1172
1355
    normalized_filename = _inaccessible_normalized_filename
1173
1356
 
1174
1357
 
 
1358
def set_signal_handler(signum, handler, restart_syscall=True):
 
1359
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
 
1360
    on platforms that support that.
 
1361
 
 
1362
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
 
1363
        automatically restart (by calling `signal.siginterrupt(signum,
 
1364
        False)`).  May be ignored if the feature is not available on this
 
1365
        platform or Python version.
 
1366
    """
 
1367
    try:
 
1368
        import signal
 
1369
        siginterrupt = signal.siginterrupt
 
1370
    except ImportError:
 
1371
        # This python implementation doesn't provide signal support, hence no
 
1372
        # handler exists
 
1373
        return None
 
1374
    except AttributeError:
 
1375
        # siginterrupt doesn't exist on this platform, or for this version
 
1376
        # of Python.
 
1377
        siginterrupt = lambda signum, flag: None
 
1378
    if restart_syscall:
 
1379
        def sig_handler(*args):
 
1380
            # Python resets the siginterrupt flag when a signal is
 
1381
            # received.  <http://bugs.python.org/issue8354>
 
1382
            # As a workaround for some cases, set it back the way we want it.
 
1383
            siginterrupt(signum, False)
 
1384
            # Now run the handler function passed to set_signal_handler.
 
1385
            handler(*args)
 
1386
    else:
 
1387
        sig_handler = handler
 
1388
    old_handler = signal.signal(signum, sig_handler)
 
1389
    if restart_syscall:
 
1390
        siginterrupt(signum, False)
 
1391
    return old_handler
 
1392
 
 
1393
 
 
1394
default_terminal_width = 80
 
1395
"""The default terminal width for ttys.
 
1396
 
 
1397
This is defined so that higher levels can share a common fallback value when
 
1398
terminal_width() returns None.
 
1399
"""
 
1400
 
 
1401
 
1175
1402
def terminal_width():
1176
 
    """Return estimated terminal width."""
1177
 
    if sys.platform == 'win32':
1178
 
        return win32utils.get_console_size()[0]
1179
 
    width = 0
 
1403
    """Return terminal width.
 
1404
 
 
1405
    None is returned if the width can't established precisely.
 
1406
 
 
1407
    The rules are:
 
1408
    - if BZR_COLUMNS is set, returns its value
 
1409
    - if there is no controlling terminal, returns None
 
1410
    - if COLUMNS is set, returns its value,
 
1411
 
 
1412
    From there, we need to query the OS to get the size of the controlling
 
1413
    terminal.
 
1414
 
 
1415
    Unices:
 
1416
    - get termios.TIOCGWINSZ
 
1417
    - if an error occurs or a negative value is obtained, returns None
 
1418
 
 
1419
    Windows:
 
1420
    
 
1421
    - win32utils.get_console_size() decides,
 
1422
    - returns None on error (provided default value)
 
1423
    """
 
1424
 
 
1425
    # If BZR_COLUMNS is set, take it, user is always right
 
1426
    try:
 
1427
        return int(os.environ['BZR_COLUMNS'])
 
1428
    except (KeyError, ValueError):
 
1429
        pass
 
1430
 
 
1431
    isatty = getattr(sys.stdout, 'isatty', None)
 
1432
    if  isatty is None or not isatty():
 
1433
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
 
1434
        return None
 
1435
 
 
1436
    # If COLUMNS is set, take it, the terminal knows better (even inside a
 
1437
    # given terminal, the application can decide to set COLUMNS to a lower
 
1438
    # value (splitted screen) or a bigger value (scroll bars))
 
1439
    try:
 
1440
        return int(os.environ['COLUMNS'])
 
1441
    except (KeyError, ValueError):
 
1442
        pass
 
1443
 
 
1444
    width, height = _terminal_size(None, None)
 
1445
    if width <= 0:
 
1446
        # Consider invalid values as meaning no width
 
1447
        return None
 
1448
 
 
1449
    return width
 
1450
 
 
1451
 
 
1452
def _win32_terminal_size(width, height):
 
1453
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
 
1454
    return width, height
 
1455
 
 
1456
 
 
1457
def _ioctl_terminal_size(width, height):
1180
1458
    try:
1181
1459
        import struct, fcntl, termios
1182
1460
        s = struct.pack('HHHH', 0, 0, 0, 0)
1183
1461
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1184
 
        width = struct.unpack('HHHH', x)[1]
1185
 
    except IOError:
 
1462
        height, width = struct.unpack('HHHH', x)[0:2]
 
1463
    except (IOError, AttributeError):
1186
1464
        pass
1187
 
    if width <= 0:
 
1465
    return width, height
 
1466
 
 
1467
_terminal_size = None
 
1468
"""Returns the terminal size as (width, height).
 
1469
 
 
1470
:param width: Default value for width.
 
1471
:param height: Default value for height.
 
1472
 
 
1473
This is defined specifically for each OS and query the size of the controlling
 
1474
terminal. If any error occurs, the provided default values should be returned.
 
1475
"""
 
1476
if sys.platform == 'win32':
 
1477
    _terminal_size = _win32_terminal_size
 
1478
else:
 
1479
    _terminal_size = _ioctl_terminal_size
 
1480
 
 
1481
 
 
1482
def _terminal_size_changed(signum, frame):
 
1483
    """Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
 
1484
    width, height = _terminal_size(None, None)
 
1485
    if width is not None:
 
1486
        os.environ['COLUMNS'] = str(width)
 
1487
 
 
1488
 
 
1489
_registered_sigwinch = False
 
1490
def watch_sigwinch():
 
1491
    """Register for SIGWINCH, once and only once.
 
1492
 
 
1493
    Do nothing if the signal module is not available.
 
1494
    """
 
1495
    global _registered_sigwinch
 
1496
    if not _registered_sigwinch:
1188
1497
        try:
1189
 
            width = int(os.environ['COLUMNS'])
1190
 
        except:
 
1498
            import signal
 
1499
            if getattr(signal, "SIGWINCH", None) is not None:
 
1500
                set_signal_handler(signal.SIGWINCH, _terminal_size_changed)
 
1501
        except ImportError:
 
1502
            # python doesn't provide signal support, nothing we can do about it
1191
1503
            pass
1192
 
    if width <= 0:
1193
 
        width = 80
1194
 
 
1195
 
    return width
 
1504
        _registered_sigwinch = True
1196
1505
 
1197
1506
 
1198
1507
def supports_executable():
1392
1701
            #       for win98 anyway.
1393
1702
            try:
1394
1703
                from bzrlib._walkdirs_win32 import Win32ReadDir
1395
 
            except ImportError:
1396
 
                _selected_dir_reader = UnicodeDirReader()
1397
 
            else:
1398
1704
                _selected_dir_reader = Win32ReadDir()
1399
 
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1705
            except ImportError:
 
1706
                pass
 
1707
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1400
1708
            # ANSI_X3.4-1968 is a form of ASCII
1401
 
            _selected_dir_reader = UnicodeDirReader()
1402
 
        else:
1403
1709
            try:
1404
1710
                from bzrlib._readdir_pyx import UTF8DirReader
1405
 
            except ImportError:
1406
 
                # No optimised code path
1407
 
                _selected_dir_reader = UnicodeDirReader()
1408
 
            else:
1409
1711
                _selected_dir_reader = UTF8DirReader()
 
1712
            except ImportError, e:
 
1713
                failed_to_load_extension(e)
 
1714
                pass
 
1715
 
 
1716
    if _selected_dir_reader is None:
 
1717
        # Fallback to the python version
 
1718
        _selected_dir_reader = UnicodeDirReader()
 
1719
 
1410
1720
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1411
1721
    # But we don't actually uses 1-3 in pending, so set them to None
1412
1722
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1517
1827
            real_handlers[kind](abspath, relpath)
1518
1828
 
1519
1829
 
 
1830
def copy_ownership_from_path(dst, src=None):
 
1831
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1832
 
 
1833
    If src is None, the containing directory is used as source. If chown
 
1834
    fails, the error is ignored and a warning is printed.
 
1835
    """
 
1836
    chown = getattr(os, 'chown', None)
 
1837
    if chown is None:
 
1838
        return
 
1839
 
 
1840
    if src == None:
 
1841
        src = os.path.dirname(dst)
 
1842
        if src == '':
 
1843
            src = '.'
 
1844
 
 
1845
    try:
 
1846
        s = os.stat(src)
 
1847
        chown(dst, s.st_uid, s.st_gid)
 
1848
    except OSError, e:
 
1849
        trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
 
1850
 
 
1851
 
1520
1852
def path_prefix_key(path):
1521
1853
    """Generate a prefix-order path key for path.
1522
1854
 
1622
1954
        return socket.gethostname().decode(get_user_encoding())
1623
1955
 
1624
1956
 
1625
 
def recv_all(socket, bytes):
 
1957
# We must not read/write any more than 64k at a time from/to a socket so we
 
1958
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
1959
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
1960
# data at once.
 
1961
MAX_SOCKET_CHUNK = 64 * 1024
 
1962
 
 
1963
def read_bytes_from_socket(sock, report_activity=None,
 
1964
        max_read_size=MAX_SOCKET_CHUNK):
 
1965
    """Read up to max_read_size of bytes from sock and notify of progress.
 
1966
 
 
1967
    Translates "Connection reset by peer" into file-like EOF (return an
 
1968
    empty string rather than raise an error), and repeats the recv if
 
1969
    interrupted by a signal.
 
1970
    """
 
1971
    while 1:
 
1972
        try:
 
1973
            bytes = sock.recv(max_read_size)
 
1974
        except socket.error, e:
 
1975
            eno = e.args[0]
 
1976
            if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
 
1977
                # The connection was closed by the other side.  Callers expect
 
1978
                # an empty string to signal end-of-stream.
 
1979
                return ""
 
1980
            elif eno == errno.EINTR:
 
1981
                # Retry the interrupted recv.
 
1982
                continue
 
1983
            raise
 
1984
        else:
 
1985
            if report_activity is not None:
 
1986
                report_activity(len(bytes), 'read')
 
1987
            return bytes
 
1988
 
 
1989
 
 
1990
def recv_all(socket, count):
1626
1991
    """Receive an exact number of bytes.
1627
1992
 
1628
1993
    Regular Socket.recv() may return less than the requested number of bytes,
1629
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1994
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1630
1995
    on all platforms, but this should work everywhere.  This will return
1631
1996
    less than the requested amount if the remote end closes.
1632
1997
 
1633
1998
    This isn't optimized and is intended mostly for use in testing.
1634
1999
    """
1635
2000
    b = ''
1636
 
    while len(b) < bytes:
1637
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
2001
    while len(b) < count:
 
2002
        new = read_bytes_from_socket(socket, None, count - len(b))
1638
2003
        if new == '':
1639
2004
            break # eof
1640
2005
        b += new
1641
2006
    return b
1642
2007
 
1643
2008
 
1644
 
def send_all(socket, bytes, report_activity=None):
 
2009
def send_all(sock, bytes, report_activity=None):
1645
2010
    """Send all bytes on a socket.
1646
 
 
1647
 
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1648
 
    implementation sends no more than 64k at a time, which avoids this problem.
1649
 
 
 
2011
 
 
2012
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2013
    some platforms, and catches EINTR which may be thrown if the send is
 
2014
    interrupted by a signal.
 
2015
 
 
2016
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2017
    and provides activity reporting.
 
2018
 
1650
2019
    :param report_activity: Call this as bytes are read, see
1651
2020
        Transport._report_activity
1652
2021
    """
1653
 
    chunk_size = 2**16
1654
 
    for pos in xrange(0, len(bytes), chunk_size):
1655
 
        block = bytes[pos:pos+chunk_size]
1656
 
        if report_activity is not None:
1657
 
            report_activity(len(block), 'write')
1658
 
        until_no_eintr(socket.sendall, block)
 
2022
    sent_total = 0
 
2023
    byte_count = len(bytes)
 
2024
    while sent_total < byte_count:
 
2025
        try:
 
2026
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2027
        except socket.error, e:
 
2028
            if e.args[0] != errno.EINTR:
 
2029
                raise
 
2030
        else:
 
2031
            sent_total += sent
 
2032
            report_activity(sent, 'write')
1659
2033
 
1660
2034
 
1661
2035
def dereference_path(path):
1712
2086
        try:
1713
2087
            from bzrlib._readdir_pyx import UTF8DirReader
1714
2088
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1715
 
        except ImportError:
 
2089
        except ImportError, e:
 
2090
            # This is one time where we won't warn that an extension failed to
 
2091
            # load. The extension is never available on Windows anyway.
1716
2092
            from bzrlib._readdir_py import (
1717
2093
                _kind_from_mode as file_kind_from_stat_mode
1718
2094
                )
1730
2106
 
1731
2107
 
1732
2108
def until_no_eintr(f, *a, **kw):
1733
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
2109
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2110
    
 
2111
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2112
    if EINTR does occur.  This is typically only true for low-level operations
 
2113
    like os.read.  If in any doubt, don't use this.
 
2114
 
 
2115
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2116
    probably code in the Python standard library and other dependencies that
 
2117
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2118
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2119
    directly controls, but it is not a complete solution.
 
2120
    """
1734
2121
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1735
2122
    while True:
1736
2123
        try:
1740
2127
                continue
1741
2128
            raise
1742
2129
 
 
2130
 
1743
2131
def re_compile_checked(re_string, flags=0, where=""):
1744
2132
    """Return a compiled re, or raise a sensible error.
1745
 
    
 
2133
 
1746
2134
    This should only be used when compiling user-supplied REs.
1747
2135
 
1748
2136
    :param re_string: Text form of regular expression.
1749
2137
    :param flags: eg re.IGNORECASE
1750
 
    :param where: Message explaining to the user the context where 
 
2138
    :param where: Message explaining to the user the context where
1751
2139
        it occurred, eg 'log search filter'.
1752
2140
    """
1753
2141
    # from https://bugs.launchpad.net/bzr/+bug/251352
1779
2167
        finally:
1780
2168
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1781
2169
        return ch
 
2170
 
 
2171
 
 
2172
if sys.platform == 'linux2':
 
2173
    def _local_concurrency():
 
2174
        concurrency = None
 
2175
        prefix = 'processor'
 
2176
        for line in file('/proc/cpuinfo', 'rb'):
 
2177
            if line.startswith(prefix):
 
2178
                concurrency = int(line[line.find(':')+1:]) + 1
 
2179
        return concurrency
 
2180
elif sys.platform == 'darwin':
 
2181
    def _local_concurrency():
 
2182
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
 
2183
                                stdout=subprocess.PIPE).communicate()[0]
 
2184
elif sys.platform[0:7] == 'freebsd':
 
2185
    def _local_concurrency():
 
2186
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
 
2187
                                stdout=subprocess.PIPE).communicate()[0]
 
2188
elif sys.platform == 'sunos5':
 
2189
    def _local_concurrency():
 
2190
        return subprocess.Popen(['psrinfo', '-p',],
 
2191
                                stdout=subprocess.PIPE).communicate()[0]
 
2192
elif sys.platform == "win32":
 
2193
    def _local_concurrency():
 
2194
        # This appears to return the number of cores.
 
2195
        return os.environ.get('NUMBER_OF_PROCESSORS')
 
2196
else:
 
2197
    def _local_concurrency():
 
2198
        # Who knows ?
 
2199
        return None
 
2200
 
 
2201
 
 
2202
_cached_local_concurrency = None
 
2203
 
 
2204
def local_concurrency(use_cache=True):
 
2205
    """Return how many processes can be run concurrently.
 
2206
 
 
2207
    Rely on platform specific implementations and default to 1 (one) if
 
2208
    anything goes wrong.
 
2209
    """
 
2210
    global _cached_local_concurrency
 
2211
 
 
2212
    if _cached_local_concurrency is not None and use_cache:
 
2213
        return _cached_local_concurrency
 
2214
 
 
2215
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
 
2216
    if concurrency is None:
 
2217
        try:
 
2218
            concurrency = _local_concurrency()
 
2219
        except (OSError, IOError):
 
2220
            pass
 
2221
    try:
 
2222
        concurrency = int(concurrency)
 
2223
    except (TypeError, ValueError):
 
2224
        concurrency = 1
 
2225
    if use_cache:
 
2226
        _cached_concurrency = concurrency
 
2227
    return concurrency
 
2228
 
 
2229
 
 
2230
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
 
2231
    """A stream writer that doesn't decode str arguments."""
 
2232
 
 
2233
    def __init__(self, encode, stream, errors='strict'):
 
2234
        codecs.StreamWriter.__init__(self, stream, errors)
 
2235
        self.encode = encode
 
2236
 
 
2237
    def write(self, object):
 
2238
        if type(object) is str:
 
2239
            self.stream.write(object)
 
2240
        else:
 
2241
            data, _ = self.encode(object, self.errors)
 
2242
            self.stream.write(data)
 
2243
 
 
2244
if sys.platform == 'win32':
 
2245
    def open_file(filename, mode='r', bufsize=-1):
 
2246
        """This function is used to override the ``open`` builtin.
 
2247
        
 
2248
        But it uses O_NOINHERIT flag so the file handle is not inherited by
 
2249
        child processes.  Deleting or renaming a closed file opened with this
 
2250
        function is not blocking child processes.
 
2251
        """
 
2252
        writing = 'w' in mode
 
2253
        appending = 'a' in mode
 
2254
        updating = '+' in mode
 
2255
        binary = 'b' in mode
 
2256
 
 
2257
        flags = O_NOINHERIT
 
2258
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
 
2259
        # for flags for each modes.
 
2260
        if binary:
 
2261
            flags |= O_BINARY
 
2262
        else:
 
2263
            flags |= O_TEXT
 
2264
 
 
2265
        if writing:
 
2266
            if updating:
 
2267
                flags |= os.O_RDWR
 
2268
            else:
 
2269
                flags |= os.O_WRONLY
 
2270
            flags |= os.O_CREAT | os.O_TRUNC
 
2271
        elif appending:
 
2272
            if updating:
 
2273
                flags |= os.O_RDWR
 
2274
            else:
 
2275
                flags |= os.O_WRONLY
 
2276
            flags |= os.O_CREAT | os.O_APPEND
 
2277
        else: #reading
 
2278
            if updating:
 
2279
                flags |= os.O_RDWR
 
2280
            else:
 
2281
                flags |= os.O_RDONLY
 
2282
 
 
2283
        return os.fdopen(os.open(filename, flags), mode, bufsize)
 
2284
else:
 
2285
    open_file = open