171
247
rename_func(tmp_name, new)
173
# Default is to just use the python builtins
174
abspath = os.path.abspath
175
realpath = os.path.realpath
250
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
251
# choke on a Unicode string containing a relative path if
252
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
254
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
255
def _posix_abspath(path):
256
# jam 20060426 rather than encoding to fsencoding
257
# copy posixpath.abspath, but use os.getcwdu instead
258
if not posixpath.isabs(path):
259
path = posixpath.join(getcwd(), path)
260
return posixpath.normpath(path)
263
def _posix_realpath(path):
264
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
267
def _win32_fixdrive(path):
268
"""Force drive letters to be consistent.
270
win32 is inconsistent whether it returns lower or upper case
271
and even if it was consistent the user might type the other
272
so we force it to uppercase
273
running python.exe under cmd.exe return capital C:\\
274
running win32 python inside a cygwin shell returns lowercase c:\\
276
drive, path = _nt_splitdrive(path)
277
return drive.upper() + path
280
def _win32_abspath(path):
281
# Real _nt_abspath doesn't have a problem with a unicode cwd
282
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
285
def _win98_abspath(path):
286
"""Return the absolute version of a path.
287
Windows 98 safe implementation (python reimplementation
288
of Win32 API function GetFullPathNameW)
293
# \\HOST\path => //HOST/path
294
# //HOST/path => //HOST/path
295
# path => C:/cwd/path
298
# check for absolute path
299
drive = _nt_splitdrive(path)[0]
300
if drive == '' and path[:2] not in('//','\\\\'):
302
# we cannot simply os.path.join cwd and path
303
# because os.path.join('C:','/path') produce '/path'
304
# and this is incorrect
305
if path[:1] in ('/','\\'):
306
cwd = _nt_splitdrive(cwd)[0]
308
path = cwd + '\\' + path
309
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
312
def _win32_realpath(path):
313
# Real _nt_realpath doesn't have a problem with a unicode cwd
314
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
317
def _win32_pathjoin(*args):
318
return _nt_join(*args).replace('\\', '/')
321
def _win32_normpath(path):
322
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
326
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
329
def _win32_mkdtemp(*args, **kwargs):
330
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
333
def _win32_rename(old, new):
334
"""We expect to be able to atomically replace 'new' with old.
336
On win32, if new exists, it must be moved out of the way first,
340
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
342
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
343
# If we try to rename a non-existant file onto cwd, we get
344
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
345
# if the old path doesn't exist, sometimes we get EACCES
346
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
352
return unicodedata.normalize('NFC', os.getcwdu())
355
# Default is to just use the python builtins, but these can be rebound on
356
# particular platforms.
357
abspath = _posix_abspath
358
realpath = _posix_realpath
176
359
pathjoin = os.path.join
177
360
normpath = os.path.normpath
178
361
getcwd = os.getcwdu
179
mkdtemp = tempfile.mkdtemp
180
362
rename = os.rename
181
363
dirname = os.path.dirname
182
364
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)
365
split = os.path.split
366
splitext = os.path.splitext
367
# These were already imported into local scope
368
# mkdtemp = tempfile.mkdtemp
369
# rmtree = shutil.rmtree
371
MIN_ABS_PATHLENGTH = 1
196
374
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)
375
if win32utils.winver == 'Windows 98':
376
abspath = _win98_abspath
378
abspath = _win32_abspath
379
realpath = _win32_realpath
380
pathjoin = _win32_pathjoin
381
normpath = _win32_normpath
382
getcwd = _win32_getcwd
383
mkdtemp = _win32_mkdtemp
384
rename = _win32_rename
386
MIN_ABS_PATHLENGTH = 3
388
def _win32_delete_readonly(function, path, excinfo):
389
"""Error handler for shutil.rmtree function [for win32]
390
Helps to remove files and dirs marked as read-only.
392
exception = excinfo[1]
393
if function in (os.remove, os.rmdir) \
394
and isinstance(exception, OSError) \
395
and exception.errno == errno.EACCES:
401
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
402
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
403
return shutil.rmtree(path, ignore_errors, onerror)
405
f = win32utils.get_unicode_argv # special function or None
409
elif sys.platform == 'darwin':
413
def get_terminal_encoding():
414
"""Find the best encoding for printing to the screen.
416
This attempts to check both sys.stdout and sys.stdin to see
417
what encoding they are in, and if that fails it falls back to
418
osutils.get_user_encoding().
419
The problem is that on Windows, locale.getpreferredencoding()
420
is not the same encoding as that used by the console:
421
http://mail.python.org/pipermail/python-list/2003-May/162357.html
423
On my standard US Windows XP, the preferred encoding is
424
cp1252, but the console is cp437
426
from bzrlib.trace import mutter
427
output_encoding = getattr(sys.stdout, 'encoding', None)
428
if not output_encoding:
429
input_encoding = getattr(sys.stdin, 'encoding', None)
430
if not input_encoding:
431
output_encoding = get_user_encoding()
432
mutter('encoding stdout as osutils.get_user_encoding() %r',
435
output_encoding = input_encoding
436
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
438
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
439
if output_encoding == 'cp0':
440
# invalid encoding (cp0 means 'no codepage' on Windows)
441
output_encoding = get_user_encoding()
442
mutter('cp0 is invalid encoding.'
443
' encoding stdout as osutils.get_user_encoding() %r',
447
codecs.lookup(output_encoding)
449
sys.stderr.write('bzr: warning:'
450
' unknown terminal encoding %s.\n'
451
' Using encoding %s instead.\n'
452
% (output_encoding, get_user_encoding())
454
output_encoding = get_user_encoding()
456
return output_encoding
221
459
def normalizepath(f):
222
if hasattr(os.path, 'realpath'):
460
if getattr(os.path, 'realpath', None) is not None:
595
1079
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
596
1080
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)
1083
if len(base) < MIN_ABS_PATHLENGTH:
1084
# must have space for e.g. a drive letter
1085
raise ValueError('%r is too short to calculate a relative path'
604
1088
rp = abspath(path)
608
while len(head) >= len(base):
1093
if len(head) <= len(base) and head != base:
1094
raise errors.PathNotChild(rp, base)
609
1095
if head == base:
611
head, tail = os.path.split(head)
1097
head, tail = split(head)
615
# XXX This should raise a NotChildPath exception, as its not tied
617
raise PathNotChild(rp, base)
1102
return pathjoin(*reversed(s))
1107
def _cicp_canonical_relpath(base, path):
1108
"""Return the canonical path relative to base.
1110
Like relpath, but on case-insensitive-case-preserving file-systems, this
1111
will return the relpath as stored on the file-system rather than in the
1112
case specified in the input string, for all existing portions of the path.
1114
This will cause O(N) behaviour if called for every path in a tree; if you
1115
have a number of paths to convert, you should use canonical_relpaths().
1117
# TODO: it should be possible to optimize this for Windows by using the
1118
# win32 API FindFiles function to look for the specified name - but using
1119
# os.listdir() still gives us the correct, platform agnostic semantics in
1122
rel = relpath(base, path)
1123
# '.' will have been turned into ''
1127
abs_base = abspath(base)
1129
_listdir = os.listdir
1131
# use an explicit iterator so we can easily consume the rest on early exit.
1132
bit_iter = iter(rel.split('/'))
1133
for bit in bit_iter:
1136
next_entries = _listdir(current)
1137
except OSError: # enoent, eperm, etc
1138
# We can't find this in the filesystem, so just append the
1140
current = pathjoin(current, bit, *list(bit_iter))
1142
for look in next_entries:
1143
if lbit == look.lower():
1144
current = pathjoin(current, look)
1147
# got to the end, nothing matched, so we just return the
1148
# non-existing bits as they were specified (the filename may be
1149
# the target of a move, for example).
1150
current = pathjoin(current, bit, *list(bit_iter))
1152
return current[len(abs_base):].lstrip('/')
1154
# XXX - TODO - we need better detection/integration of case-insensitive
1155
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1156
# filesystems), for example, so could probably benefit from the same basic
1157
# support there. For now though, only Windows and OSX get that support, and
1158
# they get it for *all* file-systems!
1159
if sys.platform in ('win32', 'darwin'):
1160
canonical_relpath = _cicp_canonical_relpath
1162
canonical_relpath = relpath
1164
def canonical_relpaths(base, paths):
1165
"""Create an iterable to canonicalize a sequence of relative paths.
1167
The intent is for this implementation to use a cache, vastly speeding
1168
up multiple transformations in the same directory.
1170
# but for now, we haven't optimized...
1171
return [canonical_relpath(base, p) for p in paths]
625
1173
def safe_unicode(unicode_or_utf8_string):
626
1174
"""Coerce unicode_or_utf8_string into unicode.
628
1176
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.
1177
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1178
wrapped in a BzrBadParameterNotUnicode exception.
633
1180
if isinstance(unicode_or_utf8_string, unicode):
634
1181
return unicode_or_utf8_string
636
1183
return unicode_or_utf8_string.decode('utf8')
637
1184
except UnicodeDecodeError:
638
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
1185
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1188
def safe_utf8(unicode_or_utf8_string):
1189
"""Coerce unicode_or_utf8_string to a utf8 string.
1191
If it is a str, it is returned.
1192
If it is Unicode, it is encoded into a utf-8 string.
1194
if isinstance(unicode_or_utf8_string, str):
1195
# TODO: jam 20070209 This is overkill, and probably has an impact on
1196
# performance if we are dealing with lots of apis that want a
1199
# Make sure it is a valid utf-8 string
1200
unicode_or_utf8_string.decode('utf-8')
1201
except UnicodeDecodeError:
1202
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1203
return unicode_or_utf8_string
1204
return unicode_or_utf8_string.encode('utf-8')
1207
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1208
' Revision id generators should be creating utf8'
1212
def safe_revision_id(unicode_or_utf8_string, warn=True):
1213
"""Revision ids should now be utf8, but at one point they were unicode.
1215
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1217
:param warn: Functions that are sanitizing user data can set warn=False
1218
:return: None or a utf8 revision id.
1220
if (unicode_or_utf8_string is None
1221
or unicode_or_utf8_string.__class__ == str):
1222
return unicode_or_utf8_string
1224
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1226
return cache_utf8.encode(unicode_or_utf8_string)
1229
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1230
' generators should be creating utf8 file ids.')
1233
def safe_file_id(unicode_or_utf8_string, warn=True):
1234
"""File ids should now be utf8, but at one point they were unicode.
1236
This is the same as safe_utf8, except it uses the cached encode functions
1237
to save a little bit of performance.
1239
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1241
:param warn: Functions that are sanitizing user data can set warn=False
1242
:return: None or a utf8 file id.
1244
if (unicode_or_utf8_string is None
1245
or unicode_or_utf8_string.__class__ == str):
1246
return unicode_or_utf8_string
1248
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1250
return cache_utf8.encode(unicode_or_utf8_string)
1253
_platform_normalizes_filenames = False
1254
if sys.platform == 'darwin':
1255
_platform_normalizes_filenames = True
1258
def normalizes_filenames():
1259
"""Return True if this platform normalizes unicode filenames.
1261
Mac OSX does, Windows/Linux do not.
1263
return _platform_normalizes_filenames
1266
def _accessible_normalized_filename(path):
1267
"""Get the unicode normalized path, and if you can access the file.
1269
On platforms where the system normalizes filenames (Mac OSX),
1270
you can access a file by any path which will normalize correctly.
1271
On platforms where the system does not normalize filenames
1272
(Windows, Linux), you have to access a file by its exact path.
1274
Internally, bzr only supports NFC normalization, since that is
1275
the standard for XML documents.
1277
So return the normalized path, and a flag indicating if the file
1278
can be accessed by that path.
1281
return unicodedata.normalize('NFC', unicode(path)), True
1284
def _inaccessible_normalized_filename(path):
1285
__doc__ = _accessible_normalized_filename.__doc__
1287
normalized = unicodedata.normalize('NFC', unicode(path))
1288
return normalized, normalized == path
1291
if _platform_normalizes_filenames:
1292
normalized_filename = _accessible_normalized_filename
1294
normalized_filename = _inaccessible_normalized_filename
641
1297
def terminal_width():
642
1298
"""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
1299
if sys.platform == 'win32':
1300
return win32utils.get_console_size()[0]
650
return int(os.environ['COLUMNS'])
651
except (IndexError, KeyError, ValueError):
1303
import struct, fcntl, termios
1304
s = struct.pack('HHHH', 0, 0, 0, 0)
1305
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1306
width = struct.unpack('HHHH', x)[1]
1311
width = int(os.environ['COLUMNS'])
654
1320
def supports_executable():
655
1321
return sys.platform != "win32"
1324
def supports_posix_readonly():
1325
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1327
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1328
directory controls creation/deletion, etc.
1330
And under win32, readonly means that the directory itself cannot be
1331
deleted. The contents of a readonly directory can be changed, unlike POSIX
1332
where files in readonly directories cannot be added, deleted or renamed.
1334
return sys.platform != "win32"
1337
def set_or_unset_env(env_variable, value):
1338
"""Modify the environment, setting or removing the env_variable.
1340
:param env_variable: The environment variable in question
1341
:param value: The value to set the environment to. If None, then
1342
the variable will be removed.
1343
:return: The original value of the environment variable.
1345
orig_val = os.environ.get(env_variable)
1347
if orig_val is not None:
1348
del os.environ[env_variable]
1350
if isinstance(value, unicode):
1351
value = value.encode(get_user_encoding())
1352
os.environ[env_variable] = value
1356
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1359
def check_legal_path(path):
1360
"""Check whether the supplied path is legal.
1361
This is only required on Windows, so we don't test on other platforms
1364
if sys.platform != "win32":
1366
if _validWin32PathRE.match(path) is None:
1367
raise errors.IllegalPath(path)
1370
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1372
def _is_error_enotdir(e):
1373
"""Check if this exception represents ENOTDIR.
1375
Unfortunately, python is very inconsistent about the exception
1376
here. The cases are:
1377
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1378
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1379
which is the windows error code.
1380
3) Windows, Python2.5 uses errno == EINVAL and
1381
winerror == ERROR_DIRECTORY
1383
:param e: An Exception object (expected to be OSError with an errno
1384
attribute, but we should be able to cope with anything)
1385
:return: True if this represents an ENOTDIR error. False otherwise.
1387
en = getattr(e, 'errno', None)
1388
if (en == errno.ENOTDIR
1389
or (sys.platform == 'win32'
1390
and (en == _WIN32_ERROR_DIRECTORY
1391
or (en == errno.EINVAL
1392
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1398
def walkdirs(top, prefix=""):
1399
"""Yield data about all the directories in a tree.
1401
This yields all the data about the contents of a directory at a time.
1402
After each directory has been yielded, if the caller has mutated the list
1403
to exclude some directories, they are then not descended into.
1405
The data yielded is of the form:
1406
((directory-relpath, directory-path-from-top),
1407
[(relpath, basename, kind, lstat, path-from-top), ...]),
1408
- directory-relpath is the relative path of the directory being returned
1409
with respect to top. prefix is prepended to this.
1410
- directory-path-from-root is the path including top for this directory.
1411
It is suitable for use with os functions.
1412
- relpath is the relative path within the subtree being walked.
1413
- basename is the basename of the path
1414
- kind is the kind of the file now. If unknown then the file is not
1415
present within the tree - but it may be recorded as versioned. See
1417
- lstat is the stat data *if* the file was statted.
1418
- planned, not implemented:
1419
path_from_tree_root is the path from the root of the tree.
1421
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1422
allows one to walk a subtree but get paths that are relative to a tree
1424
:return: an iterator over the dirs.
1426
#TODO there is a bit of a smell where the results of the directory-
1427
# summary in this, and the path from the root, may not agree
1428
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1429
# potentially confusing output. We should make this more robust - but
1430
# not at a speed cost. RBC 20060731
1432
_directory = _directory_kind
1433
_listdir = os.listdir
1434
_kind_from_mode = file_kind_from_stat_mode
1435
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1437
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1438
relroot, _, _, _, top = pending.pop()
1440
relprefix = relroot + u'/'
1443
top_slash = top + u'/'
1446
append = dirblock.append
1448
names = sorted(_listdir(top))
1450
if not _is_error_enotdir(e):
1454
abspath = top_slash + name
1455
statvalue = _lstat(abspath)
1456
kind = _kind_from_mode(statvalue.st_mode)
1457
append((relprefix + name, name, kind, statvalue, abspath))
1458
yield (relroot, top), dirblock
1460
# push the user specified dirs from dirblock
1461
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1464
class DirReader(object):
1465
"""An interface for reading directories."""
1467
def top_prefix_to_starting_dir(self, top, prefix=""):
1468
"""Converts top and prefix to a starting dir entry
1470
:param top: A utf8 path
1471
:param prefix: An optional utf8 path to prefix output relative paths
1473
:return: A tuple starting with prefix, and ending with the native
1476
raise NotImplementedError(self.top_prefix_to_starting_dir)
1478
def read_dir(self, prefix, top):
1479
"""Read a specific dir.
1481
:param prefix: A utf8 prefix to be preprended to the path basenames.
1482
:param top: A natively encoded path to read.
1483
:return: A list of the directories contents. Each item contains:
1484
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1486
raise NotImplementedError(self.read_dir)
1489
_selected_dir_reader = None
1492
def _walkdirs_utf8(top, prefix=""):
1493
"""Yield data about all the directories in a tree.
1495
This yields the same information as walkdirs() only each entry is yielded
1496
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1497
are returned as exact byte-strings.
1499
:return: yields a tuple of (dir_info, [file_info])
1500
dir_info is (utf8_relpath, path-from-top)
1501
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1502
if top is an absolute path, path-from-top is also an absolute path.
1503
path-from-top might be unicode or utf8, but it is the correct path to
1504
pass to os functions to affect the file in question. (such as os.lstat)
1506
global _selected_dir_reader
1507
if _selected_dir_reader is None:
1508
fs_encoding = _fs_enc.upper()
1509
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1510
# Win98 doesn't have unicode apis like FindFirstFileW
1511
# TODO: We possibly could support Win98 by falling back to the
1512
# original FindFirstFile, and using TCHAR instead of WCHAR,
1513
# but that gets a bit tricky, and requires custom compiling
1516
from bzrlib._walkdirs_win32 import Win32ReadDir
1517
_selected_dir_reader = Win32ReadDir()
1520
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1521
# ANSI_X3.4-1968 is a form of ASCII
1523
from bzrlib._readdir_pyx import UTF8DirReader
1524
_selected_dir_reader = UTF8DirReader()
1525
except ImportError, e:
1526
failed_to_load_extension(e)
1529
if _selected_dir_reader is None:
1530
# Fallback to the python version
1531
_selected_dir_reader = UnicodeDirReader()
1533
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1534
# But we don't actually uses 1-3 in pending, so set them to None
1535
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1536
read_dir = _selected_dir_reader.read_dir
1537
_directory = _directory_kind
1539
relroot, _, _, _, top = pending[-1].pop()
1542
dirblock = sorted(read_dir(relroot, top))
1543
yield (relroot, top), dirblock
1544
# push the user specified dirs from dirblock
1545
next = [d for d in reversed(dirblock) if d[2] == _directory]
1547
pending.append(next)
1550
class UnicodeDirReader(DirReader):
1551
"""A dir reader for non-utf8 file systems, which transcodes."""
1553
__slots__ = ['_utf8_encode']
1556
self._utf8_encode = codecs.getencoder('utf8')
1558
def top_prefix_to_starting_dir(self, top, prefix=""):
1559
"""See DirReader.top_prefix_to_starting_dir."""
1560
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1562
def read_dir(self, prefix, top):
1563
"""Read a single directory from a non-utf8 file system.
1565
top, and the abspath element in the output are unicode, all other paths
1566
are utf8. Local disk IO is done via unicode calls to listdir etc.
1568
This is currently the fallback code path when the filesystem encoding is
1569
not UTF-8. It may be better to implement an alternative so that we can
1570
safely handle paths that are not properly decodable in the current
1573
See DirReader.read_dir for details.
1575
_utf8_encode = self._utf8_encode
1577
_listdir = os.listdir
1578
_kind_from_mode = file_kind_from_stat_mode
1581
relprefix = prefix + '/'
1584
top_slash = top + u'/'
1587
append = dirblock.append
1588
for name in sorted(_listdir(top)):
1590
name_utf8 = _utf8_encode(name)[0]
1591
except UnicodeDecodeError:
1592
raise errors.BadFilenameEncoding(
1593
_utf8_encode(relprefix)[0] + name, _fs_enc)
1594
abspath = top_slash + name
1595
statvalue = _lstat(abspath)
1596
kind = _kind_from_mode(statvalue.st_mode)
1597
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1601
def copy_tree(from_path, to_path, handlers={}):
1602
"""Copy all of the entries in from_path into to_path.
1604
:param from_path: The base directory to copy.
1605
:param to_path: The target directory. If it does not exist, it will
1607
:param handlers: A dictionary of functions, which takes a source and
1608
destinations for files, directories, etc.
1609
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1610
'file', 'directory', and 'symlink' should always exist.
1611
If they are missing, they will be replaced with 'os.mkdir()',
1612
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1614
# Now, just copy the existing cached tree to the new location
1615
# We use a cheap trick here.
1616
# Absolute paths are prefixed with the first parameter
1617
# relative paths are prefixed with the second.
1618
# So we can get both the source and target returned
1619
# without any extra work.
1621
def copy_dir(source, dest):
1624
def copy_link(source, dest):
1625
"""Copy the contents of a symlink"""
1626
link_to = os.readlink(source)
1627
os.symlink(link_to, dest)
1629
real_handlers = {'file':shutil.copy2,
1630
'symlink':copy_link,
1631
'directory':copy_dir,
1633
real_handlers.update(handlers)
1635
if not os.path.exists(to_path):
1636
real_handlers['directory'](from_path, to_path)
1638
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1639
for relpath, name, kind, st, abspath in entries:
1640
real_handlers[kind](abspath, relpath)
1643
def path_prefix_key(path):
1644
"""Generate a prefix-order path key for path.
1646
This can be used to sort paths in the same way that walkdirs does.
1648
return (dirname(path) , path)
1651
def compare_paths_prefix_order(path_a, path_b):
1652
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1653
key_a = path_prefix_key(path_a)
1654
key_b = path_prefix_key(path_b)
1655
return cmp(key_a, key_b)
1658
_cached_user_encoding = None
1661
def get_user_encoding(use_cache=True):
1662
"""Find out what the preferred user encoding is.
1664
This is generally the encoding that is used for command line parameters
1665
and file contents. This may be different from the terminal encoding
1666
or the filesystem encoding.
1668
:param use_cache: Enable cache for detected encoding.
1669
(This parameter is turned on by default,
1670
and required only for selftesting)
1672
:return: A string defining the preferred user encoding
1674
global _cached_user_encoding
1675
if _cached_user_encoding is not None and use_cache:
1676
return _cached_user_encoding
1678
if sys.platform == 'darwin':
1679
# python locale.getpreferredencoding() always return
1680
# 'mac-roman' on darwin. That's a lie.
1681
sys.platform = 'posix'
1683
if os.environ.get('LANG', None) is None:
1684
# If LANG is not set, we end up with 'ascii', which is bad
1685
# ('mac-roman' is more than ascii), so we set a default which
1686
# will give us UTF-8 (which appears to work in all cases on
1687
# OSX). Users are still free to override LANG of course, as
1688
# long as it give us something meaningful. This work-around
1689
# *may* not be needed with python 3k and/or OSX 10.5, but will
1690
# work with them too -- vila 20080908
1691
os.environ['LANG'] = 'en_US.UTF-8'
1694
sys.platform = 'darwin'
1699
user_encoding = locale.getpreferredencoding()
1700
except locale.Error, e:
1701
sys.stderr.write('bzr: warning: %s\n'
1702
' Could not determine what text encoding to use.\n'
1703
' This error usually means your Python interpreter\n'
1704
' doesn\'t support the locale set by $LANG (%s)\n'
1705
" Continuing with ascii encoding.\n"
1706
% (e, os.environ.get('LANG')))
1707
user_encoding = 'ascii'
1709
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1710
# treat that as ASCII, and not support printing unicode characters to the
1713
# For python scripts run under vim, we get '', so also treat that as ASCII
1714
if user_encoding in (None, 'cp0', ''):
1715
user_encoding = 'ascii'
1719
codecs.lookup(user_encoding)
1721
sys.stderr.write('bzr: warning:'
1722
' unknown encoding %s.'
1723
' Continuing with ascii encoding.\n'
1726
user_encoding = 'ascii'
1729
_cached_user_encoding = user_encoding
1731
return user_encoding
1734
def get_host_name():
1735
"""Return the current unicode host name.
1737
This is meant to be used in place of socket.gethostname() because that
1738
behaves inconsistently on different platforms.
1740
if sys.platform == "win32":
1742
return win32utils.get_host_name()
1745
return socket.gethostname().decode(get_user_encoding())
1748
def recv_all(socket, bytes):
1749
"""Receive an exact number of bytes.
1751
Regular Socket.recv() may return less than the requested number of bytes,
1752
dependning on what's in the OS buffer. MSG_WAITALL is not available
1753
on all platforms, but this should work everywhere. This will return
1754
less than the requested amount if the remote end closes.
1756
This isn't optimized and is intended mostly for use in testing.
1759
while len(b) < bytes:
1760
new = until_no_eintr(socket.recv, bytes - len(b))
1767
def send_all(socket, bytes, report_activity=None):
1768
"""Send all bytes on a socket.
1770
Regular socket.sendall() can give socket error 10053 on Windows. This
1771
implementation sends no more than 64k at a time, which avoids this problem.
1773
:param report_activity: Call this as bytes are read, see
1774
Transport._report_activity
1777
for pos in xrange(0, len(bytes), chunk_size):
1778
block = bytes[pos:pos+chunk_size]
1779
if report_activity is not None:
1780
report_activity(len(block), 'write')
1781
until_no_eintr(socket.sendall, block)
1784
def dereference_path(path):
1785
"""Determine the real path to a file.
1787
All parent elements are dereferenced. But the file itself is not
1789
:param path: The original path. May be absolute or relative.
1790
:return: the real path *to* the file
1792
parent, base = os.path.split(path)
1793
# The pathjoin for '.' is a workaround for Python bug #1213894.
1794
# (initial path components aren't dereferenced)
1795
return pathjoin(realpath(pathjoin('.', parent)), base)
1798
def supports_mapi():
1799
"""Return True if we can use MAPI to launch a mail client."""
1800
return sys.platform == "win32"
1803
def resource_string(package, resource_name):
1804
"""Load a resource from a package and return it as a string.
1806
Note: Only packages that start with bzrlib are currently supported.
1808
This is designed to be a lightweight implementation of resource
1809
loading in a way which is API compatible with the same API from
1811
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1812
If and when pkg_resources becomes a standard library, this routine
1815
# Check package name is within bzrlib
1816
if package == "bzrlib":
1817
resource_relpath = resource_name
1818
elif package.startswith("bzrlib."):
1819
package = package[len("bzrlib."):].replace('.', os.sep)
1820
resource_relpath = pathjoin(package, resource_name)
1822
raise errors.BzrError('resource package %s not in bzrlib' % package)
1824
# Map the resource to a file and read its contents
1825
base = dirname(bzrlib.__file__)
1826
if getattr(sys, 'frozen', None): # bzr.exe
1827
base = abspath(pathjoin(base, '..', '..'))
1828
filename = pathjoin(base, resource_relpath)
1829
return open(filename, 'rU').read()
1832
def file_kind_from_stat_mode_thunk(mode):
1833
global file_kind_from_stat_mode
1834
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1836
from bzrlib._readdir_pyx import UTF8DirReader
1837
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1838
except ImportError, e:
1839
# This is one time where we won't warn that an extension failed to
1840
# load. The extension is never available on Windows anyway.
1841
from bzrlib._readdir_py import (
1842
_kind_from_mode as file_kind_from_stat_mode
1844
return file_kind_from_stat_mode(mode)
1845
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1848
def file_kind(f, _lstat=os.lstat):
1850
return file_kind_from_stat_mode(_lstat(f).st_mode)
1852
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1853
raise errors.NoSuchFile(f)
1857
def until_no_eintr(f, *a, **kw):
1858
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1859
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1863
except (IOError, OSError), e:
1864
if e.errno == errno.EINTR:
1868
def re_compile_checked(re_string, flags=0, where=""):
1869
"""Return a compiled re, or raise a sensible error.
1871
This should only be used when compiling user-supplied REs.
1873
:param re_string: Text form of regular expression.
1874
:param flags: eg re.IGNORECASE
1875
:param where: Message explaining to the user the context where
1876
it occurred, eg 'log search filter'.
1878
# from https://bugs.launchpad.net/bzr/+bug/251352
1880
re_obj = re.compile(re_string, flags)
1885
where = ' in ' + where
1886
# despite the name 'error' is a type
1887
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1888
% (where, re_string, e))
1891
if sys.platform == "win32":
1894
return msvcrt.getch()
1899
fd = sys.stdin.fileno()
1900
settings = termios.tcgetattr(fd)
1903
ch = sys.stdin.read(1)
1905
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1909
if sys.platform == 'linux2':
1910
def _local_concurrency():
1912
prefix = 'processor'
1913
for line in file('/proc/cpuinfo', 'rb'):
1914
if line.startswith(prefix):
1915
concurrency = int(line[line.find(':')+1:]) + 1
1917
elif sys.platform == 'darwin':
1918
def _local_concurrency():
1919
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
1920
stdout=subprocess.PIPE).communicate()[0]
1921
elif sys.platform[0:7] == 'freebsd':
1922
def _local_concurrency():
1923
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
1924
stdout=subprocess.PIPE).communicate()[0]
1925
elif sys.platform == 'sunos5':
1926
def _local_concurrency():
1927
return subprocess.Popen(['psrinfo', '-p',],
1928
stdout=subprocess.PIPE).communicate()[0]
1929
elif sys.platform == "win32":
1930
def _local_concurrency():
1931
# This appears to return the number of cores.
1932
return os.environ.get('NUMBER_OF_PROCESSORS')
1934
def _local_concurrency():
1939
_cached_local_concurrency = None
1941
def local_concurrency(use_cache=True):
1942
"""Return how many processes can be run concurrently.
1944
Rely on platform specific implementations and default to 1 (one) if
1945
anything goes wrong.
1947
global _cached_local_concurrency
1948
if _cached_local_concurrency is not None and use_cache:
1949
return _cached_local_concurrency
1952
concurrency = _local_concurrency()
1953
except (OSError, IOError):
1956
concurrency = int(concurrency)
1957
except (TypeError, ValueError):
1960
_cached_concurrency = concurrency