72
69
from bzrlib import symbol_versioning
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
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
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
193
:param unlink_func: A way to delete the target file if the full rename succeeds
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)
220
202
# Rename the file out of the way, but keep track if it didn't exist
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
236
if not (file_existed and e.errno in (None, errno.ENOENT)):
263
240
# If the file used to exist, rename it back into place
732
705
date_str = time.strftime(date_fmt, tt)
733
706
return date_str + offset_str
736
# Cache of formatted offset strings
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.
744
This routine may be faster then format_date.
746
:param t: Seconds since the epoch.
747
:param offset: Timezone offset in seconds east of utc.
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
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
781
727
def _format_date(t, offset, timezone, date_fmt, show_offset):
782
728
if timezone == 'utc':
783
729
tt = time.gmtime(t)
937
_extension_load_failures = []
940
def failed_to_load_extension(exception):
941
"""Handle failing to load a binary extension.
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::
948
>>> import bzrlib._fictional_extension_pyx
949
>>> except ImportError, e:
950
>>> bzrlib.osutils.failed_to_load_extension(e)
951
>>> import bzrlib._fictional_extension_py
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 --
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
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)
968
def report_extension_load_failures():
969
if not _extension_load_failures:
971
from bzrlib.config import GlobalConfig
972
if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
974
# the warnings framework should by default show this only once
975
from bzrlib.trace import 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
985
884
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
986
except ImportError, e:
987
failed_to_load_extension(e)
988
886
from bzrlib._chunks_to_lines_py import chunks_to_lines
1028
926
shutil.copyfile(src, dest)
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.
1034
Will delete even if readonly.
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
1043
except (OSError, IOError):
1045
_delete_file_or_dir(path)
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
1346
1219
normalized_filename = _inaccessible_normalized_filename
1349
default_terminal_width = 80
1350
"""The default terminal width for ttys.
1352
This is defined so that higher levels can share a common fallback value when
1353
terminal_width() returns None.
1357
1222
def terminal_width():
1358
"""Return terminal width.
1360
None is returned if the width can't established precisely.
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,
1367
From there, we need to query the OS to get the size of the controlling
1371
- get termios.TIOCGWINSZ
1372
- if an error occurs or a negative value is obtained, returns None
1376
- win32utils.get_console_size() decides,
1377
- returns None on error (provided default value)
1380
# If BZR_COLUMNS is set, take it, user is always right
1382
return int(os.environ['BZR_COLUMNS'])
1383
except (KeyError, ValueError):
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.
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))
1395
return int(os.environ['COLUMNS'])
1396
except (KeyError, ValueError):
1399
width, height = _terminal_size(None, None)
1401
# Consider invalid values as meaning no width
1407
def _win32_terminal_size(width, height):
1408
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1409
return width, height
1412
def _ioctl_terminal_size(width, height):
1223
"""Return estimated terminal width."""
1224
if sys.platform == 'win32':
1225
return win32utils.get_console_size()[0]
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]
1420
return width, height
1422
_terminal_size = None
1423
"""Returns the terminal size as (width, height).
1425
:param width: Default value for width.
1426
:param height: Default value for height.
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.
1431
if sys.platform == 'win32':
1432
_terminal_size = _win32_terminal_size
1434
_terminal_size = _ioctl_terminal_size
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)
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
1448
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1236
width = int(os.environ['COLUMNS'])
1451
1245
def supports_executable():
2036
1827
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2040
if sys.platform == 'linux2':
2041
def _local_concurrency():
2043
prefix = 'processor'
2044
for line in file('/proc/cpuinfo', 'rb'):
2045
if line.startswith(prefix):
2046
concurrency = int(line[line.find(':')+1:]) + 1
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')
2065
def _local_concurrency():
2070
_cached_local_concurrency = None
2072
def local_concurrency(use_cache=True):
2073
"""Return how many processes can be run concurrently.
2075
Rely on platform specific implementations and default to 1 (one) if
2076
anything goes wrong.
2078
global _cached_local_concurrency
2080
if _cached_local_concurrency is not None and use_cache:
2081
return _cached_local_concurrency
2083
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2084
if concurrency is None:
2086
concurrency = _local_concurrency()
2087
except (OSError, IOError):
2090
concurrency = int(concurrency)
2091
except (TypeError, ValueError):
2094
_cached_concurrency = concurrency
2098
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2099
"""A stream writer that doesn't decode str arguments."""
2101
def __init__(self, encode, stream, errors='strict'):
2102
codecs.StreamWriter.__init__(self, stream, errors)
2103
self.encode = encode
2105
def write(self, object):
2106
if type(object) is str:
2107
self.stream.write(object)
2109
data, _ = self.encode(object, self.errors)
2110
self.stream.write(data)