201
196
def fancy_rename(old, new, rename_func, unlink_func):
202
197
"""A fancy rename, when you don't have atomic rename.
204
199
:param old: The old path, to rename from
205
200
:param new: The new path, to rename to
206
201
:param rename_func: The potentially non-atomic rename function
207
:param unlink_func: A way to delete the target file if the full rename
202
:param unlink_func: A way to delete the target file if the full rename succeeds
210
205
# sftp rename doesn't allow overwriting, so play tricks:
211
207
base = os.path.basename(new)
212
208
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))
209
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
218
210
tmp_name = pathjoin(dirname, tmp_name)
220
212
# Rename the file out of the way, but keep track if it didn't exist
723
653
:param timezone: How to display the time: 'utc', 'original' for the
724
654
timezone specified by offset, or 'local' for the process's current
726
:param date_fmt: strftime format.
727
:param show_offset: Whether to append the timezone.
729
(date_fmt, tt, offset_str) = \
730
_format_date(t, offset, timezone, date_fmt, show_offset)
731
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
732
date_str = time.strftime(date_fmt, tt)
733
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
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
763
"""Return an unicode date string formatted according to the current locale.
765
:param t: Seconds since the epoch.
766
:param offset: Timezone offset in seconds east of utc.
767
:param timezone: How to display the time: 'utc', 'original' for the
768
timezone specified by offset, or 'local' for the process's current
770
:param date_fmt: strftime format.
771
:param show_offset: Whether to append the timezone.
773
(date_fmt, tt, offset_str) = \
774
_format_date(t, offset, timezone, date_fmt, show_offset)
775
date_str = time.strftime(date_fmt, tt)
776
if not isinstance(date_str, unicode):
777
date_str = date_str.decode(get_user_encoding(), 'replace')
778
return date_str + offset_str
781
def _format_date(t, offset, timezone, date_fmt, show_offset):
656
:param show_offset: Whether to append the timezone.
657
:param date_fmt: strftime format.
782
659
if timezone == 'utc':
783
660
tt = time.gmtime(t)
921
799
return pathjoin(*p)
924
def parent_directories(filename):
925
"""Return the list of parent directories, deepest first.
927
For example, parent_directories("a/b/c") -> ["a/b", "a"].
930
parts = splitpath(dirname(filename))
932
parents.append(joinpath(parts))
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
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
986
except ImportError, e:
987
failed_to_load_extension(e)
988
from bzrlib._chunks_to_lines_py import chunks_to_lines
991
802
def split_lines(s):
992
803
"""Split s into lines, but without removing the newline characters."""
993
# Trivially convert a fulltext into a 'chunked' representation, and let
994
# chunks_to_lines do the heavy lifting.
995
if isinstance(s, str):
996
# chunks_to_lines only supports 8-bit strings
997
return chunks_to_lines([s])
999
return _split_lines(s)
1002
def _split_lines(s):
1003
"""Split s into lines, but without removing the newline characters.
1005
This supports Unicode or plain string objects.
1007
804
lines = s.split('\n')
1008
805
result = [line + '\n' for line in lines[:-1]]
1028
825
shutil.copyfile(src, dest)
828
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
829
# Forgiveness than Permission (EAFP) because:
830
# - root can damage a solaris file system by using unlink,
831
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
832
# EACCES, OSX: EPERM) when invoked on a directory.
1031
833
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.
834
"""Delete a file or directory."""
1056
835
if isdir(path): # Takes care of symlinks
1145
if len(head) <= len(base) and head != base:
1146
raise errors.PathNotChild(rp, base)
909
while len(head) >= len(base):
1147
910
if head == base:
1149
head, tail = split(head)
912
head, tail = os.path.split(head)
916
raise errors.PathNotChild(rp, base)
1154
return pathjoin(*reversed(s))
1159
def _cicp_canonical_relpath(base, path):
1160
"""Return the canonical path relative to base.
1162
Like relpath, but on case-insensitive-case-preserving file-systems, this
1163
will return the relpath as stored on the file-system rather than in the
1164
case specified in the input string, for all existing portions of the path.
1166
This will cause O(N) behaviour if called for every path in a tree; if you
1167
have a number of paths to convert, you should use canonical_relpaths().
1169
# TODO: it should be possible to optimize this for Windows by using the
1170
# win32 API FindFiles function to look for the specified name - but using
1171
# os.listdir() still gives us the correct, platform agnostic semantics in
1174
rel = relpath(base, path)
1175
# '.' will have been turned into ''
1179
abs_base = abspath(base)
1181
_listdir = os.listdir
1183
# use an explicit iterator so we can easily consume the rest on early exit.
1184
bit_iter = iter(rel.split('/'))
1185
for bit in bit_iter:
1188
next_entries = _listdir(current)
1189
except OSError: # enoent, eperm, etc
1190
# We can't find this in the filesystem, so just append the
1192
current = pathjoin(current, bit, *list(bit_iter))
1194
for look in next_entries:
1195
if lbit == look.lower():
1196
current = pathjoin(current, look)
1199
# got to the end, nothing matched, so we just return the
1200
# non-existing bits as they were specified (the filename may be
1201
# the target of a move, for example).
1202
current = pathjoin(current, bit, *list(bit_iter))
1204
return current[len(abs_base):].lstrip('/')
1206
# XXX - TODO - we need better detection/integration of case-insensitive
1207
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1208
# filesystems), for example, so could probably benefit from the same basic
1209
# support there. For now though, only Windows and OSX get that support, and
1210
# they get it for *all* file-systems!
1211
if sys.platform in ('win32', 'darwin'):
1212
canonical_relpath = _cicp_canonical_relpath
1214
canonical_relpath = relpath
1216
def canonical_relpaths(base, paths):
1217
"""Create an iterable to canonicalize a sequence of relative paths.
1219
The intent is for this implementation to use a cache, vastly speeding
1220
up multiple transformations in the same directory.
1222
# but for now, we haven't optimized...
1223
return [canonical_relpath(base, p) for p in paths]
1225
924
def safe_unicode(unicode_or_utf8_string):
1226
925
"""Coerce unicode_or_utf8_string into unicode.
1228
927
If it is unicode, it is returned.
1229
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1230
wrapped in a BzrBadParameterNotUnicode exception.
928
Otherwise it is decoded from utf-8. If a decoding error
929
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
930
as a BzrBadParameter exception.
1232
932
if isinstance(unicode_or_utf8_string, unicode):
1233
933
return unicode_or_utf8_string
1346
1046
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
1049
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):
1050
"""Return estimated terminal width."""
1051
if sys.platform == 'win32':
1052
return win32utils.get_console_size()[0]
1414
1055
import struct, fcntl, termios
1415
1056
s = struct.pack('HHHH', 0, 0, 0, 0)
1416
1057
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1417
height, width = struct.unpack('HHHH', x)[0:2]
1418
except (IOError, AttributeError):
1058
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)
1063
width = int(os.environ['COLUMNS'])
1451
1072
def supports_executable():
1529
1150
def walkdirs(top, prefix=""):
1530
1151
"""Yield data about all the directories in a tree.
1532
1153
This yields all the data about the contents of a directory at a time.
1533
1154
After each directory has been yielded, if the caller has mutated the list
1534
1155
to exclude some directories, they are then not descended into.
1536
1157
The data yielded is of the form:
1537
1158
((directory-relpath, directory-path-from-top),
1538
1159
[(relpath, basename, kind, lstat, path-from-top), ...]),
1539
1160
- directory-relpath is the relative path of the directory being returned
1540
1161
with respect to top. prefix is prepended to this.
1541
- directory-path-from-root is the path including top for this directory.
1162
- directory-path-from-root is the path including top for this directory.
1542
1163
It is suitable for use with os functions.
1543
1164
- relpath is the relative path within the subtree being walked.
1544
1165
- basename is the basename of the path
1546
1167
present within the tree - but it may be recorded as versioned. See
1547
1168
versioned_kind.
1548
1169
- lstat is the stat data *if* the file was statted.
1549
- planned, not implemented:
1170
- planned, not implemented:
1550
1171
path_from_tree_root is the path from the root of the tree.
1552
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1173
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1553
1174
allows one to walk a subtree but get paths that are relative to a tree
1554
1175
rooted higher up.
1555
1176
:return: an iterator over the dirs.
1557
1178
#TODO there is a bit of a smell where the results of the directory-
1558
# summary in this, and the path from the root, may not agree
1179
# summary in this, and the path from the root, may not agree
1559
1180
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1560
1181
# potentially confusing output. We should make this more robust - but
1561
1182
# not at a speed cost. RBC 20060731
1562
1183
_lstat = os.lstat
1563
1184
_directory = _directory_kind
1564
1185
_listdir = os.listdir
1565
_kind_from_mode = file_kind_from_stat_mode
1186
_kind_from_mode = _formats.get
1566
1187
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1568
1189
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1592
1213
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1595
class DirReader(object):
1596
"""An interface for reading directories."""
1598
def top_prefix_to_starting_dir(self, top, prefix=""):
1599
"""Converts top and prefix to a starting dir entry
1601
:param top: A utf8 path
1602
:param prefix: An optional utf8 path to prefix output relative paths
1604
:return: A tuple starting with prefix, and ending with the native
1607
raise NotImplementedError(self.top_prefix_to_starting_dir)
1609
def read_dir(self, prefix, top):
1610
"""Read a specific dir.
1612
:param prefix: A utf8 prefix to be preprended to the path basenames.
1613
:param top: A natively encoded path to read.
1614
:return: A list of the directories contents. Each item contains:
1615
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1617
raise NotImplementedError(self.read_dir)
1620
_selected_dir_reader = None
1216
_real_walkdirs_utf8 = None
1623
1218
def _walkdirs_utf8(top, prefix=""):
1624
1219
"""Yield data about all the directories in a tree.
1634
1229
path-from-top might be unicode or utf8, but it is the correct path to
1635
1230
pass to os functions to affect the file in question. (such as os.lstat)
1637
global _selected_dir_reader
1638
if _selected_dir_reader is None:
1232
global _real_walkdirs_utf8
1233
if _real_walkdirs_utf8 is None:
1639
1234
fs_encoding = _fs_enc.upper()
1640
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1235
if win32utils.winver == 'Windows NT':
1641
1236
# Win98 doesn't have unicode apis like FindFirstFileW
1642
1237
# TODO: We possibly could support Win98 by falling back to the
1643
1238
# original FindFirstFile, and using TCHAR instead of WCHAR,
1644
1239
# but that gets a bit tricky, and requires custom compiling
1645
1240
# for win98 anyway.
1647
from bzrlib._walkdirs_win32 import Win32ReadDir
1648
_selected_dir_reader = Win32ReadDir()
1242
from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1649
1243
except ImportError:
1651
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1244
_real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1246
_real_walkdirs_utf8 = _walkdirs_utf8_win32_find_file
1247
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1652
1248
# ANSI_X3.4-1968 is a form of ASCII
1654
from bzrlib._readdir_pyx import UTF8DirReader
1655
_selected_dir_reader = UTF8DirReader()
1656
except ImportError, e:
1657
failed_to_load_extension(e)
1660
if _selected_dir_reader is None:
1661
# Fallback to the python version
1662
_selected_dir_reader = UnicodeDirReader()
1249
_real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1251
_real_walkdirs_utf8 = _walkdirs_fs_utf8
1252
return _real_walkdirs_utf8(top, prefix=prefix)
1255
def _walkdirs_fs_utf8(top, prefix=""):
1256
"""See _walkdirs_utf8.
1258
This sub-function is called when we know the filesystem is already in utf8
1259
encoding. So we don't need to transcode filenames.
1262
_directory = _directory_kind
1263
_listdir = os.listdir
1264
_kind_from_mode = _formats.get
1664
1266
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1665
1267
# But we don't actually uses 1-3 in pending, so set them to None
1666
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1667
read_dir = _selected_dir_reader.read_dir
1668
_directory = _directory_kind
1268
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1670
relroot, _, _, _, top = pending[-1].pop()
1673
dirblock = sorted(read_dir(relroot, top))
1270
relroot, _, _, _, top = pending.pop()
1272
relprefix = relroot + '/'
1275
top_slash = top + '/'
1278
append = dirblock.append
1279
for name in sorted(_listdir(top)):
1280
abspath = top_slash + name
1281
statvalue = _lstat(abspath)
1282
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1283
append((relprefix + name, name, kind, statvalue, abspath))
1674
1284
yield (relroot, top), dirblock
1675
1286
# push the user specified dirs from dirblock
1676
next = [d for d in reversed(dirblock) if d[2] == _directory]
1678
pending.append(next)
1681
class UnicodeDirReader(DirReader):
1682
"""A dir reader for non-utf8 file systems, which transcodes."""
1684
__slots__ = ['_utf8_encode']
1687
self._utf8_encode = codecs.getencoder('utf8')
1689
def top_prefix_to_starting_dir(self, top, prefix=""):
1690
"""See DirReader.top_prefix_to_starting_dir."""
1691
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1693
def read_dir(self, prefix, top):
1694
"""Read a single directory from a non-utf8 file system.
1696
top, and the abspath element in the output are unicode, all other paths
1697
are utf8. Local disk IO is done via unicode calls to listdir etc.
1699
This is currently the fallback code path when the filesystem encoding is
1700
not UTF-8. It may be better to implement an alternative so that we can
1701
safely handle paths that are not properly decodable in the current
1704
See DirReader.read_dir for details.
1706
_utf8_encode = self._utf8_encode
1708
_listdir = os.listdir
1709
_kind_from_mode = file_kind_from_stat_mode
1712
relprefix = prefix + '/'
1287
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1290
def _walkdirs_unicode_to_utf8(top, prefix=""):
1291
"""See _walkdirs_utf8
1293
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1295
This is currently the fallback code path when the filesystem encoding is
1296
not UTF-8. It may be better to implement an alternative so that we can
1297
safely handle paths that are not properly decodable in the current
1300
_utf8_encode = codecs.getencoder('utf8')
1302
_directory = _directory_kind
1303
_listdir = os.listdir
1304
_kind_from_mode = _formats.get
1306
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1308
relroot, _, _, _, top = pending.pop()
1310
relprefix = relroot + '/'
1715
1313
top_slash = top + u'/'
1718
1316
append = dirblock.append
1719
1317
for name in sorted(_listdir(top)):
1721
name_utf8 = _utf8_encode(name)[0]
1722
except UnicodeDecodeError:
1723
raise errors.BadFilenameEncoding(
1724
_utf8_encode(relprefix)[0] + name, _fs_enc)
1318
name_utf8 = _utf8_encode(name)[0]
1725
1319
abspath = top_slash + name
1726
1320
statvalue = _lstat(abspath)
1727
kind = _kind_from_mode(statvalue.st_mode)
1321
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1728
1322
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1323
yield (relroot, top), dirblock
1325
# push the user specified dirs from dirblock
1326
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1732
1329
def copy_tree(from_path, to_path, handlers={}):
1733
1330
"""Copy all of the entries in from_path into to_path.
1735
:param from_path: The base directory to copy.
1332
:param from_path: The base directory to copy.
1736
1333
:param to_path: The target directory. If it does not exist, it will
1738
1335
:param handlers: A dictionary of functions, which takes a source and
1890
1463
while len(b) < bytes:
1891
new = until_no_eintr(socket.recv, bytes - len(b))
1464
new = socket.recv(bytes - len(b))
1898
def send_all(socket, bytes, report_activity=None):
1471
def send_all(socket, bytes):
1899
1472
"""Send all bytes on a socket.
1901
1474
Regular socket.sendall() can give socket error 10053 on Windows. This
1902
1475
implementation sends no more than 64k at a time, which avoids this problem.
1904
:param report_activity: Call this as bytes are read, see
1905
Transport._report_activity
1907
1477
chunk_size = 2**16
1908
1478
for pos in xrange(0, len(bytes), chunk_size):
1909
block = bytes[pos:pos+chunk_size]
1910
if report_activity is not None:
1911
report_activity(len(block), 'write')
1912
until_no_eintr(socket.sendall, block)
1479
socket.sendall(bytes[pos:pos+chunk_size])
1915
1482
def dereference_path(path):
1958
1525
base = abspath(pathjoin(base, '..', '..'))
1959
1526
filename = pathjoin(base, resource_relpath)
1960
1527
return open(filename, 'rU').read()
1963
def file_kind_from_stat_mode_thunk(mode):
1964
global file_kind_from_stat_mode
1965
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1967
from bzrlib._readdir_pyx import UTF8DirReader
1968
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.
1972
from bzrlib._readdir_py import (
1973
_kind_from_mode as file_kind_from_stat_mode
1975
return file_kind_from_stat_mode(mode)
1976
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1979
def file_kind(f, _lstat=os.lstat):
1981
return file_kind_from_stat_mode(_lstat(f).st_mode)
1983
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1984
raise errors.NoSuchFile(f)
1988
def until_no_eintr(f, *a, **kw):
1989
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1990
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1994
except (IOError, OSError), e:
1995
if e.errno == errno.EINTR:
1999
def re_compile_checked(re_string, flags=0, where=""):
2000
"""Return a compiled re, or raise a sensible error.
2002
This should only be used when compiling user-supplied REs.
2004
:param re_string: Text form of regular expression.
2005
:param flags: eg re.IGNORECASE
2006
:param where: Message explaining to the user the context where
2007
it occurred, eg 'log search filter'.
2009
# from https://bugs.launchpad.net/bzr/+bug/251352
2011
re_obj = re.compile(re_string, flags)
2016
where = ' in ' + where
2017
# despite the name 'error' is a type
2018
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2019
% (where, re_string, e))
2022
if sys.platform == "win32":
2025
return msvcrt.getch()
2030
fd = sys.stdin.fileno()
2031
settings = termios.tcgetattr(fd)
2034
ch = sys.stdin.read(1)
2036
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)