676
671
:param timezone: How to display the time: 'utc', 'original' for the
677
672
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):
674
:param show_offset: Whether to append the timezone.
675
:param date_fmt: strftime format.
708
677
if timezone == 'utc':
709
678
tt = time.gmtime(t)
992
def _cicp_canonical_relpath(base, path):
993
"""Return the canonical path relative to base.
995
Like relpath, but on case-insensitive-case-preserving file-systems, this
996
will return the relpath as stored on the file-system rather than in the
997
case specified in the input string, for all existing portions of the path.
999
This will cause O(N) behaviour if called for every path in a tree; if you
1000
have a number of paths to convert, you should use canonical_relpaths().
1002
# TODO: it should be possible to optimize this for Windows by using the
1003
# win32 API FindFiles function to look for the specified name - but using
1004
# os.listdir() still gives us the correct, platform agnostic semantics in
1007
rel = relpath(base, path)
1008
# '.' will have been turned into ''
1012
abs_base = abspath(base)
1014
_listdir = os.listdir
1016
# use an explicit iterator so we can easily consume the rest on early exit.
1017
bit_iter = iter(rel.split('/'))
1018
for bit in bit_iter:
1020
for look in _listdir(current):
1021
if lbit == look.lower():
1022
current = pathjoin(current, look)
1025
# got to the end, nothing matched, so we just return the
1026
# non-existing bits as they were specified (the filename may be
1027
# the target of a move, for example).
1028
current = pathjoin(current, bit, *list(bit_iter))
1030
return current[len(abs_base)+1:]
1032
# XXX - TODO - we need better detection/integration of case-insensitive
1033
# file-systems; Linux often sees FAT32 devices, for example, so could
1034
# probably benefit from the same basic support there. For now though, only
1035
# Windows gets that support, and it gets it for *all* file-systems!
1036
if sys.platform == "win32":
1037
canonical_relpath = _cicp_canonical_relpath
1039
canonical_relpath = relpath
1041
def canonical_relpaths(base, paths):
1042
"""Create an iterable to canonicalize a sequence of relative paths.
1044
The intent is for this implementation to use a cache, vastly speeding
1045
up multiple transformations in the same directory.
1047
# but for now, we haven't optimized...
1048
return [canonical_relpath(base, p) for p in paths]
1050
942
def safe_unicode(unicode_or_utf8_string):
1051
943
"""Coerce unicode_or_utf8_string into unicode.
1053
945
If it is unicode, it is returned.
1054
946
Otherwise it is decoded from utf-8. If a decoding error
1055
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
947
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
1056
948
as a BzrBadParameter exception.
1058
950
if isinstance(unicode_or_utf8_string, unicode):
1276
1168
def walkdirs(top, prefix=""):
1277
1169
"""Yield data about all the directories in a tree.
1279
1171
This yields all the data about the contents of a directory at a time.
1280
1172
After each directory has been yielded, if the caller has mutated the list
1281
1173
to exclude some directories, they are then not descended into.
1283
1175
The data yielded is of the form:
1284
1176
((directory-relpath, directory-path-from-top),
1285
1177
[(relpath, basename, kind, lstat, path-from-top), ...]),
1286
1178
- directory-relpath is the relative path of the directory being returned
1287
1179
with respect to top. prefix is prepended to this.
1288
- directory-path-from-root is the path including top for this directory.
1180
- directory-path-from-root is the path including top for this directory.
1289
1181
It is suitable for use with os functions.
1290
1182
- relpath is the relative path within the subtree being walked.
1291
1183
- basename is the basename of the path
1293
1185
present within the tree - but it may be recorded as versioned. See
1294
1186
versioned_kind.
1295
1187
- lstat is the stat data *if* the file was statted.
1296
- planned, not implemented:
1188
- planned, not implemented:
1297
1189
path_from_tree_root is the path from the root of the tree.
1299
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1191
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1300
1192
allows one to walk a subtree but get paths that are relative to a tree
1301
1193
rooted higher up.
1302
1194
:return: an iterator over the dirs.
1304
1196
#TODO there is a bit of a smell where the results of the directory-
1305
# summary in this, and the path from the root, may not agree
1197
# summary in this, and the path from the root, may not agree
1306
1198
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1307
1199
# potentially confusing output. We should make this more robust - but
1308
1200
# not at a speed cost. RBC 20060731
1309
1201
_lstat = os.lstat
1310
1202
_directory = _directory_kind
1311
1203
_listdir = os.listdir
1312
_kind_from_mode = file_kind_from_stat_mode
1204
_kind_from_mode = _formats.get
1313
1205
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1315
1207
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1339
1231
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1342
class DirReader(object):
1343
"""An interface for reading directories."""
1345
def top_prefix_to_starting_dir(self, top, prefix=""):
1346
"""Converts top and prefix to a starting dir entry
1348
:param top: A utf8 path
1349
:param prefix: An optional utf8 path to prefix output relative paths
1351
:return: A tuple starting with prefix, and ending with the native
1354
raise NotImplementedError(self.top_prefix_to_starting_dir)
1356
def read_dir(self, prefix, top):
1357
"""Read a specific dir.
1359
:param prefix: A utf8 prefix to be preprended to the path basenames.
1360
:param top: A natively encoded path to read.
1361
:return: A list of the directories contents. Each item contains:
1362
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1364
raise NotImplementedError(self.read_dir)
1367
_selected_dir_reader = None
1234
_real_walkdirs_utf8 = None
1370
1236
def _walkdirs_utf8(top, prefix=""):
1371
1237
"""Yield data about all the directories in a tree.
1381
1247
path-from-top might be unicode or utf8, but it is the correct path to
1382
1248
pass to os functions to affect the file in question. (such as os.lstat)
1384
global _selected_dir_reader
1385
if _selected_dir_reader is None:
1250
global _real_walkdirs_utf8
1251
if _real_walkdirs_utf8 is None:
1386
1252
fs_encoding = _fs_enc.upper()
1387
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1253
if win32utils.winver == 'Windows NT':
1388
1254
# Win98 doesn't have unicode apis like FindFirstFileW
1389
1255
# TODO: We possibly could support Win98 by falling back to the
1390
1256
# original FindFirstFile, and using TCHAR instead of WCHAR,
1391
1257
# but that gets a bit tricky, and requires custom compiling
1392
1258
# for win98 anyway.
1394
from bzrlib._walkdirs_win32 import Win32ReadDir
1260
from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
1395
1261
except ImportError:
1396
_selected_dir_reader = UnicodeDirReader()
1262
_real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1398
_selected_dir_reader = Win32ReadDir()
1264
_real_walkdirs_utf8 = _walkdirs_utf8_win32_find_file
1399
1265
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1400
1266
# ANSI_X3.4-1968 is a form of ASCII
1401
_selected_dir_reader = UnicodeDirReader()
1267
_real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1404
from bzrlib._readdir_pyx import UTF8DirReader
1406
# No optimised code path
1407
_selected_dir_reader = UnicodeDirReader()
1409
_selected_dir_reader = UTF8DirReader()
1269
_real_walkdirs_utf8 = _walkdirs_fs_utf8
1270
return _real_walkdirs_utf8(top, prefix=prefix)
1273
def _walkdirs_fs_utf8(top, prefix=""):
1274
"""See _walkdirs_utf8.
1276
This sub-function is called when we know the filesystem is already in utf8
1277
encoding. So we don't need to transcode filenames.
1280
_directory = _directory_kind
1281
# Use C accelerated directory listing.
1282
_listdir = _read_dir
1283
_kind_from_mode = _formats.get
1410
1285
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1411
1286
# But we don't actually uses 1-3 in pending, so set them to None
1412
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1413
read_dir = _selected_dir_reader.read_dir
1414
_directory = _directory_kind
1287
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1416
relroot, _, _, _, top = pending[-1].pop()
1419
dirblock = sorted(read_dir(relroot, top))
1289
relroot, _, _, _, top = pending.pop()
1291
relprefix = relroot + '/'
1294
top_slash = top + '/'
1297
append = dirblock.append
1298
# read_dir supplies in should-stat order.
1299
for _, name in sorted(_listdir(top)):
1300
abspath = top_slash + name
1301
statvalue = _lstat(abspath)
1302
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1303
append((relprefix + name, name, kind, statvalue, abspath))
1420
1305
yield (relroot, top), dirblock
1421
1307
# push the user specified dirs from dirblock
1422
next = [d for d in reversed(dirblock) if d[2] == _directory]
1424
pending.append(next)
1427
class UnicodeDirReader(DirReader):
1428
"""A dir reader for non-utf8 file systems, which transcodes."""
1430
__slots__ = ['_utf8_encode']
1433
self._utf8_encode = codecs.getencoder('utf8')
1435
def top_prefix_to_starting_dir(self, top, prefix=""):
1436
"""See DirReader.top_prefix_to_starting_dir."""
1437
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1439
def read_dir(self, prefix, top):
1440
"""Read a single directory from a non-utf8 file system.
1442
top, and the abspath element in the output are unicode, all other paths
1443
are utf8. Local disk IO is done via unicode calls to listdir etc.
1445
This is currently the fallback code path when the filesystem encoding is
1446
not UTF-8. It may be better to implement an alternative so that we can
1447
safely handle paths that are not properly decodable in the current
1450
See DirReader.read_dir for details.
1452
_utf8_encode = self._utf8_encode
1454
_listdir = os.listdir
1455
_kind_from_mode = file_kind_from_stat_mode
1458
relprefix = prefix + '/'
1308
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1311
def _walkdirs_unicode_to_utf8(top, prefix=""):
1312
"""See _walkdirs_utf8
1314
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1316
This is currently the fallback code path when the filesystem encoding is
1317
not UTF-8. It may be better to implement an alternative so that we can
1318
safely handle paths that are not properly decodable in the current
1321
_utf8_encode = codecs.getencoder('utf8')
1323
_directory = _directory_kind
1324
_listdir = os.listdir
1325
_kind_from_mode = _formats.get
1327
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1329
relroot, _, _, _, top = pending.pop()
1331
relprefix = relroot + '/'
1461
1334
top_slash = top + u'/'
1464
1337
append = dirblock.append
1465
1338
for name in sorted(_listdir(top)):
1467
name_utf8 = _utf8_encode(name)[0]
1468
except UnicodeDecodeError:
1469
raise errors.BadFilenameEncoding(
1470
_utf8_encode(relprefix)[0] + name, _fs_enc)
1339
name_utf8 = _utf8_encode(name)[0]
1471
1340
abspath = top_slash + name
1472
1341
statvalue = _lstat(abspath)
1473
kind = _kind_from_mode(statvalue.st_mode)
1342
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1474
1343
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1344
yield (relroot, top), dirblock
1346
# push the user specified dirs from dirblock
1347
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1478
1350
def copy_tree(from_path, to_path, handlers={}):
1479
1351
"""Copy all of the entries in from_path into to_path.
1481
:param from_path: The base directory to copy.
1353
:param from_path: The base directory to copy.
1482
1354
:param to_path: The target directory. If it does not exist, it will
1484
1356
:param handlers: A dictionary of functions, which takes a source and
1636
1498
while len(b) < bytes:
1637
new = until_no_eintr(socket.recv, bytes - len(b))
1499
new = socket.recv(bytes - len(b))
1644
def send_all(socket, bytes, report_activity=None):
1506
def send_all(socket, bytes):
1645
1507
"""Send all bytes on a socket.
1647
1509
Regular socket.sendall() can give socket error 10053 on Windows. This
1648
1510
implementation sends no more than 64k at a time, which avoids this problem.
1650
:param report_activity: Call this as bytes are read, see
1651
Transport._report_activity
1653
1512
chunk_size = 2**16
1654
1513
for pos in xrange(0, len(bytes), chunk_size):
1655
block = bytes[pos:pos+chunk_size]
1656
if report_activity is not None:
1657
report_activity(len(block), 'write')
1658
until_no_eintr(socket.sendall, block)
1514
socket.sendall(bytes[pos:pos+chunk_size])
1661
1517
def dereference_path(path):
1706
1562
return open(filename, 'rU').read()
1709
def file_kind_from_stat_mode_thunk(mode):
1710
global file_kind_from_stat_mode
1711
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1713
from bzrlib._readdir_pyx import UTF8DirReader
1714
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1716
from bzrlib._readdir_py import (
1717
_kind_from_mode as file_kind_from_stat_mode
1719
return file_kind_from_stat_mode(mode)
1720
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1723
def file_kind(f, _lstat=os.lstat):
1725
return file_kind_from_stat_mode(_lstat(f).st_mode)
1727
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1728
raise errors.NoSuchFile(f)
1732
def until_no_eintr(f, *a, **kw):
1733
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1734
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1738
except (IOError, OSError), e:
1739
if e.errno == errno.EINTR:
1743
def re_compile_checked(re_string, flags=0, where=""):
1744
"""Return a compiled re, or raise a sensible error.
1746
This should only be used when compiling user-supplied REs.
1748
:param re_string: Text form of regular expression.
1749
:param flags: eg re.IGNORECASE
1750
:param where: Message explaining to the user the context where
1751
it occurred, eg 'log search filter'.
1753
# from https://bugs.launchpad.net/bzr/+bug/251352
1755
re_obj = re.compile(re_string, flags)
1760
where = ' in ' + where
1761
# despite the name 'error' is a type
1762
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1763
% (where, re_string, e))
1766
if sys.platform == "win32":
1769
return msvcrt.getch()
1774
fd = sys.stdin.fileno()
1775
settings = termios.tcgetattr(fd)
1778
ch = sys.stdin.read(1)
1780
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1566
from bzrlib._readdir_pyx import read_dir as _read_dir
1568
from bzrlib._readdir_py import read_dir as _read_dir