169
250
unlink_func(tmp_name)
171
252
rename_func(tmp_name, new)
173
# Default is to just use the python builtins
174
abspath = os.path.abspath
175
realpath = os.path.realpath
253
if failure_exc is not None:
254
raise failure_exc[0], failure_exc[1], failure_exc[2]
257
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
258
# choke on a Unicode string containing a relative path if
259
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
261
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
262
def _posix_abspath(path):
263
# jam 20060426 rather than encoding to fsencoding
264
# copy posixpath.abspath, but use os.getcwdu instead
265
if not posixpath.isabs(path):
266
path = posixpath.join(getcwd(), path)
267
return posixpath.normpath(path)
270
def _posix_realpath(path):
271
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
274
def _win32_fixdrive(path):
275
"""Force drive letters to be consistent.
277
win32 is inconsistent whether it returns lower or upper case
278
and even if it was consistent the user might type the other
279
so we force it to uppercase
280
running python.exe under cmd.exe return capital C:\\
281
running win32 python inside a cygwin shell returns lowercase c:\\
283
drive, path = _nt_splitdrive(path)
284
return drive.upper() + path
287
def _win32_abspath(path):
288
# Real _nt_abspath doesn't have a problem with a unicode cwd
289
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
292
def _win98_abspath(path):
293
"""Return the absolute version of a path.
294
Windows 98 safe implementation (python reimplementation
295
of Win32 API function GetFullPathNameW)
300
# \\HOST\path => //HOST/path
301
# //HOST/path => //HOST/path
302
# path => C:/cwd/path
305
# check for absolute path
306
drive = _nt_splitdrive(path)[0]
307
if drive == '' and path[:2] not in('//','\\\\'):
309
# we cannot simply os.path.join cwd and path
310
# because os.path.join('C:','/path') produce '/path'
311
# and this is incorrect
312
if path[:1] in ('/','\\'):
313
cwd = _nt_splitdrive(cwd)[0]
315
path = cwd + '\\' + path
316
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
319
def _win32_realpath(path):
320
# Real _nt_realpath doesn't have a problem with a unicode cwd
321
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
324
def _win32_pathjoin(*args):
325
return _nt_join(*args).replace('\\', '/')
328
def _win32_normpath(path):
329
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
333
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
336
def _win32_mkdtemp(*args, **kwargs):
337
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
340
def _win32_rename(old, new):
341
"""We expect to be able to atomically replace 'new' with old.
343
On win32, if new exists, it must be moved out of the way first,
347
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
349
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
350
# If we try to rename a non-existant file onto cwd, we get
351
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
352
# if the old path doesn't exist, sometimes we get EACCES
353
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
359
return unicodedata.normalize('NFC', os.getcwdu())
362
# Default is to just use the python builtins, but these can be rebound on
363
# particular platforms.
364
abspath = _posix_abspath
365
realpath = _posix_realpath
176
366
pathjoin = os.path.join
177
367
normpath = os.path.normpath
178
368
getcwd = os.getcwdu
179
mkdtemp = tempfile.mkdtemp
180
369
rename = os.rename
181
370
dirname = os.path.dirname
182
371
basename = os.path.basename
184
if os.name == "posix":
185
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
186
# choke on a Unicode string containing a relative path if
187
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
189
_fs_enc = sys.getfilesystemencoding()
191
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
194
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
372
split = os.path.split
373
splitext = os.path.splitext
374
# These were already imported into local scope
375
# mkdtemp = tempfile.mkdtemp
376
# rmtree = shutil.rmtree
378
MIN_ABS_PATHLENGTH = 1
196
381
if sys.platform == 'win32':
197
# We need to use the Unicode-aware os.path.abspath and
198
# os.path.realpath on Windows systems.
200
return os.path.abspath(path).replace('\\', '/')
203
return os.path.realpath(path).replace('\\', '/')
206
return os.path.join(*args).replace('\\', '/')
209
return os.path.normpath(path).replace('\\', '/')
212
return os.getcwdu().replace('\\', '/')
214
def mkdtemp(*args, **kwargs):
215
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
217
def rename(old, new):
218
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
382
if win32utils.winver == 'Windows 98':
383
abspath = _win98_abspath
385
abspath = _win32_abspath
386
realpath = _win32_realpath
387
pathjoin = _win32_pathjoin
388
normpath = _win32_normpath
389
getcwd = _win32_getcwd
390
mkdtemp = _win32_mkdtemp
391
rename = _win32_rename
393
MIN_ABS_PATHLENGTH = 3
395
def _win32_delete_readonly(function, path, excinfo):
396
"""Error handler for shutil.rmtree function [for win32]
397
Helps to remove files and dirs marked as read-only.
399
exception = excinfo[1]
400
if function in (os.remove, os.rmdir) \
401
and isinstance(exception, OSError) \
402
and exception.errno == errno.EACCES:
408
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
409
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
410
return shutil.rmtree(path, ignore_errors, onerror)
412
f = win32utils.get_unicode_argv # special function or None
416
elif sys.platform == 'darwin':
420
def get_terminal_encoding():
421
"""Find the best encoding for printing to the screen.
423
This attempts to check both sys.stdout and sys.stdin to see
424
what encoding they are in, and if that fails it falls back to
425
osutils.get_user_encoding().
426
The problem is that on Windows, locale.getpreferredencoding()
427
is not the same encoding as that used by the console:
428
http://mail.python.org/pipermail/python-list/2003-May/162357.html
430
On my standard US Windows XP, the preferred encoding is
431
cp1252, but the console is cp437
433
from bzrlib.trace import mutter
434
output_encoding = getattr(sys.stdout, 'encoding', None)
435
if not output_encoding:
436
input_encoding = getattr(sys.stdin, 'encoding', None)
437
if not input_encoding:
438
output_encoding = get_user_encoding()
439
mutter('encoding stdout as osutils.get_user_encoding() %r',
442
output_encoding = input_encoding
443
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
445
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
446
if output_encoding == 'cp0':
447
# invalid encoding (cp0 means 'no codepage' on Windows)
448
output_encoding = get_user_encoding()
449
mutter('cp0 is invalid encoding.'
450
' encoding stdout as osutils.get_user_encoding() %r',
454
codecs.lookup(output_encoding)
456
sys.stderr.write('bzr: warning:'
457
' unknown terminal encoding %s.\n'
458
' Using encoding %s instead.\n'
459
% (output_encoding, get_user_encoding())
461
output_encoding = get_user_encoding()
463
return output_encoding
221
466
def normalizepath(f):
222
if hasattr(os.path, 'realpath'):
467
if getattr(os.path, 'realpath', None) is not None:
595
1115
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
596
1116
avoids that problem.
598
if sys.platform != "win32":
602
assert len(base) >= minlength, ('Length of base must be equal or exceed the'
603
' platform minimum length (which is %d)' % minlength)
1119
if len(base) < MIN_ABS_PATHLENGTH:
1120
# must have space for e.g. a drive letter
1121
raise ValueError('%r is too short to calculate a relative path'
604
1124
rp = abspath(path)
608
while len(head) >= len(base):
1129
if len(head) <= len(base) and head != base:
1130
raise errors.PathNotChild(rp, base)
609
1131
if head == base:
611
head, tail = os.path.split(head)
1133
head, tail = split(head)
615
# XXX This should raise a NotChildPath exception, as its not tied
617
raise PathNotChild(rp, base)
1138
return pathjoin(*reversed(s))
1143
def _cicp_canonical_relpath(base, path):
1144
"""Return the canonical path relative to base.
1146
Like relpath, but on case-insensitive-case-preserving file-systems, this
1147
will return the relpath as stored on the file-system rather than in the
1148
case specified in the input string, for all existing portions of the path.
1150
This will cause O(N) behaviour if called for every path in a tree; if you
1151
have a number of paths to convert, you should use canonical_relpaths().
1153
# TODO: it should be possible to optimize this for Windows by using the
1154
# win32 API FindFiles function to look for the specified name - but using
1155
# os.listdir() still gives us the correct, platform agnostic semantics in
1158
rel = relpath(base, path)
1159
# '.' will have been turned into ''
1163
abs_base = abspath(base)
1165
_listdir = os.listdir
1167
# use an explicit iterator so we can easily consume the rest on early exit.
1168
bit_iter = iter(rel.split('/'))
1169
for bit in bit_iter:
1172
next_entries = _listdir(current)
1173
except OSError: # enoent, eperm, etc
1174
# We can't find this in the filesystem, so just append the
1176
current = pathjoin(current, bit, *list(bit_iter))
1178
for look in next_entries:
1179
if lbit == look.lower():
1180
current = pathjoin(current, look)
1183
# got to the end, nothing matched, so we just return the
1184
# non-existing bits as they were specified (the filename may be
1185
# the target of a move, for example).
1186
current = pathjoin(current, bit, *list(bit_iter))
1188
return current[len(abs_base):].lstrip('/')
1190
# XXX - TODO - we need better detection/integration of case-insensitive
1191
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1192
# filesystems), for example, so could probably benefit from the same basic
1193
# support there. For now though, only Windows and OSX get that support, and
1194
# they get it for *all* file-systems!
1195
if sys.platform in ('win32', 'darwin'):
1196
canonical_relpath = _cicp_canonical_relpath
1198
canonical_relpath = relpath
1200
def canonical_relpaths(base, paths):
1201
"""Create an iterable to canonicalize a sequence of relative paths.
1203
The intent is for this implementation to use a cache, vastly speeding
1204
up multiple transformations in the same directory.
1206
# but for now, we haven't optimized...
1207
return [canonical_relpath(base, p) for p in paths]
625
1209
def safe_unicode(unicode_or_utf8_string):
626
1210
"""Coerce unicode_or_utf8_string into unicode.
628
1212
If it is unicode, it is returned.
629
Otherwise it is decoded from utf-8. If a decoding error
630
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
631
as a BzrBadParameter exception.
1213
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1214
wrapped in a BzrBadParameterNotUnicode exception.
633
1216
if isinstance(unicode_or_utf8_string, unicode):
634
1217
return unicode_or_utf8_string
636
1219
return unicode_or_utf8_string.decode('utf8')
637
1220
except UnicodeDecodeError:
638
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
1221
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1224
def safe_utf8(unicode_or_utf8_string):
1225
"""Coerce unicode_or_utf8_string to a utf8 string.
1227
If it is a str, it is returned.
1228
If it is Unicode, it is encoded into a utf-8 string.
1230
if isinstance(unicode_or_utf8_string, str):
1231
# TODO: jam 20070209 This is overkill, and probably has an impact on
1232
# performance if we are dealing with lots of apis that want a
1235
# Make sure it is a valid utf-8 string
1236
unicode_or_utf8_string.decode('utf-8')
1237
except UnicodeDecodeError:
1238
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1239
return unicode_or_utf8_string
1240
return unicode_or_utf8_string.encode('utf-8')
1243
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1244
' Revision id generators should be creating utf8'
1248
def safe_revision_id(unicode_or_utf8_string, warn=True):
1249
"""Revision ids should now be utf8, but at one point they were unicode.
1251
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1253
:param warn: Functions that are sanitizing user data can set warn=False
1254
:return: None or a utf8 revision id.
1256
if (unicode_or_utf8_string is None
1257
or unicode_or_utf8_string.__class__ == str):
1258
return unicode_or_utf8_string
1260
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1262
return cache_utf8.encode(unicode_or_utf8_string)
1265
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1266
' generators should be creating utf8 file ids.')
1269
def safe_file_id(unicode_or_utf8_string, warn=True):
1270
"""File ids should now be utf8, but at one point they were unicode.
1272
This is the same as safe_utf8, except it uses the cached encode functions
1273
to save a little bit of performance.
1275
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1277
:param warn: Functions that are sanitizing user data can set warn=False
1278
:return: None or a utf8 file id.
1280
if (unicode_or_utf8_string is None
1281
or unicode_or_utf8_string.__class__ == str):
1282
return unicode_or_utf8_string
1284
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1286
return cache_utf8.encode(unicode_or_utf8_string)
1289
_platform_normalizes_filenames = False
1290
if sys.platform == 'darwin':
1291
_platform_normalizes_filenames = True
1294
def normalizes_filenames():
1295
"""Return True if this platform normalizes unicode filenames.
1297
Mac OSX does, Windows/Linux do not.
1299
return _platform_normalizes_filenames
1302
def _accessible_normalized_filename(path):
1303
"""Get the unicode normalized path, and if you can access the file.
1305
On platforms where the system normalizes filenames (Mac OSX),
1306
you can access a file by any path which will normalize correctly.
1307
On platforms where the system does not normalize filenames
1308
(Windows, Linux), you have to access a file by its exact path.
1310
Internally, bzr only supports NFC normalization, since that is
1311
the standard for XML documents.
1313
So return the normalized path, and a flag indicating if the file
1314
can be accessed by that path.
1317
return unicodedata.normalize('NFC', unicode(path)), True
1320
def _inaccessible_normalized_filename(path):
1321
__doc__ = _accessible_normalized_filename.__doc__
1323
normalized = unicodedata.normalize('NFC', unicode(path))
1324
return normalized, normalized == path
1327
if _platform_normalizes_filenames:
1328
normalized_filename = _accessible_normalized_filename
1330
normalized_filename = _inaccessible_normalized_filename
1333
default_terminal_width = 80
1334
"""The default terminal width for ttys.
1336
This is defined so that higher levels can share a common fallback value when
1337
terminal_width() returns None.
641
1341
def terminal_width():
642
"""Return estimated terminal width."""
644
# TODO: Do something smart on Windows?
646
# TODO: Is there anything that gets a better update when the window
647
# is resized while the program is running? We could use the Python termcap
650
return int(os.environ['COLUMNS'])
651
except (IndexError, KeyError, ValueError):
1342
"""Return terminal width.
1344
None is returned if the width can't established precisely.
1347
# If BZR_COLUMNS is set, take it, user is always right
1349
return int(os.environ['BZR_COLUMNS'])
1350
except (KeyError, ValueError):
1353
isatty = getattr(sys.stdout, 'isatty', None)
1354
if isatty is None or not isatty():
1355
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1358
if sys.platform == 'win32':
1359
return win32utils.get_console_size(defaultx=None)[0]
1362
import struct, fcntl, termios
1363
s = struct.pack('HHHH', 0, 0, 0, 0)
1364
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1365
width = struct.unpack('HHHH', x)[1]
1366
except (IOError, AttributeError):
1367
# If COLUMNS is set, take it
1369
return int(os.environ['COLUMNS'])
1370
except (KeyError, ValueError):
1374
# Consider invalid values as meaning no width
654
1380
def supports_executable():
655
1381
return sys.platform != "win32"
1384
def supports_posix_readonly():
1385
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1387
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1388
directory controls creation/deletion, etc.
1390
And under win32, readonly means that the directory itself cannot be
1391
deleted. The contents of a readonly directory can be changed, unlike POSIX
1392
where files in readonly directories cannot be added, deleted or renamed.
1394
return sys.platform != "win32"
1397
def set_or_unset_env(env_variable, value):
1398
"""Modify the environment, setting or removing the env_variable.
1400
:param env_variable: The environment variable in question
1401
:param value: The value to set the environment to. If None, then
1402
the variable will be removed.
1403
:return: The original value of the environment variable.
1405
orig_val = os.environ.get(env_variable)
1407
if orig_val is not None:
1408
del os.environ[env_variable]
1410
if isinstance(value, unicode):
1411
value = value.encode(get_user_encoding())
1412
os.environ[env_variable] = value
1416
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1419
def check_legal_path(path):
1420
"""Check whether the supplied path is legal.
1421
This is only required on Windows, so we don't test on other platforms
1424
if sys.platform != "win32":
1426
if _validWin32PathRE.match(path) is None:
1427
raise errors.IllegalPath(path)
1430
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1432
def _is_error_enotdir(e):
1433
"""Check if this exception represents ENOTDIR.
1435
Unfortunately, python is very inconsistent about the exception
1436
here. The cases are:
1437
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1438
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1439
which is the windows error code.
1440
3) Windows, Python2.5 uses errno == EINVAL and
1441
winerror == ERROR_DIRECTORY
1443
:param e: An Exception object (expected to be OSError with an errno
1444
attribute, but we should be able to cope with anything)
1445
:return: True if this represents an ENOTDIR error. False otherwise.
1447
en = getattr(e, 'errno', None)
1448
if (en == errno.ENOTDIR
1449
or (sys.platform == 'win32'
1450
and (en == _WIN32_ERROR_DIRECTORY
1451
or (en == errno.EINVAL
1452
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1458
def walkdirs(top, prefix=""):
1459
"""Yield data about all the directories in a tree.
1461
This yields all the data about the contents of a directory at a time.
1462
After each directory has been yielded, if the caller has mutated the list
1463
to exclude some directories, they are then not descended into.
1465
The data yielded is of the form:
1466
((directory-relpath, directory-path-from-top),
1467
[(relpath, basename, kind, lstat, path-from-top), ...]),
1468
- directory-relpath is the relative path of the directory being returned
1469
with respect to top. prefix is prepended to this.
1470
- directory-path-from-root is the path including top for this directory.
1471
It is suitable for use with os functions.
1472
- relpath is the relative path within the subtree being walked.
1473
- basename is the basename of the path
1474
- kind is the kind of the file now. If unknown then the file is not
1475
present within the tree - but it may be recorded as versioned. See
1477
- lstat is the stat data *if* the file was statted.
1478
- planned, not implemented:
1479
path_from_tree_root is the path from the root of the tree.
1481
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1482
allows one to walk a subtree but get paths that are relative to a tree
1484
:return: an iterator over the dirs.
1486
#TODO there is a bit of a smell where the results of the directory-
1487
# summary in this, and the path from the root, may not agree
1488
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1489
# potentially confusing output. We should make this more robust - but
1490
# not at a speed cost. RBC 20060731
1492
_directory = _directory_kind
1493
_listdir = os.listdir
1494
_kind_from_mode = file_kind_from_stat_mode
1495
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1497
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1498
relroot, _, _, _, top = pending.pop()
1500
relprefix = relroot + u'/'
1503
top_slash = top + u'/'
1506
append = dirblock.append
1508
names = sorted(_listdir(top))
1510
if not _is_error_enotdir(e):
1514
abspath = top_slash + name
1515
statvalue = _lstat(abspath)
1516
kind = _kind_from_mode(statvalue.st_mode)
1517
append((relprefix + name, name, kind, statvalue, abspath))
1518
yield (relroot, top), dirblock
1520
# push the user specified dirs from dirblock
1521
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1524
class DirReader(object):
1525
"""An interface for reading directories."""
1527
def top_prefix_to_starting_dir(self, top, prefix=""):
1528
"""Converts top and prefix to a starting dir entry
1530
:param top: A utf8 path
1531
:param prefix: An optional utf8 path to prefix output relative paths
1533
:return: A tuple starting with prefix, and ending with the native
1536
raise NotImplementedError(self.top_prefix_to_starting_dir)
1538
def read_dir(self, prefix, top):
1539
"""Read a specific dir.
1541
:param prefix: A utf8 prefix to be preprended to the path basenames.
1542
:param top: A natively encoded path to read.
1543
:return: A list of the directories contents. Each item contains:
1544
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1546
raise NotImplementedError(self.read_dir)
1549
_selected_dir_reader = None
1552
def _walkdirs_utf8(top, prefix=""):
1553
"""Yield data about all the directories in a tree.
1555
This yields the same information as walkdirs() only each entry is yielded
1556
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1557
are returned as exact byte-strings.
1559
:return: yields a tuple of (dir_info, [file_info])
1560
dir_info is (utf8_relpath, path-from-top)
1561
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1562
if top is an absolute path, path-from-top is also an absolute path.
1563
path-from-top might be unicode or utf8, but it is the correct path to
1564
pass to os functions to affect the file in question. (such as os.lstat)
1566
global _selected_dir_reader
1567
if _selected_dir_reader is None:
1568
fs_encoding = _fs_enc.upper()
1569
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1570
# Win98 doesn't have unicode apis like FindFirstFileW
1571
# TODO: We possibly could support Win98 by falling back to the
1572
# original FindFirstFile, and using TCHAR instead of WCHAR,
1573
# but that gets a bit tricky, and requires custom compiling
1576
from bzrlib._walkdirs_win32 import Win32ReadDir
1577
_selected_dir_reader = Win32ReadDir()
1580
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1581
# ANSI_X3.4-1968 is a form of ASCII
1583
from bzrlib._readdir_pyx import UTF8DirReader
1584
_selected_dir_reader = UTF8DirReader()
1585
except ImportError, e:
1586
failed_to_load_extension(e)
1589
if _selected_dir_reader is None:
1590
# Fallback to the python version
1591
_selected_dir_reader = UnicodeDirReader()
1593
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1594
# But we don't actually uses 1-3 in pending, so set them to None
1595
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1596
read_dir = _selected_dir_reader.read_dir
1597
_directory = _directory_kind
1599
relroot, _, _, _, top = pending[-1].pop()
1602
dirblock = sorted(read_dir(relroot, top))
1603
yield (relroot, top), dirblock
1604
# push the user specified dirs from dirblock
1605
next = [d for d in reversed(dirblock) if d[2] == _directory]
1607
pending.append(next)
1610
class UnicodeDirReader(DirReader):
1611
"""A dir reader for non-utf8 file systems, which transcodes."""
1613
__slots__ = ['_utf8_encode']
1616
self._utf8_encode = codecs.getencoder('utf8')
1618
def top_prefix_to_starting_dir(self, top, prefix=""):
1619
"""See DirReader.top_prefix_to_starting_dir."""
1620
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1622
def read_dir(self, prefix, top):
1623
"""Read a single directory from a non-utf8 file system.
1625
top, and the abspath element in the output are unicode, all other paths
1626
are utf8. Local disk IO is done via unicode calls to listdir etc.
1628
This is currently the fallback code path when the filesystem encoding is
1629
not UTF-8. It may be better to implement an alternative so that we can
1630
safely handle paths that are not properly decodable in the current
1633
See DirReader.read_dir for details.
1635
_utf8_encode = self._utf8_encode
1637
_listdir = os.listdir
1638
_kind_from_mode = file_kind_from_stat_mode
1641
relprefix = prefix + '/'
1644
top_slash = top + u'/'
1647
append = dirblock.append
1648
for name in sorted(_listdir(top)):
1650
name_utf8 = _utf8_encode(name)[0]
1651
except UnicodeDecodeError:
1652
raise errors.BadFilenameEncoding(
1653
_utf8_encode(relprefix)[0] + name, _fs_enc)
1654
abspath = top_slash + name
1655
statvalue = _lstat(abspath)
1656
kind = _kind_from_mode(statvalue.st_mode)
1657
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1661
def copy_tree(from_path, to_path, handlers={}):
1662
"""Copy all of the entries in from_path into to_path.
1664
:param from_path: The base directory to copy.
1665
:param to_path: The target directory. If it does not exist, it will
1667
:param handlers: A dictionary of functions, which takes a source and
1668
destinations for files, directories, etc.
1669
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1670
'file', 'directory', and 'symlink' should always exist.
1671
If they are missing, they will be replaced with 'os.mkdir()',
1672
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1674
# Now, just copy the existing cached tree to the new location
1675
# We use a cheap trick here.
1676
# Absolute paths are prefixed with the first parameter
1677
# relative paths are prefixed with the second.
1678
# So we can get both the source and target returned
1679
# without any extra work.
1681
def copy_dir(source, dest):
1684
def copy_link(source, dest):
1685
"""Copy the contents of a symlink"""
1686
link_to = os.readlink(source)
1687
os.symlink(link_to, dest)
1689
real_handlers = {'file':shutil.copy2,
1690
'symlink':copy_link,
1691
'directory':copy_dir,
1693
real_handlers.update(handlers)
1695
if not os.path.exists(to_path):
1696
real_handlers['directory'](from_path, to_path)
1698
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1699
for relpath, name, kind, st, abspath in entries:
1700
real_handlers[kind](abspath, relpath)
1703
def path_prefix_key(path):
1704
"""Generate a prefix-order path key for path.
1706
This can be used to sort paths in the same way that walkdirs does.
1708
return (dirname(path) , path)
1711
def compare_paths_prefix_order(path_a, path_b):
1712
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1713
key_a = path_prefix_key(path_a)
1714
key_b = path_prefix_key(path_b)
1715
return cmp(key_a, key_b)
1718
_cached_user_encoding = None
1721
def get_user_encoding(use_cache=True):
1722
"""Find out what the preferred user encoding is.
1724
This is generally the encoding that is used for command line parameters
1725
and file contents. This may be different from the terminal encoding
1726
or the filesystem encoding.
1728
:param use_cache: Enable cache for detected encoding.
1729
(This parameter is turned on by default,
1730
and required only for selftesting)
1732
:return: A string defining the preferred user encoding
1734
global _cached_user_encoding
1735
if _cached_user_encoding is not None and use_cache:
1736
return _cached_user_encoding
1738
if sys.platform == 'darwin':
1739
# python locale.getpreferredencoding() always return
1740
# 'mac-roman' on darwin. That's a lie.
1741
sys.platform = 'posix'
1743
if os.environ.get('LANG', None) is None:
1744
# If LANG is not set, we end up with 'ascii', which is bad
1745
# ('mac-roman' is more than ascii), so we set a default which
1746
# will give us UTF-8 (which appears to work in all cases on
1747
# OSX). Users are still free to override LANG of course, as
1748
# long as it give us something meaningful. This work-around
1749
# *may* not be needed with python 3k and/or OSX 10.5, but will
1750
# work with them too -- vila 20080908
1751
os.environ['LANG'] = 'en_US.UTF-8'
1754
sys.platform = 'darwin'
1759
user_encoding = locale.getpreferredencoding()
1760
except locale.Error, e:
1761
sys.stderr.write('bzr: warning: %s\n'
1762
' Could not determine what text encoding to use.\n'
1763
' This error usually means your Python interpreter\n'
1764
' doesn\'t support the locale set by $LANG (%s)\n'
1765
" Continuing with ascii encoding.\n"
1766
% (e, os.environ.get('LANG')))
1767
user_encoding = 'ascii'
1769
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1770
# treat that as ASCII, and not support printing unicode characters to the
1773
# For python scripts run under vim, we get '', so also treat that as ASCII
1774
if user_encoding in (None, 'cp0', ''):
1775
user_encoding = 'ascii'
1779
codecs.lookup(user_encoding)
1781
sys.stderr.write('bzr: warning:'
1782
' unknown encoding %s.'
1783
' Continuing with ascii encoding.\n'
1786
user_encoding = 'ascii'
1789
_cached_user_encoding = user_encoding
1791
return user_encoding
1794
def get_host_name():
1795
"""Return the current unicode host name.
1797
This is meant to be used in place of socket.gethostname() because that
1798
behaves inconsistently on different platforms.
1800
if sys.platform == "win32":
1802
return win32utils.get_host_name()
1805
return socket.gethostname().decode(get_user_encoding())
1808
def recv_all(socket, bytes):
1809
"""Receive an exact number of bytes.
1811
Regular Socket.recv() may return less than the requested number of bytes,
1812
dependning on what's in the OS buffer. MSG_WAITALL is not available
1813
on all platforms, but this should work everywhere. This will return
1814
less than the requested amount if the remote end closes.
1816
This isn't optimized and is intended mostly for use in testing.
1819
while len(b) < bytes:
1820
new = until_no_eintr(socket.recv, bytes - len(b))
1827
def send_all(socket, bytes, report_activity=None):
1828
"""Send all bytes on a socket.
1830
Regular socket.sendall() can give socket error 10053 on Windows. This
1831
implementation sends no more than 64k at a time, which avoids this problem.
1833
:param report_activity: Call this as bytes are read, see
1834
Transport._report_activity
1837
for pos in xrange(0, len(bytes), chunk_size):
1838
block = bytes[pos:pos+chunk_size]
1839
if report_activity is not None:
1840
report_activity(len(block), 'write')
1841
until_no_eintr(socket.sendall, block)
1844
def dereference_path(path):
1845
"""Determine the real path to a file.
1847
All parent elements are dereferenced. But the file itself is not
1849
:param path: The original path. May be absolute or relative.
1850
:return: the real path *to* the file
1852
parent, base = os.path.split(path)
1853
# The pathjoin for '.' is a workaround for Python bug #1213894.
1854
# (initial path components aren't dereferenced)
1855
return pathjoin(realpath(pathjoin('.', parent)), base)
1858
def supports_mapi():
1859
"""Return True if we can use MAPI to launch a mail client."""
1860
return sys.platform == "win32"
1863
def resource_string(package, resource_name):
1864
"""Load a resource from a package and return it as a string.
1866
Note: Only packages that start with bzrlib are currently supported.
1868
This is designed to be a lightweight implementation of resource
1869
loading in a way which is API compatible with the same API from
1871
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1872
If and when pkg_resources becomes a standard library, this routine
1875
# Check package name is within bzrlib
1876
if package == "bzrlib":
1877
resource_relpath = resource_name
1878
elif package.startswith("bzrlib."):
1879
package = package[len("bzrlib."):].replace('.', os.sep)
1880
resource_relpath = pathjoin(package, resource_name)
1882
raise errors.BzrError('resource package %s not in bzrlib' % package)
1884
# Map the resource to a file and read its contents
1885
base = dirname(bzrlib.__file__)
1886
if getattr(sys, 'frozen', None): # bzr.exe
1887
base = abspath(pathjoin(base, '..', '..'))
1888
filename = pathjoin(base, resource_relpath)
1889
return open(filename, 'rU').read()
1892
def file_kind_from_stat_mode_thunk(mode):
1893
global file_kind_from_stat_mode
1894
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1896
from bzrlib._readdir_pyx import UTF8DirReader
1897
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1898
except ImportError, e:
1899
# This is one time where we won't warn that an extension failed to
1900
# load. The extension is never available on Windows anyway.
1901
from bzrlib._readdir_py import (
1902
_kind_from_mode as file_kind_from_stat_mode
1904
return file_kind_from_stat_mode(mode)
1905
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1908
def file_kind(f, _lstat=os.lstat):
1910
return file_kind_from_stat_mode(_lstat(f).st_mode)
1912
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1913
raise errors.NoSuchFile(f)
1917
def until_no_eintr(f, *a, **kw):
1918
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1919
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1923
except (IOError, OSError), e:
1924
if e.errno == errno.EINTR:
1928
def re_compile_checked(re_string, flags=0, where=""):
1929
"""Return a compiled re, or raise a sensible error.
1931
This should only be used when compiling user-supplied REs.
1933
:param re_string: Text form of regular expression.
1934
:param flags: eg re.IGNORECASE
1935
:param where: Message explaining to the user the context where
1936
it occurred, eg 'log search filter'.
1938
# from https://bugs.launchpad.net/bzr/+bug/251352
1940
re_obj = re.compile(re_string, flags)
1945
where = ' in ' + where
1946
# despite the name 'error' is a type
1947
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1948
% (where, re_string, e))
1951
if sys.platform == "win32":
1954
return msvcrt.getch()
1959
fd = sys.stdin.fileno()
1960
settings = termios.tcgetattr(fd)
1963
ch = sys.stdin.read(1)
1965
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1969
if sys.platform == 'linux2':
1970
def _local_concurrency():
1972
prefix = 'processor'
1973
for line in file('/proc/cpuinfo', 'rb'):
1974
if line.startswith(prefix):
1975
concurrency = int(line[line.find(':')+1:]) + 1
1977
elif sys.platform == 'darwin':
1978
def _local_concurrency():
1979
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
1980
stdout=subprocess.PIPE).communicate()[0]
1981
elif sys.platform[0:7] == 'freebsd':
1982
def _local_concurrency():
1983
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
1984
stdout=subprocess.PIPE).communicate()[0]
1985
elif sys.platform == 'sunos5':
1986
def _local_concurrency():
1987
return subprocess.Popen(['psrinfo', '-p',],
1988
stdout=subprocess.PIPE).communicate()[0]
1989
elif sys.platform == "win32":
1990
def _local_concurrency():
1991
# This appears to return the number of cores.
1992
return os.environ.get('NUMBER_OF_PROCESSORS')
1994
def _local_concurrency():
1999
_cached_local_concurrency = None
2001
def local_concurrency(use_cache=True):
2002
"""Return how many processes can be run concurrently.
2004
Rely on platform specific implementations and default to 1 (one) if
2005
anything goes wrong.
2007
global _cached_local_concurrency
2009
if _cached_local_concurrency is not None and use_cache:
2010
return _cached_local_concurrency
2012
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2013
if concurrency is None:
2015
concurrency = _local_concurrency()
2016
except (OSError, IOError):
2019
concurrency = int(concurrency)
2020
except (TypeError, ValueError):
2023
_cached_concurrency = concurrency