317
345
"""We expect to be able to atomically replace 'new' with old.
319
347
On win32, if new exists, it must be moved out of the way first,
323
351
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
324
352
except OSError, e:
325
353
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
326
# If we try to rename a non-existant file onto cwd, we get
327
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
354
# If we try to rename a non-existant file onto cwd, we get
355
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
328
356
# if the old path doesn't exist, sometimes we get EACCES
329
357
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
511
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
512
report_activity=None, direction='read'):
562
def pumpfile(fromfile, tofile):
513
563
"""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
565
: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)
570
b = fromfile.read(BUFSIZE)
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)
577
578
def file_iterator(input_file, readsize=32768):
579
580
b = input_file.read(readsize)
676
656
:param timezone: How to display the time: 'utc', 'original' for the
677
657
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):
659
:param show_offset: Whether to append the timezone.
660
:param date_fmt: strftime format.
708
662
if timezone == 'utc':
709
663
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 (or NFS-mounted OSX
1034
# filesystems), for example, so could probably benefit from the same basic
1035
# support there. For now though, only Windows and OSX get that support, and
1036
# they get it for *all* file-systems!
1037
if sys.platform in ('win32', 'darwin'):
1038
canonical_relpath = _cicp_canonical_relpath
1040
canonical_relpath = relpath
1042
def canonical_relpaths(base, paths):
1043
"""Create an iterable to canonicalize a sequence of relative paths.
1045
The intent is for this implementation to use a cache, vastly speeding
1046
up multiple transformations in the same directory.
1048
# but for now, we haven't optimized...
1049
return [canonical_relpath(base, p) for p in paths]
1051
922
def safe_unicode(unicode_or_utf8_string):
1052
923
"""Coerce unicode_or_utf8_string into unicode.
1054
925
If it is unicode, it is returned.
1055
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1056
wrapped in a BzrBadParameterNotUnicode exception.
926
Otherwise it is decoded from utf-8. If a decoding error
927
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
928
as a BzrBadParameter exception.
1058
930
if isinstance(unicode_or_utf8_string, unicode):
1059
931
return unicode_or_utf8_string
1245
1117
raise errors.IllegalPath(path)
1248
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1250
def _is_error_enotdir(e):
1251
"""Check if this exception represents ENOTDIR.
1253
Unfortunately, python is very inconsistent about the exception
1254
here. The cases are:
1255
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1256
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1257
which is the windows error code.
1258
3) Windows, Python2.5 uses errno == EINVAL and
1259
winerror == ERROR_DIRECTORY
1261
:param e: An Exception object (expected to be OSError with an errno
1262
attribute, but we should be able to cope with anything)
1263
:return: True if this represents an ENOTDIR error. False otherwise.
1265
en = getattr(e, 'errno', None)
1266
if (en == errno.ENOTDIR
1267
or (sys.platform == 'win32'
1268
and (en == _WIN32_ERROR_DIRECTORY
1269
or (en == errno.EINVAL
1270
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1276
1120
def walkdirs(top, prefix=""):
1277
1121
"""Yield data about all the directories in a tree.
1279
1123
This yields all the data about the contents of a directory at a time.
1280
1124
After each directory has been yielded, if the caller has mutated the list
1281
1125
to exclude some directories, they are then not descended into.
1283
1127
The data yielded is of the form:
1284
1128
((directory-relpath, directory-path-from-top),
1285
1129
[(relpath, basename, kind, lstat, path-from-top), ...]),
1286
1130
- directory-relpath is the relative path of the directory being returned
1287
1131
with respect to top. prefix is prepended to this.
1288
- directory-path-from-root is the path including top for this directory.
1132
- directory-path-from-root is the path including top for this directory.
1289
1133
It is suitable for use with os functions.
1290
1134
- relpath is the relative path within the subtree being walked.
1291
1135
- basename is the basename of the path
1293
1137
present within the tree - but it may be recorded as versioned. See
1294
1138
versioned_kind.
1295
1139
- lstat is the stat data *if* the file was statted.
1296
- planned, not implemented:
1140
- planned, not implemented:
1297
1141
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
1143
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1300
1144
allows one to walk a subtree but get paths that are relative to a tree
1301
1145
rooted higher up.
1302
1146
:return: an iterator over the dirs.
1304
1148
#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
1149
# summary in this, and the path from the root, may not agree
1306
1150
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1307
1151
# potentially confusing output. We should make this more robust - but
1308
1152
# not at a speed cost. RBC 20060731
1309
1153
_lstat = os.lstat
1310
1154
_directory = _directory_kind
1311
1155
_listdir = os.listdir
1312
_kind_from_mode = file_kind_from_stat_mode
1156
_kind_from_mode = _formats.get
1313
1157
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1315
1159
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1324
1168
append = dirblock.append
1326
names = sorted(_listdir(top))
1328
if not _is_error_enotdir(e):
1332
abspath = top_slash + name
1333
statvalue = _lstat(abspath)
1334
kind = _kind_from_mode(statvalue.st_mode)
1335
append((relprefix + name, name, kind, statvalue, abspath))
1169
for name in sorted(_listdir(top)):
1170
abspath = top_slash + name
1171
statvalue = _lstat(abspath)
1172
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1173
append((relprefix + name, name, kind, statvalue, abspath))
1336
1174
yield (relroot, top), dirblock
1338
1176
# push the user specified dirs from dirblock
1339
1177
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
1370
1180
def _walkdirs_utf8(top, prefix=""):
1371
1181
"""Yield data about all the directories in a tree.
1381
1191
path-from-top might be unicode or utf8, but it is the correct path to
1382
1192
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:
1386
fs_encoding = _fs_enc.upper()
1387
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1388
# Win98 doesn't have unicode apis like FindFirstFileW
1389
# TODO: We possibly could support Win98 by falling back to the
1390
# original FindFirstFile, and using TCHAR instead of WCHAR,
1391
# but that gets a bit tricky, and requires custom compiling
1394
from bzrlib._walkdirs_win32 import Win32ReadDir
1396
_selected_dir_reader = UnicodeDirReader()
1398
_selected_dir_reader = Win32ReadDir()
1399
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1400
# ANSI_X3.4-1968 is a form of ASCII
1401
_selected_dir_reader = UnicodeDirReader()
1404
from bzrlib._readdir_pyx import UTF8DirReader
1406
# No optimised code path
1407
_selected_dir_reader = UnicodeDirReader()
1409
_selected_dir_reader = UTF8DirReader()
1194
fs_encoding = _fs_enc.upper()
1195
if (sys.platform == 'win32' or
1196
fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1197
return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1199
return _walkdirs_fs_utf8(top, prefix=prefix)
1202
def _walkdirs_fs_utf8(top, prefix=""):
1203
"""See _walkdirs_utf8.
1205
This sub-function is called when we know the filesystem is already in utf8
1206
encoding. So we don't need to transcode filenames.
1209
_directory = _directory_kind
1210
_listdir = os.listdir
1211
_kind_from_mode = _formats.get
1410
1213
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1411
1214
# 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
1215
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1416
relroot, _, _, _, top = pending[-1].pop()
1419
dirblock = sorted(read_dir(relroot, top))
1217
relroot, _, _, _, top = pending.pop()
1219
relprefix = relroot + '/'
1222
top_slash = top + '/'
1225
append = dirblock.append
1226
for name in sorted(_listdir(top)):
1227
abspath = top_slash + name
1228
statvalue = _lstat(abspath)
1229
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1230
append((relprefix + name, name, kind, statvalue, abspath))
1420
1231
yield (relroot, top), dirblock
1421
1233
# 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 + '/'
1234
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1237
def _walkdirs_unicode_to_utf8(top, prefix=""):
1238
"""See _walkdirs_utf8
1240
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1242
This is currently the fallback code path when the filesystem encoding is
1243
not UTF-8. It may be better to implement an alternative so that we can
1244
safely handle paths that are not properly decodable in the current
1247
_utf8_encode = codecs.getencoder('utf8')
1249
_directory = _directory_kind
1250
_listdir = os.listdir
1251
_kind_from_mode = _formats.get
1253
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1255
relroot, _, _, _, top = pending.pop()
1257
relprefix = relroot + '/'
1461
1260
top_slash = top + u'/'
1464
1263
append = dirblock.append
1465
1264
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)
1265
name_utf8 = _utf8_encode(name)[0]
1471
1266
abspath = top_slash + name
1472
1267
statvalue = _lstat(abspath)
1473
kind = _kind_from_mode(statvalue.st_mode)
1268
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1474
1269
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1270
yield (relroot, top), dirblock
1272
# push the user specified dirs from dirblock
1273
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1478
1276
def copy_tree(from_path, to_path, handlers={}):
1479
1277
"""Copy all of the entries in from_path into to_path.
1481
:param from_path: The base directory to copy.
1279
:param from_path: The base directory to copy.
1482
1280
:param to_path: The target directory. If it does not exist, it will
1484
1282
:param handlers: A dictionary of functions, which takes a source and
1636
1408
while len(b) < bytes:
1637
new = until_no_eintr(socket.recv, bytes - len(b))
1409
new = socket.recv(bytes - len(b))
1644
def send_all(socket, bytes, report_activity=None):
1416
def send_all(socket, bytes):
1645
1417
"""Send all bytes on a socket.
1647
1419
Regular socket.sendall() can give socket error 10053 on Windows. This
1648
1420
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
1422
chunk_size = 2**16
1654
1423
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)
1424
socket.sendall(bytes[pos:pos+chunk_size])
1661
1427
def dereference_path(path):
1704
1470
base = abspath(pathjoin(base, '..', '..'))
1705
1471
filename = pathjoin(base, resource_relpath)
1706
1472
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)