505
494
for dirname in dir_list:
506
495
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
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)
501
def pumpfile(fromfile, tofile):
502
"""Copy contents of one file to another."""
505
b = fromfile.read(BUFSIZE)
577
511
def file_iterator(input_file, readsize=32768):
647
571
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
648
572
return offset.days * 86400 + offset.seconds
650
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
652
def format_date(t, offset=0, timezone='original', date_fmt=None,
575
def format_date(t, offset=0, timezone='original', date_fmt=None,
653
576
show_offset=True):
654
"""Return a formatted date string.
656
:param t: Seconds since the epoch.
657
:param offset: Timezone offset in seconds east of utc.
658
:param timezone: How to display the time: 'utc', 'original' for the
659
timezone specified by offset, or 'local' for the process's current
661
:param date_fmt: strftime format.
662
:param show_offset: Whether to append the timezone.
664
(date_fmt, tt, offset_str) = \
665
_format_date(t, offset, timezone, date_fmt, show_offset)
666
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
667
date_str = time.strftime(date_fmt, tt)
668
return date_str + offset_str
670
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
672
"""Return an unicode date string formatted according to the current locale.
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_str = time.strftime(date_fmt, tt)
685
if not isinstance(date_str, unicode):
686
date_str = date_str.decode(bzrlib.user_encoding, 'replace')
687
return date_str + offset_str
689
def _format_date(t, offset, timezone, date_fmt, show_offset):
577
## TODO: Perhaps a global option to use either universal or local time?
578
## Or perhaps just let people set $TZ?
579
assert isinstance(t, float)
690
581
if timezone == 'utc':
691
582
tt = time.gmtime(t)
974
def _cicp_canonical_relpath(base, path):
975
"""Return the canonical path relative to base.
977
Like relpath, but on case-insensitive-case-preserving file-systems, this
978
will return the relpath as stored on the file-system rather than in the
979
case specified in the input string, for all existing portions of the path.
981
This will cause O(N) behaviour if called for every path in a tree; if you
982
have a number of paths to convert, you should use canonical_relpaths().
984
# TODO: it should be possible to optimize this for Windows by using the
985
# win32 API FindFiles function to look for the specified name - but using
986
# os.listdir() still gives us the correct, platform agnostic semantics in
989
rel = relpath(base, path)
990
# '.' will have been turned into ''
994
abs_base = abspath(base)
996
_listdir = os.listdir
998
# use an explicit iterator so we can easily consume the rest on early exit.
999
bit_iter = iter(rel.split('/'))
1000
for bit in bit_iter:
1002
for look in _listdir(current):
1003
if lbit == look.lower():
1004
current = pathjoin(current, look)
1007
# got to the end, nothing matched, so we just return the
1008
# non-existing bits as they were specified (the filename may be
1009
# the target of a move, for example).
1010
current = pathjoin(current, bit, *list(bit_iter))
1012
return current[len(abs_base)+1:]
1014
# XXX - TODO - we need better detection/integration of case-insensitive
1015
# file-systems; Linux often sees FAT32 devices, for example, so could
1016
# probably benefit from the same basic support there. For now though, only
1017
# Windows gets that support, and it gets it for *all* file-systems!
1018
if sys.platform == "win32":
1019
canonical_relpath = _cicp_canonical_relpath
1021
canonical_relpath = relpath
1023
def canonical_relpaths(base, paths):
1024
"""Create an iterable to canonicalize a sequence of relative paths.
1026
The intent is for this implementation to use a cache, vastly speeding
1027
up multiple transformations in the same directory.
1029
# but for now, we haven't optimized...
1030
return [canonical_relpath(base, p) for p in paths]
1032
837
def safe_unicode(unicode_or_utf8_string):
1033
838
"""Coerce unicode_or_utf8_string into unicode.
1045
850
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1048
def safe_utf8(unicode_or_utf8_string):
1049
"""Coerce unicode_or_utf8_string to a utf8 string.
1051
If it is a str, it is returned.
1052
If it is Unicode, it is encoded into a utf-8 string.
1054
if isinstance(unicode_or_utf8_string, str):
1055
# TODO: jam 20070209 This is overkill, and probably has an impact on
1056
# performance if we are dealing with lots of apis that want a
1059
# Make sure it is a valid utf-8 string
1060
unicode_or_utf8_string.decode('utf-8')
1061
except UnicodeDecodeError:
1062
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1063
return unicode_or_utf8_string
1064
return unicode_or_utf8_string.encode('utf-8')
1067
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1068
' Revision id generators should be creating utf8'
1072
def safe_revision_id(unicode_or_utf8_string, warn=True):
1073
"""Revision ids should now be utf8, but at one point they were unicode.
1075
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1077
:param warn: Functions that are sanitizing user data can set warn=False
1078
:return: None or a utf8 revision id.
1080
if (unicode_or_utf8_string is None
1081
or unicode_or_utf8_string.__class__ == str):
1082
return unicode_or_utf8_string
1084
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1086
return cache_utf8.encode(unicode_or_utf8_string)
1089
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1090
' generators should be creating utf8 file ids.')
1093
def safe_file_id(unicode_or_utf8_string, warn=True):
1094
"""File ids should now be utf8, but at one point they were unicode.
1096
This is the same as safe_utf8, except it uses the cached encode functions
1097
to save a little bit of performance.
1099
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1101
:param warn: Functions that are sanitizing user data can set warn=False
1102
:return: None or a utf8 file id.
1104
if (unicode_or_utf8_string is None
1105
or unicode_or_utf8_string.__class__ == str):
1106
return unicode_or_utf8_string
1108
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1110
return cache_utf8.encode(unicode_or_utf8_string)
1113
853
_platform_normalizes_filenames = False
1114
854
if sys.platform == 'darwin':
1115
855
_platform_normalizes_filenames = True
1288
1001
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1289
1002
# potentially confusing output. We should make this more robust - but
1290
1003
# not at a speed cost. RBC 20060731
1292
1006
_directory = _directory_kind
1293
1007
_listdir = os.listdir
1294
_kind_from_mode = file_kind_from_stat_mode
1295
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1008
pending = [(prefix, "", _directory, None, top)]
1011
currentdir = pending.pop()
1297
1012
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1298
relroot, _, _, _, top = pending.pop()
1300
relprefix = relroot + u'/'
1303
top_slash = top + u'/'
1306
append = dirblock.append
1308
names = sorted(_listdir(top))
1310
if not _is_error_enotdir(e):
1314
abspath = top_slash + name
1315
statvalue = _lstat(abspath)
1316
kind = _kind_from_mode(statvalue.st_mode)
1317
append((relprefix + name, name, kind, statvalue, abspath))
1318
yield (relroot, top), dirblock
1320
# push the user specified dirs from dirblock
1321
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1324
class DirReader(object):
1325
"""An interface for reading directories."""
1327
def top_prefix_to_starting_dir(self, top, prefix=""):
1328
"""Converts top and prefix to a starting dir entry
1330
:param top: A utf8 path
1331
:param prefix: An optional utf8 path to prefix output relative paths
1333
:return: A tuple starting with prefix, and ending with the native
1336
raise NotImplementedError(self.top_prefix_to_starting_dir)
1338
def read_dir(self, prefix, top):
1339
"""Read a specific dir.
1341
:param prefix: A utf8 prefix to be preprended to the path basenames.
1342
:param top: A natively encoded path to read.
1343
:return: A list of the directories contents. Each item contains:
1344
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1346
raise NotImplementedError(self.read_dir)
1349
_selected_dir_reader = None
1352
def _walkdirs_utf8(top, prefix=""):
1353
"""Yield data about all the directories in a tree.
1355
This yields the same information as walkdirs() only each entry is yielded
1356
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1357
are returned as exact byte-strings.
1359
:return: yields a tuple of (dir_info, [file_info])
1360
dir_info is (utf8_relpath, path-from-top)
1361
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1362
if top is an absolute path, path-from-top is also an absolute path.
1363
path-from-top might be unicode or utf8, but it is the correct path to
1364
pass to os functions to affect the file in question. (such as os.lstat)
1366
global _selected_dir_reader
1367
if _selected_dir_reader is None:
1368
fs_encoding = _fs_enc.upper()
1369
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1370
# Win98 doesn't have unicode apis like FindFirstFileW
1371
# TODO: We possibly could support Win98 by falling back to the
1372
# original FindFirstFile, and using TCHAR instead of WCHAR,
1373
# but that gets a bit tricky, and requires custom compiling
1376
from bzrlib._walkdirs_win32 import Win32ReadDir
1378
_selected_dir_reader = UnicodeDirReader()
1380
_selected_dir_reader = Win32ReadDir()
1381
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1382
# ANSI_X3.4-1968 is a form of ASCII
1383
_selected_dir_reader = UnicodeDirReader()
1386
from bzrlib._readdir_pyx import UTF8DirReader
1388
# No optimised code path
1389
_selected_dir_reader = UnicodeDirReader()
1391
_selected_dir_reader = UTF8DirReader()
1392
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1393
# But we don't actually uses 1-3 in pending, so set them to None
1394
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1395
read_dir = _selected_dir_reader.read_dir
1396
_directory = _directory_kind
1398
relroot, _, _, _, top = pending[-1].pop()
1401
dirblock = sorted(read_dir(relroot, top))
1402
yield (relroot, top), dirblock
1403
# push the user specified dirs from dirblock
1404
next = [d for d in reversed(dirblock) if d[2] == _directory]
1406
pending.append(next)
1409
class UnicodeDirReader(DirReader):
1410
"""A dir reader for non-utf8 file systems, which transcodes."""
1412
__slots__ = ['_utf8_encode']
1415
self._utf8_encode = codecs.getencoder('utf8')
1417
def top_prefix_to_starting_dir(self, top, prefix=""):
1418
"""See DirReader.top_prefix_to_starting_dir."""
1419
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1421
def read_dir(self, prefix, top):
1422
"""Read a single directory from a non-utf8 file system.
1424
top, and the abspath element in the output are unicode, all other paths
1425
are utf8. Local disk IO is done via unicode calls to listdir etc.
1427
This is currently the fallback code path when the filesystem encoding is
1428
not UTF-8. It may be better to implement an alternative so that we can
1429
safely handle paths that are not properly decodable in the current
1432
See DirReader.read_dir for details.
1434
_utf8_encode = self._utf8_encode
1436
_listdir = os.listdir
1437
_kind_from_mode = file_kind_from_stat_mode
1440
relprefix = prefix + '/'
1443
top_slash = top + u'/'
1446
append = dirblock.append
1015
relroot = currentdir[0] + '/'
1447
1018
for name in sorted(_listdir(top)):
1449
name_utf8 = _utf8_encode(name)[0]
1450
except UnicodeDecodeError:
1451
raise errors.BadFilenameEncoding(
1452
_utf8_encode(relprefix)[0] + name, _fs_enc)
1453
abspath = top_slash + name
1454
statvalue = _lstat(abspath)
1455
kind = _kind_from_mode(statvalue.st_mode)
1456
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1019
abspath = top + '/' + name
1020
statvalue = lstat(abspath)
1021
dirblock.append((relroot + name, name,
1022
file_kind_from_stat_mode(statvalue.st_mode),
1023
statvalue, abspath))
1024
yield (currentdir[0], top), dirblock
1025
# push the user specified dirs from dirblock
1026
for dir in reversed(dirblock):
1027
if dir[2] == _directory:
1460
1031
def copy_tree(from_path, to_path, handlers={}):
1646
1179
# The pathjoin for '.' is a workaround for Python bug #1213894.
1647
1180
# (initial path components aren't dereferenced)
1648
1181
return pathjoin(realpath(pathjoin('.', parent)), base)
1651
def supports_mapi():
1652
"""Return True if we can use MAPI to launch a mail client."""
1653
return sys.platform == "win32"
1656
def resource_string(package, resource_name):
1657
"""Load a resource from a package and return it as a string.
1659
Note: Only packages that start with bzrlib are currently supported.
1661
This is designed to be a lightweight implementation of resource
1662
loading in a way which is API compatible with the same API from
1664
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1665
If and when pkg_resources becomes a standard library, this routine
1668
# Check package name is within bzrlib
1669
if package == "bzrlib":
1670
resource_relpath = resource_name
1671
elif package.startswith("bzrlib."):
1672
package = package[len("bzrlib."):].replace('.', os.sep)
1673
resource_relpath = pathjoin(package, resource_name)
1675
raise errors.BzrError('resource package %s not in bzrlib' % package)
1677
# Map the resource to a file and read its contents
1678
base = dirname(bzrlib.__file__)
1679
if getattr(sys, 'frozen', None): # bzr.exe
1680
base = abspath(pathjoin(base, '..', '..'))
1681
filename = pathjoin(base, resource_relpath)
1682
return open(filename, 'rU').read()
1685
def file_kind_from_stat_mode_thunk(mode):
1686
global file_kind_from_stat_mode
1687
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1689
from bzrlib._readdir_pyx import UTF8DirReader
1690
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1692
from bzrlib._readdir_py import (
1693
_kind_from_mode as file_kind_from_stat_mode
1695
return file_kind_from_stat_mode(mode)
1696
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1699
def file_kind(f, _lstat=os.lstat):
1701
return file_kind_from_stat_mode(_lstat(f).st_mode)
1703
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1704
raise errors.NoSuchFile(f)
1708
def until_no_eintr(f, *a, **kw):
1709
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1710
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1714
except (IOError, OSError), e:
1715
if e.errno == errno.EINTR:
1720
if sys.platform == "win32":
1723
return msvcrt.getch()
1728
fd = sys.stdin.fileno()
1729
settings = termios.tcgetattr(fd)
1732
ch = sys.stdin.read(1)
1734
termios.tcsetattr(fd, termios.TCSADRAIN, settings)