~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Sidnei da Silva
  • Date: 2009-05-29 14:19:29 UTC
  • mto: (4531.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4532.
  • Revision ID: sidnei.da.silva@canonical.com-20090529141929-3heywbvj36po72a5
- Add initial config

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
179
167
    try:
180
168
        return _kind_marker_map[kind]
181
169
    except KeyError:
182
 
        # Slightly faster than using .get(, '') when the common case is that
183
 
        # kind will be found
184
 
        return ''
 
170
        raise errors.BzrError('invalid file kind %r' % kind)
185
171
 
186
172
 
187
173
lexists = getattr(os.path, 'lexists', None)
204
190
    :param old: The old path, to rename from
205
191
    :param new: The new path, to rename to
206
192
    :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
 
193
    :param unlink_func: A way to delete the target file if the full rename succeeds
209
194
    """
 
195
 
210
196
    # sftp rename doesn't allow overwriting, so play tricks:
211
197
    base = os.path.basename(new)
212
198
    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))
 
199
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
218
200
    tmp_name = pathjoin(dirname, tmp_name)
219
201
 
220
202
    # Rename the file out of the way, but keep track if it didn't exist
240
222
    else:
241
223
        file_existed = True
242
224
 
243
 
    failure_exc = None
244
225
    success = False
245
226
    try:
246
227
        try:
252
233
            # source and target may be aliases of each other (e.g. on a
253
234
            # case-insensitive filesystem), so we may have accidentally renamed
254
235
            # 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
 
236
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
237
                raise
261
238
    finally:
262
239
        if file_existed:
263
240
            # If the file used to exist, rename it back into place
266
243
                unlink_func(tmp_name)
267
244
            else:
268
245
                rename_func(tmp_name, new)
269
 
    if failure_exc is not None:
270
 
        raise failure_exc[0], failure_exc[1], failure_exc[2]
271
246
 
272
247
 
273
248
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
711
686
    return offset.days * 86400 + offset.seconds
712
687
 
713
688
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
689
 
717
690
def format_date(t, offset=0, timezone='original', date_fmt=None,
718
691
                show_offset=True):
732
705
    date_str = time.strftime(date_fmt, tt)
733
706
    return date_str + offset_str
734
707
 
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
708
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
762
709
                      show_offset=True):
763
710
    """Return an unicode date string formatted according to the current locale.
774
721
               _format_date(t, offset, timezone, date_fmt, show_offset)
775
722
    date_str = time.strftime(date_fmt, tt)
776
723
    if not isinstance(date_str, unicode):
777
 
        date_str = date_str.decode(get_user_encoding(), 'replace')
 
724
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
778
725
    return date_str + offset_str
779
726
 
780
 
 
781
727
def _format_date(t, offset, timezone, date_fmt, show_offset):
782
728
    if timezone == 'utc':
783
729
        tt = time.gmtime(t)
934
880
    return parents
935
881
 
936
882
 
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
883
try:
985
884
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
986
 
except ImportError, e:
987
 
    failed_to_load_extension(e)
 
885
except ImportError:
988
886
    from bzrlib._chunks_to_lines_py import chunks_to_lines
989
887
 
990
888
 
1028
926
        shutil.copyfile(src, dest)
1029
927
 
1030
928
 
 
929
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
930
# Forgiveness than Permission (EAFP) because:
 
931
# - root can damage a solaris file system by using unlink,
 
932
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
933
#   EACCES, OSX: EPERM) when invoked on a directory.
1031
934
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.
 
935
    """Delete a file or directory."""
1056
936
    if isdir(path): # Takes care of symlinks
1057
937
        os.rmdir(path)
1058
938
    else:
1141
1021
 
1142
1022
    s = []
1143
1023
    head = rp
1144
 
    while True:
1145
 
        if len(head) <= len(base) and head != base:
1146
 
            raise errors.PathNotChild(rp, base)
 
1024
    while len(head) >= len(base):
1147
1025
        if head == base:
1148
1026
            break
1149
 
        head, tail = split(head)
 
1027
        head, tail = os.path.split(head)
1150
1028
        if tail:
1151
 
            s.append(tail)
 
1029
            s.insert(0, tail)
 
1030
    else:
 
1031
        raise errors.PathNotChild(rp, base)
1152
1032
 
1153
1033
    if s:
1154
 
        return pathjoin(*reversed(s))
 
1034
        return pathjoin(*s)
1155
1035
    else:
1156
1036
        return ''
1157
1037
 
1184
1064
    bit_iter = iter(rel.split('/'))
1185
1065
    for bit in bit_iter:
1186
1066
        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:
 
1067
        for look in _listdir(current):
1195
1068
            if lbit == look.lower():
1196
1069
                current = pathjoin(current, look)
1197
1070
                break
1201
1074
            # the target of a move, for example).
1202
1075
            current = pathjoin(current, bit, *list(bit_iter))
1203
1076
            break
1204
 
    return current[len(abs_base):].lstrip('/')
 
1077
    return current[len(abs_base)+1:]
1205
1078
 
1206
1079
# XXX - TODO - we need better detection/integration of case-insensitive
1207
1080
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1346
1219
    normalized_filename = _inaccessible_normalized_filename
1347
1220
 
1348
1221
 
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
1222
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):
 
1223
    """Return estimated terminal width."""
 
1224
    if sys.platform == 'win32':
 
1225
        return win32utils.get_console_size()[0]
 
1226
    width = 0
1413
1227
    try:
1414
1228
        import struct, fcntl, termios
1415
1229
        s = struct.pack('HHHH', 0, 0, 0, 0)
1416
1230
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1417
 
        height, width = struct.unpack('HHHH', x)[0:2]
1418
 
    except (IOError, AttributeError):
 
1231
        width = struct.unpack('HHHH', x)[1]
 
1232
    except IOError:
1419
1233
        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)
 
1234
    if width <= 0:
 
1235
        try:
 
1236
            width = int(os.environ['COLUMNS'])
 
1237
        except:
 
1238
            pass
 
1239
    if width <= 0:
 
1240
        width = 80
 
1241
 
 
1242
    return width
1449
1243
 
1450
1244
 
1451
1245
def supports_executable():
1653
1447
            try:
1654
1448
                from bzrlib._readdir_pyx import UTF8DirReader
1655
1449
                _selected_dir_reader = UTF8DirReader()
1656
 
            except ImportError, e:
1657
 
                failed_to_load_extension(e)
 
1450
            except ImportError:
1658
1451
                pass
1659
1452
 
1660
1453
    if _selected_dir_reader is None:
1966
1759
        try:
1967
1760
            from bzrlib._readdir_pyx import UTF8DirReader
1968
1761
            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.
 
1762
        except ImportError:
1972
1763
            from bzrlib._readdir_py import (
1973
1764
                _kind_from_mode as file_kind_from_stat_mode
1974
1765
                )
2035
1826
        finally:
2036
1827
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2037
1828
        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)