482
505
for dirname in dir_list:
483
506
if is_inside(dirname, fname) or is_inside(fname, dirname):
511
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
512
report_activity=None, direction='read'):
513
"""Copy contents of one file to another.
515
The read_length can either be -1 to read to end-of-file (EOF) or
516
it can specify the maximum number of bytes to read.
518
The buff_size represents the maximum size for each read operation
519
performed on from_file.
521
:param report_activity: Call this as bytes are read, see
522
Transport._report_activity
523
:param direction: Will be passed to report_activity
525
:return: The number of bytes copied.
529
# read specified number of bytes
531
while read_length > 0:
532
num_bytes_to_read = min(read_length, buff_size)
534
block = from_file.read(num_bytes_to_read)
538
if report_activity is not None:
539
report_activity(len(block), direction)
542
actual_bytes_read = len(block)
543
read_length -= actual_bytes_read
544
length += actual_bytes_read
489
def pumpfile(fromfile, tofile):
490
"""Copy contents of one file to another."""
493
b = fromfile.read(BUFSIZE)
548
block = from_file.read(buff_size)
552
if report_activity is not None:
553
report_activity(len(block), direction)
559
def pump_string_file(bytes, file_handle, segment_size=None):
560
"""Write bytes to file_handle in many smaller writes.
562
:param bytes: The string to write.
563
:param file_handle: The file to write to.
565
# Write data in chunks rather than all at once, because very large
566
# writes fail on some platforms (e.g. Windows with SMB mounted
569
segment_size = 5242880 # 5MB
570
segments = range(len(bytes) / segment_size + 1)
571
write = file_handle.write
572
for segment_index in segments:
573
segment = buffer(bytes, segment_index * segment_size, segment_size)
499
577
def file_iterator(input_file, readsize=32768):
555
661
def local_time_offset(t=None):
556
662
"""Return offset of local zone from GMT, either at present or at time t."""
557
# python2.3 localtime() can't take None
561
if time.localtime(t).tm_isdst and time.daylight:
564
return -time.timezone
567
def format_date(t, offset=0, timezone='original', date_fmt=None,
665
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
666
return offset.days * 86400 + offset.seconds
668
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
670
def format_date(t, offset=0, timezone='original', date_fmt=None,
568
671
show_offset=True):
569
## TODO: Perhaps a global option to use either universal or local time?
570
## Or perhaps just let people set $TZ?
571
assert isinstance(t, float)
672
"""Return a formatted date string.
674
:param t: Seconds since the epoch.
675
:param offset: Timezone offset in seconds east of utc.
676
:param timezone: How to display the time: 'utc', 'original' for the
677
timezone specified by offset, or 'local' for the process's current
679
:param date_fmt: strftime format.
680
:param show_offset: Whether to append the timezone.
682
(date_fmt, tt, offset_str) = \
683
_format_date(t, offset, timezone, date_fmt, show_offset)
684
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
685
date_str = time.strftime(date_fmt, tt)
686
return date_str + offset_str
688
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
690
"""Return an unicode date string formatted according to the current locale.
692
:param t: Seconds since the epoch.
693
:param offset: Timezone offset in seconds east of utc.
694
:param timezone: How to display the time: 'utc', 'original' for the
695
timezone specified by offset, or 'local' for the process's current
697
:param date_fmt: strftime format.
698
:param show_offset: Whether to append the timezone.
700
(date_fmt, tt, offset_str) = \
701
_format_date(t, offset, timezone, date_fmt, show_offset)
702
date_str = time.strftime(date_fmt, tt)
703
if not isinstance(date_str, unicode):
704
date_str = date_str.decode(bzrlib.user_encoding, 'replace')
705
return date_str + offset_str
707
def _format_date(t, offset, timezone, date_fmt, show_offset):
573
708
if timezone == 'utc':
574
709
tt = time.gmtime(t)
581
716
tt = time.localtime(t)
582
717
offset = local_time_offset(t)
584
raise BzrError("unsupported timezone format %r" % timezone,
585
['options are "utc", "original", "local"'])
719
raise errors.UnsupportedTimezoneFormat(timezone)
586
720
if date_fmt is None:
587
721
date_fmt = "%a %Y-%m-%d %H:%M:%S"
589
723
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
592
return (time.strftime(date_fmt, tt) + offset_str)
726
return (date_fmt, tt, offset_str)
595
729
def compact_date(when):
596
730
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
733
def format_delta(delta):
734
"""Get a nice looking string for a time delta.
736
:param delta: The time difference in seconds, can be positive or negative.
737
positive indicates time in the past, negative indicates time in the
738
future. (usually time.time() - stored_time)
739
:return: String formatted to show approximate resolution
745
direction = 'in the future'
749
if seconds < 90: # print seconds up to 90 seconds
751
return '%d second %s' % (seconds, direction,)
753
return '%d seconds %s' % (seconds, direction)
755
minutes = int(seconds / 60)
756
seconds -= 60 * minutes
761
if minutes < 90: # print minutes, seconds up to 90 minutes
763
return '%d minute, %d second%s %s' % (
764
minutes, seconds, plural_seconds, direction)
766
return '%d minutes, %d second%s %s' % (
767
minutes, seconds, plural_seconds, direction)
769
hours = int(minutes / 60)
770
minutes -= 60 * hours
777
return '%d hour, %d minute%s %s' % (hours, minutes,
778
plural_minutes, direction)
779
return '%d hours, %d minute%s %s' % (hours, minutes,
780
plural_minutes, direction)
601
783
"""Return size of given open file."""
1006
def _cicp_canonical_relpath(base, path):
1007
"""Return the canonical path relative to base.
1009
Like relpath, but on case-insensitive-case-preserving file-systems, this
1010
will return the relpath as stored on the file-system rather than in the
1011
case specified in the input string, for all existing portions of the path.
1013
This will cause O(N) behaviour if called for every path in a tree; if you
1014
have a number of paths to convert, you should use canonical_relpaths().
1016
# TODO: it should be possible to optimize this for Windows by using the
1017
# win32 API FindFiles function to look for the specified name - but using
1018
# os.listdir() still gives us the correct, platform agnostic semantics in
1021
rel = relpath(base, path)
1022
# '.' will have been turned into ''
1026
abs_base = abspath(base)
1028
_listdir = os.listdir
1030
# use an explicit iterator so we can easily consume the rest on early exit.
1031
bit_iter = iter(rel.split('/'))
1032
for bit in bit_iter:
1034
for look in _listdir(current):
1035
if lbit == look.lower():
1036
current = pathjoin(current, look)
1039
# got to the end, nothing matched, so we just return the
1040
# non-existing bits as they were specified (the filename may be
1041
# the target of a move, for example).
1042
current = pathjoin(current, bit, *list(bit_iter))
1044
return current[len(abs_base)+1:]
1046
# XXX - TODO - we need better detection/integration of case-insensitive
1047
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1048
# filesystems), for example, so could probably benefit from the same basic
1049
# support there. For now though, only Windows and OSX get that support, and
1050
# they get it for *all* file-systems!
1051
if sys.platform in ('win32', 'darwin'):
1052
canonical_relpath = _cicp_canonical_relpath
1054
canonical_relpath = relpath
1056
def canonical_relpaths(base, paths):
1057
"""Create an iterable to canonicalize a sequence of relative paths.
1059
The intent is for this implementation to use a cache, vastly speeding
1060
up multiple transformations in the same directory.
1062
# but for now, we haven't optimized...
1063
return [canonical_relpath(base, p) for p in paths]
787
1065
def safe_unicode(unicode_or_utf8_string):
788
1066
"""Coerce unicode_or_utf8_string into unicode.
790
1068
If it is unicode, it is returned.
791
Otherwise it is decoded from utf-8. If a decoding error
792
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
793
as a BzrBadParameter exception.
1069
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1070
wrapped in a BzrBadParameterNotUnicode exception.
795
1072
if isinstance(unicode_or_utf8_string, unicode):
796
1073
return unicode_or_utf8_string
798
1075
return unicode_or_utf8_string.decode('utf8')
799
1076
except UnicodeDecodeError:
800
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
1077
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1080
def safe_utf8(unicode_or_utf8_string):
1081
"""Coerce unicode_or_utf8_string to a utf8 string.
1083
If it is a str, it is returned.
1084
If it is Unicode, it is encoded into a utf-8 string.
1086
if isinstance(unicode_or_utf8_string, str):
1087
# TODO: jam 20070209 This is overkill, and probably has an impact on
1088
# performance if we are dealing with lots of apis that want a
1091
# Make sure it is a valid utf-8 string
1092
unicode_or_utf8_string.decode('utf-8')
1093
except UnicodeDecodeError:
1094
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1095
return unicode_or_utf8_string
1096
return unicode_or_utf8_string.encode('utf-8')
1099
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1100
' Revision id generators should be creating utf8'
1104
def safe_revision_id(unicode_or_utf8_string, warn=True):
1105
"""Revision ids should now be utf8, but at one point they were unicode.
1107
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1109
:param warn: Functions that are sanitizing user data can set warn=False
1110
:return: None or a utf8 revision id.
1112
if (unicode_or_utf8_string is None
1113
or unicode_or_utf8_string.__class__ == str):
1114
return unicode_or_utf8_string
1116
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1118
return cache_utf8.encode(unicode_or_utf8_string)
1121
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1122
' generators should be creating utf8 file ids.')
1125
def safe_file_id(unicode_or_utf8_string, warn=True):
1126
"""File ids should now be utf8, but at one point they were unicode.
1128
This is the same as safe_utf8, except it uses the cached encode functions
1129
to save a little bit of performance.
1131
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1133
:param warn: Functions that are sanitizing user data can set warn=False
1134
:return: None or a utf8 file id.
1136
if (unicode_or_utf8_string is None
1137
or unicode_or_utf8_string.__class__ == str):
1138
return unicode_or_utf8_string
1140
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1142
return cache_utf8.encode(unicode_or_utf8_string)
803
1145
_platform_normalizes_filenames = False
897
1251
def check_legal_path(path):
898
"""Check whether the supplied path is legal.
1252
"""Check whether the supplied path is legal.
899
1253
This is only required on Windows, so we don't test on other platforms
902
1256
if sys.platform != "win32":
904
1258
if _validWin32PathRE.match(path) is None:
905
raise IllegalPath(path)
1259
raise errors.IllegalPath(path)
1262
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1264
def _is_error_enotdir(e):
1265
"""Check if this exception represents ENOTDIR.
1267
Unfortunately, python is very inconsistent about the exception
1268
here. The cases are:
1269
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1270
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1271
which is the windows error code.
1272
3) Windows, Python2.5 uses errno == EINVAL and
1273
winerror == ERROR_DIRECTORY
1275
:param e: An Exception object (expected to be OSError with an errno
1276
attribute, but we should be able to cope with anything)
1277
:return: True if this represents an ENOTDIR error. False otherwise.
1279
en = getattr(e, 'errno', None)
1280
if (en == errno.ENOTDIR
1281
or (sys.platform == 'win32'
1282
and (en == _WIN32_ERROR_DIRECTORY
1283
or (en == errno.EINVAL
1284
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
908
1290
def walkdirs(top, prefix=""):
909
1291
"""Yield data about all the directories in a tree.
911
1293
This yields all the data about the contents of a directory at a time.
912
1294
After each directory has been yielded, if the caller has mutated the list
913
1295
to exclude some directories, they are then not descended into.
915
1297
The data yielded is of the form:
916
1298
((directory-relpath, directory-path-from-top),
917
[(relpath, basename, kind, lstat), ...]),
1299
[(relpath, basename, kind, lstat, path-from-top), ...]),
918
1300
- directory-relpath is the relative path of the directory being returned
919
1301
with respect to top. prefix is prepended to this.
920
- directory-path-from-root is the path including top for this directory.
1302
- directory-path-from-root is the path including top for this directory.
921
1303
It is suitable for use with os functions.
922
1304
- relpath is the relative path within the subtree being walked.
923
1305
- basename is the basename of the path
925
1307
present within the tree - but it may be recorded as versioned. See
927
1309
- lstat is the stat data *if* the file was statted.
928
- planned, not implemented:
1310
- planned, not implemented:
929
1311
path_from_tree_root is the path from the root of the tree.
931
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1313
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
932
1314
allows one to walk a subtree but get paths that are relative to a tree
933
1315
rooted higher up.
934
1316
:return: an iterator over the dirs.
936
1318
#TODO there is a bit of a smell where the results of the directory-
937
# summary in this, and the path from the root, may not agree
1319
# summary in this, and the path from the root, may not agree
938
1320
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
939
1321
# potentially confusing output. We should make this more robust - but
940
1322
# not at a speed cost. RBC 20060731
943
1324
_directory = _directory_kind
945
pending = [(prefix, "", _directory, None, top)]
1325
_listdir = os.listdir
1326
_kind_from_mode = file_kind_from_stat_mode
1327
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
948
currentdir = pending.pop()
949
1329
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
952
relroot = currentdir[0] + '/'
1330
relroot, _, _, _, top = pending.pop()
1332
relprefix = relroot + u'/'
1335
top_slash = top + u'/'
1338
append = dirblock.append
1340
names = sorted(_listdir(top))
1342
if not _is_error_enotdir(e):
1346
abspath = top_slash + name
1347
statvalue = _lstat(abspath)
1348
kind = _kind_from_mode(statvalue.st_mode)
1349
append((relprefix + name, name, kind, statvalue, abspath))
1350
yield (relroot, top), dirblock
1352
# push the user specified dirs from dirblock
1353
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1356
class DirReader(object):
1357
"""An interface for reading directories."""
1359
def top_prefix_to_starting_dir(self, top, prefix=""):
1360
"""Converts top and prefix to a starting dir entry
1362
:param top: A utf8 path
1363
:param prefix: An optional utf8 path to prefix output relative paths
1365
:return: A tuple starting with prefix, and ending with the native
1368
raise NotImplementedError(self.top_prefix_to_starting_dir)
1370
def read_dir(self, prefix, top):
1371
"""Read a specific dir.
1373
:param prefix: A utf8 prefix to be preprended to the path basenames.
1374
:param top: A natively encoded path to read.
1375
:return: A list of the directories contents. Each item contains:
1376
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1378
raise NotImplementedError(self.read_dir)
1381
_selected_dir_reader = None
1384
def _walkdirs_utf8(top, prefix=""):
1385
"""Yield data about all the directories in a tree.
1387
This yields the same information as walkdirs() only each entry is yielded
1388
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1389
are returned as exact byte-strings.
1391
:return: yields a tuple of (dir_info, [file_info])
1392
dir_info is (utf8_relpath, path-from-top)
1393
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1394
if top is an absolute path, path-from-top is also an absolute path.
1395
path-from-top might be unicode or utf8, but it is the correct path to
1396
pass to os functions to affect the file in question. (such as os.lstat)
1398
global _selected_dir_reader
1399
if _selected_dir_reader is None:
1400
fs_encoding = _fs_enc.upper()
1401
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1402
# Win98 doesn't have unicode apis like FindFirstFileW
1403
# TODO: We possibly could support Win98 by falling back to the
1404
# original FindFirstFile, and using TCHAR instead of WCHAR,
1405
# but that gets a bit tricky, and requires custom compiling
1408
from bzrlib._walkdirs_win32 import Win32ReadDir
1409
_selected_dir_reader = Win32ReadDir()
1412
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1413
# ANSI_X3.4-1968 is a form of ASCII
1415
from bzrlib._readdir_pyx import UTF8DirReader
1416
_selected_dir_reader = UTF8DirReader()
1420
if _selected_dir_reader is None:
1421
# Fallback to the python version
1422
_selected_dir_reader = UnicodeDirReader()
1424
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1425
# But we don't actually uses 1-3 in pending, so set them to None
1426
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1427
read_dir = _selected_dir_reader.read_dir
1428
_directory = _directory_kind
1430
relroot, _, _, _, top = pending[-1].pop()
1433
dirblock = sorted(read_dir(relroot, top))
1434
yield (relroot, top), dirblock
1435
# push the user specified dirs from dirblock
1436
next = [d for d in reversed(dirblock) if d[2] == _directory]
1438
pending.append(next)
1441
class UnicodeDirReader(DirReader):
1442
"""A dir reader for non-utf8 file systems, which transcodes."""
1444
__slots__ = ['_utf8_encode']
1447
self._utf8_encode = codecs.getencoder('utf8')
1449
def top_prefix_to_starting_dir(self, top, prefix=""):
1450
"""See DirReader.top_prefix_to_starting_dir."""
1451
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1453
def read_dir(self, prefix, top):
1454
"""Read a single directory from a non-utf8 file system.
1456
top, and the abspath element in the output are unicode, all other paths
1457
are utf8. Local disk IO is done via unicode calls to listdir etc.
1459
This is currently the fallback code path when the filesystem encoding is
1460
not UTF-8. It may be better to implement an alternative so that we can
1461
safely handle paths that are not properly decodable in the current
1464
See DirReader.read_dir for details.
1466
_utf8_encode = self._utf8_encode
1468
_listdir = os.listdir
1469
_kind_from_mode = file_kind_from_stat_mode
1472
relprefix = prefix + '/'
1475
top_slash = top + u'/'
1478
append = dirblock.append
955
1479
for name in sorted(_listdir(top)):
956
abspath = top + '/' + name
957
statvalue = lstat(abspath)
958
dirblock.append((relroot + name, name,
959
file_kind_from_stat_mode(statvalue.st_mode),
961
yield (currentdir[0], top), dirblock
962
# push the user specified dirs from dirblock
963
for dir in reversed(dirblock):
964
if dir[2] == _directory:
1481
name_utf8 = _utf8_encode(name)[0]
1482
except UnicodeDecodeError:
1483
raise errors.BadFilenameEncoding(
1484
_utf8_encode(relprefix)[0] + name, _fs_enc)
1485
abspath = top_slash + name
1486
statvalue = _lstat(abspath)
1487
kind = _kind_from_mode(statvalue.st_mode)
1488
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
968
1492
def copy_tree(from_path, to_path, handlers={}):
969
1493
"""Copy all of the entries in from_path into to_path.
971
:param from_path: The base directory to copy.
1495
:param from_path: The base directory to copy.
972
1496
:param to_path: The target directory. If it does not exist, it will
974
1498
:param handlers: A dictionary of functions, which takes a source and
1025
1549
_cached_user_encoding = None
1028
def get_user_encoding():
1552
def get_user_encoding(use_cache=True):
1029
1553
"""Find out what the preferred user encoding is.
1031
1555
This is generally the encoding that is used for command line parameters
1032
1556
and file contents. This may be different from the terminal encoding
1033
1557
or the filesystem encoding.
1559
:param use_cache: Enable cache for detected encoding.
1560
(This parameter is turned on by default,
1561
and required only for selftesting)
1035
1563
:return: A string defining the preferred user encoding
1037
1565
global _cached_user_encoding
1038
if _cached_user_encoding is not None:
1566
if _cached_user_encoding is not None and use_cache:
1039
1567
return _cached_user_encoding
1041
1569
if sys.platform == 'darwin':
1042
# work around egregious python 2.4 bug
1570
# python locale.getpreferredencoding() always return
1571
# 'mac-roman' on darwin. That's a lie.
1043
1572
sys.platform = 'posix'
1574
if os.environ.get('LANG', None) is None:
1575
# If LANG is not set, we end up with 'ascii', which is bad
1576
# ('mac-roman' is more than ascii), so we set a default which
1577
# will give us UTF-8 (which appears to work in all cases on
1578
# OSX). Users are still free to override LANG of course, as
1579
# long as it give us something meaningful. This work-around
1580
# *may* not be needed with python 3k and/or OSX 10.5, but will
1581
# work with them too -- vila 20080908
1582
os.environ['LANG'] = 'en_US.UTF-8'
1047
1585
sys.platform = 'darwin'
1052
_cached_user_encoding = locale.getpreferredencoding()
1590
user_encoding = locale.getpreferredencoding()
1053
1591
except locale.Error, e:
1054
1592
sys.stderr.write('bzr: warning: %s\n'
1055
' Could not what text encoding to use.\n'
1593
' Could not determine what text encoding to use.\n'
1056
1594
' This error usually means your Python interpreter\n'
1057
1595
' doesn\'t support the locale set by $LANG (%s)\n'
1058
1596
" Continuing with ascii encoding.\n"
1059
1597
% (e, os.environ.get('LANG')))
1061
if _cached_user_encoding is None:
1062
_cached_user_encoding = 'ascii'
1063
return _cached_user_encoding
1598
user_encoding = 'ascii'
1600
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1601
# treat that as ASCII, and not support printing unicode characters to the
1604
# For python scripts run under vim, we get '', so also treat that as ASCII
1605
if user_encoding in (None, 'cp0', ''):
1606
user_encoding = 'ascii'
1610
codecs.lookup(user_encoding)
1612
sys.stderr.write('bzr: warning:'
1613
' unknown encoding %s.'
1614
' Continuing with ascii encoding.\n'
1617
user_encoding = 'ascii'
1620
_cached_user_encoding = user_encoding
1622
return user_encoding
1625
def get_host_name():
1626
"""Return the current unicode host name.
1628
This is meant to be used in place of socket.gethostname() because that
1629
behaves inconsistently on different platforms.
1631
if sys.platform == "win32":
1633
return win32utils.get_host_name()
1636
return socket.gethostname().decode(get_user_encoding())
1639
def recv_all(socket, bytes):
1640
"""Receive an exact number of bytes.
1642
Regular Socket.recv() may return less than the requested number of bytes,
1643
dependning on what's in the OS buffer. MSG_WAITALL is not available
1644
on all platforms, but this should work everywhere. This will return
1645
less than the requested amount if the remote end closes.
1647
This isn't optimized and is intended mostly for use in testing.
1650
while len(b) < bytes:
1651
new = until_no_eintr(socket.recv, bytes - len(b))
1658
def send_all(socket, bytes, report_activity=None):
1659
"""Send all bytes on a socket.
1661
Regular socket.sendall() can give socket error 10053 on Windows. This
1662
implementation sends no more than 64k at a time, which avoids this problem.
1664
:param report_activity: Call this as bytes are read, see
1665
Transport._report_activity
1668
for pos in xrange(0, len(bytes), chunk_size):
1669
block = bytes[pos:pos+chunk_size]
1670
if report_activity is not None:
1671
report_activity(len(block), 'write')
1672
until_no_eintr(socket.sendall, block)
1675
def dereference_path(path):
1676
"""Determine the real path to a file.
1678
All parent elements are dereferenced. But the file itself is not
1680
:param path: The original path. May be absolute or relative.
1681
:return: the real path *to* the file
1683
parent, base = os.path.split(path)
1684
# The pathjoin for '.' is a workaround for Python bug #1213894.
1685
# (initial path components aren't dereferenced)
1686
return pathjoin(realpath(pathjoin('.', parent)), base)
1689
def supports_mapi():
1690
"""Return True if we can use MAPI to launch a mail client."""
1691
return sys.platform == "win32"
1694
def resource_string(package, resource_name):
1695
"""Load a resource from a package and return it as a string.
1697
Note: Only packages that start with bzrlib are currently supported.
1699
This is designed to be a lightweight implementation of resource
1700
loading in a way which is API compatible with the same API from
1702
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1703
If and when pkg_resources becomes a standard library, this routine
1706
# Check package name is within bzrlib
1707
if package == "bzrlib":
1708
resource_relpath = resource_name
1709
elif package.startswith("bzrlib."):
1710
package = package[len("bzrlib."):].replace('.', os.sep)
1711
resource_relpath = pathjoin(package, resource_name)
1713
raise errors.BzrError('resource package %s not in bzrlib' % package)
1715
# Map the resource to a file and read its contents
1716
base = dirname(bzrlib.__file__)
1717
if getattr(sys, 'frozen', None): # bzr.exe
1718
base = abspath(pathjoin(base, '..', '..'))
1719
filename = pathjoin(base, resource_relpath)
1720
return open(filename, 'rU').read()
1723
def file_kind_from_stat_mode_thunk(mode):
1724
global file_kind_from_stat_mode
1725
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1727
from bzrlib._readdir_pyx import UTF8DirReader
1728
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1730
from bzrlib._readdir_py import (
1731
_kind_from_mode as file_kind_from_stat_mode
1733
return file_kind_from_stat_mode(mode)
1734
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1737
def file_kind(f, _lstat=os.lstat):
1739
return file_kind_from_stat_mode(_lstat(f).st_mode)
1741
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1742
raise errors.NoSuchFile(f)
1746
def until_no_eintr(f, *a, **kw):
1747
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1748
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1752
except (IOError, OSError), e:
1753
if e.errno == errno.EINTR:
1757
def re_compile_checked(re_string, flags=0, where=""):
1758
"""Return a compiled re, or raise a sensible error.
1760
This should only be used when compiling user-supplied REs.
1762
:param re_string: Text form of regular expression.
1763
:param flags: eg re.IGNORECASE
1764
:param where: Message explaining to the user the context where
1765
it occurred, eg 'log search filter'.
1767
# from https://bugs.launchpad.net/bzr/+bug/251352
1769
re_obj = re.compile(re_string, flags)
1774
where = ' in ' + where
1775
# despite the name 'error' is a type
1776
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1777
% (where, re_string, e))
1780
if sys.platform == "win32":
1783
return msvcrt.getch()
1788
fd = sys.stdin.fileno()
1789
settings = termios.tcgetattr(fd)
1792
ch = sys.stdin.read(1)
1794
termios.tcsetattr(fd, termios.TCSADRAIN, settings)