59
150
# TODO: I'm not really sure this is the best format either.x
152
if _QUOTE_RE is None:
62
153
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
64
155
if _QUOTE_RE.search(f):
65
156
return '"' + f + '"'
71
mode = os.lstat(f)[ST_MODE]
161
_directory_kind = 'directory'
164
"""Return the current umask"""
165
# Assume that people aren't messing with the umask while running
166
# XXX: This is not thread safe, but there is no way to get the
167
# umask without setting it
175
_directory_kind: "/",
177
'tree-reference': '+',
90
181
def kind_marker(kind):
183
return _kind_marker_map[kind]
185
# Slightly faster than using .get(, '') when the common case is that
93
elif kind == 'directory':
95
elif kind == 'symlink':
98
raise BzrError('invalid file kind %r' % kind)
102
if hasattr(os, 'lstat'):
108
if e.errno == errno.ENOENT:
111
raise BzrError("lstat/stat of (%r): %r" % (f, e))
190
lexists = getattr(os.path, 'lexists', None)
194
stat = getattr(os, 'lstat', os.stat)
198
if e.errno == errno.ENOENT:
201
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
204
def fancy_rename(old, new, rename_func, unlink_func):
205
"""A fancy rename, when you don't have atomic rename.
207
:param old: The old path, to rename from
208
:param new: The new path, to rename to
209
:param rename_func: The potentially non-atomic rename function
210
:param unlink_func: A way to delete the target file if the full rename
213
# sftp rename doesn't allow overwriting, so play tricks:
214
base = os.path.basename(new)
215
dirname = os.path.dirname(new)
216
# callers use different encodings for the paths so the following MUST
217
# respect that. We rely on python upcasting to unicode if new is unicode
218
# and keeping a str if not.
219
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
220
os.getpid(), rand_chars(10))
221
tmp_name = pathjoin(dirname, tmp_name)
223
# Rename the file out of the way, but keep track if it didn't exist
224
# We don't want to grab just any exception
225
# something like EACCES should prevent us from continuing
226
# The downside is that the rename_func has to throw an exception
227
# with an errno = ENOENT, or NoSuchFile
230
rename_func(new, tmp_name)
231
except (errors.NoSuchFile,), e:
234
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
235
# function raises an IOError with errno is None when a rename fails.
236
# This then gets caught here.
237
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
240
if (getattr(e, 'errno', None) is None
241
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
250
# This may throw an exception, in which case success will
252
rename_func(old, new)
254
except (IOError, OSError), e:
255
# source and target may be aliases of each other (e.g. on a
256
# case-insensitive filesystem), so we may have accidentally renamed
257
# source by when we tried to rename target
258
failure_exc = sys.exc_info()
259
if (file_existed and e.errno in (None, errno.ENOENT)
260
and old.lower() == new.lower()):
261
# source and target are the same file on a case-insensitive
262
# filesystem, so we don't generate an exception
266
# If the file used to exist, rename it back into place
267
# otherwise just delete it from the tmp location
269
unlink_func(tmp_name)
271
rename_func(tmp_name, new)
272
if failure_exc is not None:
273
raise failure_exc[0], failure_exc[1], failure_exc[2]
276
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
277
# choke on a Unicode string containing a relative path if
278
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
280
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
281
def _posix_abspath(path):
282
# jam 20060426 rather than encoding to fsencoding
283
# copy posixpath.abspath, but use os.getcwdu instead
284
if not posixpath.isabs(path):
285
path = posixpath.join(getcwd(), path)
286
return posixpath.normpath(path)
289
def _posix_realpath(path):
290
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
293
def _win32_fixdrive(path):
294
"""Force drive letters to be consistent.
296
win32 is inconsistent whether it returns lower or upper case
297
and even if it was consistent the user might type the other
298
so we force it to uppercase
299
running python.exe under cmd.exe return capital C:\\
300
running win32 python inside a cygwin shell returns lowercase c:\\
302
drive, path = _nt_splitdrive(path)
303
return drive.upper() + path
306
def _win32_abspath(path):
307
# Real _nt_abspath doesn't have a problem with a unicode cwd
308
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
311
def _win98_abspath(path):
312
"""Return the absolute version of a path.
313
Windows 98 safe implementation (python reimplementation
314
of Win32 API function GetFullPathNameW)
319
# \\HOST\path => //HOST/path
320
# //HOST/path => //HOST/path
321
# path => C:/cwd/path
324
# check for absolute path
325
drive = _nt_splitdrive(path)[0]
326
if drive == '' and path[:2] not in('//','\\\\'):
328
# we cannot simply os.path.join cwd and path
329
# because os.path.join('C:','/path') produce '/path'
330
# and this is incorrect
331
if path[:1] in ('/','\\'):
332
cwd = _nt_splitdrive(cwd)[0]
334
path = cwd + '\\' + path
335
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
338
def _win32_realpath(path):
339
# Real _nt_realpath doesn't have a problem with a unicode cwd
340
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
343
def _win32_pathjoin(*args):
344
return _nt_join(*args).replace('\\', '/')
347
def _win32_normpath(path):
348
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
352
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
355
def _win32_mkdtemp(*args, **kwargs):
356
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
359
def _win32_rename(old, new):
360
"""We expect to be able to atomically replace 'new' with old.
362
On win32, if new exists, it must be moved out of the way first,
366
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
368
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
369
# If we try to rename a non-existant file onto cwd, we get
370
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
371
# if the old path doesn't exist, sometimes we get EACCES
372
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
378
return unicodedata.normalize('NFC', os.getcwdu())
381
# Default is to just use the python builtins, but these can be rebound on
382
# particular platforms.
383
abspath = _posix_abspath
384
realpath = _posix_realpath
385
pathjoin = os.path.join
386
normpath = os.path.normpath
389
dirname = os.path.dirname
390
basename = os.path.basename
391
split = os.path.split
392
splitext = os.path.splitext
393
# These were already imported into local scope
394
# mkdtemp = tempfile.mkdtemp
395
# rmtree = shutil.rmtree
397
MIN_ABS_PATHLENGTH = 1
400
if sys.platform == 'win32':
401
if win32utils.winver == 'Windows 98':
402
abspath = _win98_abspath
404
abspath = _win32_abspath
405
realpath = _win32_realpath
406
pathjoin = _win32_pathjoin
407
normpath = _win32_normpath
408
getcwd = _win32_getcwd
409
mkdtemp = _win32_mkdtemp
410
rename = _win32_rename
412
MIN_ABS_PATHLENGTH = 3
414
def _win32_delete_readonly(function, path, excinfo):
415
"""Error handler for shutil.rmtree function [for win32]
416
Helps to remove files and dirs marked as read-only.
418
exception = excinfo[1]
419
if function in (os.remove, os.rmdir) \
420
and isinstance(exception, OSError) \
421
and exception.errno == errno.EACCES:
427
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
428
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
429
return shutil.rmtree(path, ignore_errors, onerror)
431
f = win32utils.get_unicode_argv # special function or None
435
elif sys.platform == 'darwin':
439
def get_terminal_encoding():
440
"""Find the best encoding for printing to the screen.
442
This attempts to check both sys.stdout and sys.stdin to see
443
what encoding they are in, and if that fails it falls back to
444
osutils.get_user_encoding().
445
The problem is that on Windows, locale.getpreferredencoding()
446
is not the same encoding as that used by the console:
447
http://mail.python.org/pipermail/python-list/2003-May/162357.html
449
On my standard US Windows XP, the preferred encoding is
450
cp1252, but the console is cp437
452
from bzrlib.trace import mutter
453
output_encoding = getattr(sys.stdout, 'encoding', None)
454
if not output_encoding:
455
input_encoding = getattr(sys.stdin, 'encoding', None)
456
if not input_encoding:
457
output_encoding = get_user_encoding()
458
mutter('encoding stdout as osutils.get_user_encoding() %r',
461
output_encoding = input_encoding
462
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
464
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
465
if output_encoding == 'cp0':
466
# invalid encoding (cp0 means 'no codepage' on Windows)
467
output_encoding = get_user_encoding()
468
mutter('cp0 is invalid encoding.'
469
' encoding stdout as osutils.get_user_encoding() %r',
473
codecs.lookup(output_encoding)
475
sys.stderr.write('bzr: warning:'
476
' unknown terminal encoding %s.\n'
477
' Using encoding %s instead.\n'
478
% (output_encoding, get_user_encoding())
480
output_encoding = get_user_encoding()
482
return output_encoding
113
485
def normalizepath(f):
114
if hasattr(os.path, 'realpath'):
486
if getattr(os.path, 'realpath', None) is not None:
118
490
[p,e] = os.path.split(f)
119
491
if e == "" or e == "." or e == "..":
122
return os.path.join(F(p), e)
126
"""Copy a file to a backup.
128
Backups are named in GNU-style, with a ~ suffix.
130
If the file is already a backup, it's not copied.
136
if has_symlinks() and os.path.islink(fn):
137
target = os.readlink(fn)
138
os.symlink(target, bfn)
146
outf = file(bfn, 'wb')
494
return pathjoin(F(p), e)
1127
def relpath(base, path):
1128
"""Return path relative to base, or raise exception.
1130
The path may be either an absolute path or a path relative to the
1131
current working directory.
1133
os.path.commonprefix (python2.4) has a bad bug that it works just
1134
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1135
avoids that problem.
1138
if len(base) < MIN_ABS_PATHLENGTH:
1139
# must have space for e.g. a drive letter
1140
raise ValueError('%r is too short to calculate a relative path'
1148
if len(head) <= len(base) and head != base:
1149
raise errors.PathNotChild(rp, base)
1152
head, tail = split(head)
1157
return pathjoin(*reversed(s))
1162
def _cicp_canonical_relpath(base, path):
1163
"""Return the canonical path relative to base.
1165
Like relpath, but on case-insensitive-case-preserving file-systems, this
1166
will return the relpath as stored on the file-system rather than in the
1167
case specified in the input string, for all existing portions of the path.
1169
This will cause O(N) behaviour if called for every path in a tree; if you
1170
have a number of paths to convert, you should use canonical_relpaths().
1172
# TODO: it should be possible to optimize this for Windows by using the
1173
# win32 API FindFiles function to look for the specified name - but using
1174
# os.listdir() still gives us the correct, platform agnostic semantics in
1177
rel = relpath(base, path)
1178
# '.' will have been turned into ''
1182
abs_base = abspath(base)
1184
_listdir = os.listdir
1186
# use an explicit iterator so we can easily consume the rest on early exit.
1187
bit_iter = iter(rel.split('/'))
1188
for bit in bit_iter:
1191
next_entries = _listdir(current)
1192
except OSError: # enoent, eperm, etc
1193
# We can't find this in the filesystem, so just append the
1195
current = pathjoin(current, bit, *list(bit_iter))
1197
for look in next_entries:
1198
if lbit == look.lower():
1199
current = pathjoin(current, look)
1202
# got to the end, nothing matched, so we just return the
1203
# non-existing bits as they were specified (the filename may be
1204
# the target of a move, for example).
1205
current = pathjoin(current, bit, *list(bit_iter))
1207
return current[len(abs_base):].lstrip('/')
1209
# XXX - TODO - we need better detection/integration of case-insensitive
1210
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1211
# filesystems), for example, so could probably benefit from the same basic
1212
# support there. For now though, only Windows and OSX get that support, and
1213
# they get it for *all* file-systems!
1214
if sys.platform in ('win32', 'darwin'):
1215
canonical_relpath = _cicp_canonical_relpath
1217
canonical_relpath = relpath
1219
def canonical_relpaths(base, paths):
1220
"""Create an iterable to canonicalize a sequence of relative paths.
1222
The intent is for this implementation to use a cache, vastly speeding
1223
up multiple transformations in the same directory.
1225
# but for now, we haven't optimized...
1226
return [canonical_relpath(base, p) for p in paths]
1228
def safe_unicode(unicode_or_utf8_string):
1229
"""Coerce unicode_or_utf8_string into unicode.
1231
If it is unicode, it is returned.
1232
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1233
wrapped in a BzrBadParameterNotUnicode exception.
1235
if isinstance(unicode_or_utf8_string, unicode):
1236
return unicode_or_utf8_string
1238
return unicode_or_utf8_string.decode('utf8')
1239
except UnicodeDecodeError:
1240
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1243
def safe_utf8(unicode_or_utf8_string):
1244
"""Coerce unicode_or_utf8_string to a utf8 string.
1246
If it is a str, it is returned.
1247
If it is Unicode, it is encoded into a utf-8 string.
1249
if isinstance(unicode_or_utf8_string, str):
1250
# TODO: jam 20070209 This is overkill, and probably has an impact on
1251
# performance if we are dealing with lots of apis that want a
1254
# Make sure it is a valid utf-8 string
1255
unicode_or_utf8_string.decode('utf-8')
1256
except UnicodeDecodeError:
1257
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1258
return unicode_or_utf8_string
1259
return unicode_or_utf8_string.encode('utf-8')
1262
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1263
' Revision id generators should be creating utf8'
1267
def safe_revision_id(unicode_or_utf8_string, warn=True):
1268
"""Revision ids should now be utf8, but at one point they were unicode.
1270
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1272
:param warn: Functions that are sanitizing user data can set warn=False
1273
:return: None or a utf8 revision id.
1275
if (unicode_or_utf8_string is None
1276
or unicode_or_utf8_string.__class__ == str):
1277
return unicode_or_utf8_string
1279
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1281
return cache_utf8.encode(unicode_or_utf8_string)
1284
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1285
' generators should be creating utf8 file ids.')
1288
def safe_file_id(unicode_or_utf8_string, warn=True):
1289
"""File ids should now be utf8, but at one point they were unicode.
1291
This is the same as safe_utf8, except it uses the cached encode functions
1292
to save a little bit of performance.
1294
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1296
:param warn: Functions that are sanitizing user data can set warn=False
1297
:return: None or a utf8 file id.
1299
if (unicode_or_utf8_string is None
1300
or unicode_or_utf8_string.__class__ == str):
1301
return unicode_or_utf8_string
1303
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1305
return cache_utf8.encode(unicode_or_utf8_string)
1308
_platform_normalizes_filenames = False
1309
if sys.platform == 'darwin':
1310
_platform_normalizes_filenames = True
1313
def normalizes_filenames():
1314
"""Return True if this platform normalizes unicode filenames.
1316
Mac OSX does, Windows/Linux do not.
1318
return _platform_normalizes_filenames
1321
def _accessible_normalized_filename(path):
1322
"""Get the unicode normalized path, and if you can access the file.
1324
On platforms where the system normalizes filenames (Mac OSX),
1325
you can access a file by any path which will normalize correctly.
1326
On platforms where the system does not normalize filenames
1327
(Windows, Linux), you have to access a file by its exact path.
1329
Internally, bzr only supports NFC normalization, since that is
1330
the standard for XML documents.
1332
So return the normalized path, and a flag indicating if the file
1333
can be accessed by that path.
1336
return unicodedata.normalize('NFC', unicode(path)), True
1339
def _inaccessible_normalized_filename(path):
1340
__doc__ = _accessible_normalized_filename.__doc__
1342
normalized = unicodedata.normalize('NFC', unicode(path))
1343
return normalized, normalized == path
1346
if _platform_normalizes_filenames:
1347
normalized_filename = _accessible_normalized_filename
1349
normalized_filename = _inaccessible_normalized_filename
1352
default_terminal_width = 80
1353
"""The default terminal width for ttys.
1355
This is defined so that higher levels can share a common fallback value when
1356
terminal_width() returns None.
1360
def terminal_width():
1361
"""Return terminal width.
1363
None is returned if the width can't established precisely.
1366
- if BZR_COLUMNS is set, returns its value
1367
- if there is no controlling terminal, returns None
1368
- if COLUMNS is set, returns its value,
1370
From there, we need to query the OS to get the size of the controlling
1374
- get termios.TIOCGWINSZ
1375
- if an error occurs or a negative value is obtained, returns None
1379
- win32utils.get_console_size() decides,
1380
- returns None on error (provided default value)
1383
# If BZR_COLUMNS is set, take it, user is always right
1385
return int(os.environ['BZR_COLUMNS'])
1386
except (KeyError, ValueError):
1389
isatty = getattr(sys.stdout, 'isatty', None)
1390
if isatty is None or not isatty():
1391
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1394
# If COLUMNS is set, take it, the terminal knows better (even inside a
1395
# given terminal, the application can decide to set COLUMNS to a lower
1396
# value (splitted screen) or a bigger value (scroll bars))
1398
return int(os.environ['COLUMNS'])
1399
except (KeyError, ValueError):
1402
width, height = _terminal_size(None, None)
1404
# Consider invalid values as meaning no width
1410
def _win32_terminal_size(width, height):
1411
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1412
return width, height
1415
def _ioctl_terminal_size(width, height):
1417
import struct, fcntl, termios
1418
s = struct.pack('HHHH', 0, 0, 0, 0)
1419
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1420
height, width = struct.unpack('HHHH', x)[0:2]
1421
except (IOError, AttributeError):
1423
return width, height
1425
_terminal_size = None
1426
"""Returns the terminal size as (width, height).
1428
:param width: Default value for width.
1429
:param height: Default value for height.
1431
This is defined specifically for each OS and query the size of the controlling
1432
terminal. If any error occurs, the provided default values should be returned.
1434
if sys.platform == 'win32':
1435
_terminal_size = _win32_terminal_size
1437
_terminal_size = _ioctl_terminal_size
1440
def _terminal_size_changed(signum, frame):
1441
"""Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1442
width, height = _terminal_size(None, None)
1443
if width is not None:
1444
os.environ['COLUMNS'] = str(width)
1447
_registered_sigwinch = False
1449
def watch_sigwinch():
1450
"""Register for SIGWINCH, once and only once."""
1451
global _registered_sigwinch
1452
if not _registered_sigwinch:
1453
if sys.platform == 'win32':
1454
# Martin (gz) mentioned WINDOW_BUFFER_SIZE_RECORD from
1455
# ReadConsoleInput but I've no idea how to plug that in
1456
# the current design -- vila 20091216
1459
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1460
_registered_sigwinch = True
1463
def supports_executable():
1464
return sys.platform != "win32"
1467
def supports_posix_readonly():
1468
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1470
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1471
directory controls creation/deletion, etc.
1473
And under win32, readonly means that the directory itself cannot be
1474
deleted. The contents of a readonly directory can be changed, unlike POSIX
1475
where files in readonly directories cannot be added, deleted or renamed.
1477
return sys.platform != "win32"
1480
def set_or_unset_env(env_variable, value):
1481
"""Modify the environment, setting or removing the env_variable.
1483
:param env_variable: The environment variable in question
1484
:param value: The value to set the environment to. If None, then
1485
the variable will be removed.
1486
:return: The original value of the environment variable.
1488
orig_val = os.environ.get(env_variable)
1490
if orig_val is not None:
1491
del os.environ[env_variable]
1493
if isinstance(value, unicode):
1494
value = value.encode(get_user_encoding())
1495
os.environ[env_variable] = value
1499
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1502
def check_legal_path(path):
1503
"""Check whether the supplied path is legal.
1504
This is only required on Windows, so we don't test on other platforms
1507
if sys.platform != "win32":
1509
if _validWin32PathRE.match(path) is None:
1510
raise errors.IllegalPath(path)
1513
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1515
def _is_error_enotdir(e):
1516
"""Check if this exception represents ENOTDIR.
1518
Unfortunately, python is very inconsistent about the exception
1519
here. The cases are:
1520
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1521
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1522
which is the windows error code.
1523
3) Windows, Python2.5 uses errno == EINVAL and
1524
winerror == ERROR_DIRECTORY
1526
:param e: An Exception object (expected to be OSError with an errno
1527
attribute, but we should be able to cope with anything)
1528
:return: True if this represents an ENOTDIR error. False otherwise.
1530
en = getattr(e, 'errno', None)
1531
if (en == errno.ENOTDIR
1532
or (sys.platform == 'win32'
1533
and (en == _WIN32_ERROR_DIRECTORY
1534
or (en == errno.EINVAL
1535
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1541
def walkdirs(top, prefix=""):
1542
"""Yield data about all the directories in a tree.
1544
This yields all the data about the contents of a directory at a time.
1545
After each directory has been yielded, if the caller has mutated the list
1546
to exclude some directories, they are then not descended into.
1548
The data yielded is of the form:
1549
((directory-relpath, directory-path-from-top),
1550
[(relpath, basename, kind, lstat, path-from-top), ...]),
1551
- directory-relpath is the relative path of the directory being returned
1552
with respect to top. prefix is prepended to this.
1553
- directory-path-from-root is the path including top for this directory.
1554
It is suitable for use with os functions.
1555
- relpath is the relative path within the subtree being walked.
1556
- basename is the basename of the path
1557
- kind is the kind of the file now. If unknown then the file is not
1558
present within the tree - but it may be recorded as versioned. See
1560
- lstat is the stat data *if* the file was statted.
1561
- planned, not implemented:
1562
path_from_tree_root is the path from the root of the tree.
1564
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1565
allows one to walk a subtree but get paths that are relative to a tree
1567
:return: an iterator over the dirs.
1569
#TODO there is a bit of a smell where the results of the directory-
1570
# summary in this, and the path from the root, may not agree
1571
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1572
# potentially confusing output. We should make this more robust - but
1573
# not at a speed cost. RBC 20060731
1575
_directory = _directory_kind
1576
_listdir = os.listdir
1577
_kind_from_mode = file_kind_from_stat_mode
1578
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1580
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1581
relroot, _, _, _, top = pending.pop()
1583
relprefix = relroot + u'/'
1586
top_slash = top + u'/'
1589
append = dirblock.append
1591
names = sorted(_listdir(top))
1593
if not _is_error_enotdir(e):
1597
abspath = top_slash + name
1598
statvalue = _lstat(abspath)
1599
kind = _kind_from_mode(statvalue.st_mode)
1600
append((relprefix + name, name, kind, statvalue, abspath))
1601
yield (relroot, top), dirblock
1603
# push the user specified dirs from dirblock
1604
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1607
class DirReader(object):
1608
"""An interface for reading directories."""
1610
def top_prefix_to_starting_dir(self, top, prefix=""):
1611
"""Converts top and prefix to a starting dir entry
1613
:param top: A utf8 path
1614
:param prefix: An optional utf8 path to prefix output relative paths
1616
:return: A tuple starting with prefix, and ending with the native
1619
raise NotImplementedError(self.top_prefix_to_starting_dir)
1621
def read_dir(self, prefix, top):
1622
"""Read a specific dir.
1624
:param prefix: A utf8 prefix to be preprended to the path basenames.
1625
:param top: A natively encoded path to read.
1626
:return: A list of the directories contents. Each item contains:
1627
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1629
raise NotImplementedError(self.read_dir)
1632
_selected_dir_reader = None
1635
def _walkdirs_utf8(top, prefix=""):
1636
"""Yield data about all the directories in a tree.
1638
This yields the same information as walkdirs() only each entry is yielded
1639
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1640
are returned as exact byte-strings.
1642
:return: yields a tuple of (dir_info, [file_info])
1643
dir_info is (utf8_relpath, path-from-top)
1644
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1645
if top is an absolute path, path-from-top is also an absolute path.
1646
path-from-top might be unicode or utf8, but it is the correct path to
1647
pass to os functions to affect the file in question. (such as os.lstat)
1649
global _selected_dir_reader
1650
if _selected_dir_reader is None:
1651
fs_encoding = _fs_enc.upper()
1652
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1653
# Win98 doesn't have unicode apis like FindFirstFileW
1654
# TODO: We possibly could support Win98 by falling back to the
1655
# original FindFirstFile, and using TCHAR instead of WCHAR,
1656
# but that gets a bit tricky, and requires custom compiling
1659
from bzrlib._walkdirs_win32 import Win32ReadDir
1660
_selected_dir_reader = Win32ReadDir()
1663
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1664
# ANSI_X3.4-1968 is a form of ASCII
1666
from bzrlib._readdir_pyx import UTF8DirReader
1667
_selected_dir_reader = UTF8DirReader()
1668
except ImportError, e:
1669
failed_to_load_extension(e)
1672
if _selected_dir_reader is None:
1673
# Fallback to the python version
1674
_selected_dir_reader = UnicodeDirReader()
1676
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1677
# But we don't actually uses 1-3 in pending, so set them to None
1678
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1679
read_dir = _selected_dir_reader.read_dir
1680
_directory = _directory_kind
1682
relroot, _, _, _, top = pending[-1].pop()
1685
dirblock = sorted(read_dir(relroot, top))
1686
yield (relroot, top), dirblock
1687
# push the user specified dirs from dirblock
1688
next = [d for d in reversed(dirblock) if d[2] == _directory]
1690
pending.append(next)
1693
class UnicodeDirReader(DirReader):
1694
"""A dir reader for non-utf8 file systems, which transcodes."""
1696
__slots__ = ['_utf8_encode']
1699
self._utf8_encode = codecs.getencoder('utf8')
1701
def top_prefix_to_starting_dir(self, top, prefix=""):
1702
"""See DirReader.top_prefix_to_starting_dir."""
1703
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1705
def read_dir(self, prefix, top):
1706
"""Read a single directory from a non-utf8 file system.
1708
top, and the abspath element in the output are unicode, all other paths
1709
are utf8. Local disk IO is done via unicode calls to listdir etc.
1711
This is currently the fallback code path when the filesystem encoding is
1712
not UTF-8. It may be better to implement an alternative so that we can
1713
safely handle paths that are not properly decodable in the current
1716
See DirReader.read_dir for details.
1718
_utf8_encode = self._utf8_encode
1720
_listdir = os.listdir
1721
_kind_from_mode = file_kind_from_stat_mode
1724
relprefix = prefix + '/'
1727
top_slash = top + u'/'
1730
append = dirblock.append
1731
for name in sorted(_listdir(top)):
1733
name_utf8 = _utf8_encode(name)[0]
1734
except UnicodeDecodeError:
1735
raise errors.BadFilenameEncoding(
1736
_utf8_encode(relprefix)[0] + name, _fs_enc)
1737
abspath = top_slash + name
1738
statvalue = _lstat(abspath)
1739
kind = _kind_from_mode(statvalue.st_mode)
1740
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1744
def copy_tree(from_path, to_path, handlers={}):
1745
"""Copy all of the entries in from_path into to_path.
1747
:param from_path: The base directory to copy.
1748
:param to_path: The target directory. If it does not exist, it will
1750
:param handlers: A dictionary of functions, which takes a source and
1751
destinations for files, directories, etc.
1752
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1753
'file', 'directory', and 'symlink' should always exist.
1754
If they are missing, they will be replaced with 'os.mkdir()',
1755
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1757
# Now, just copy the existing cached tree to the new location
1758
# We use a cheap trick here.
1759
# Absolute paths are prefixed with the first parameter
1760
# relative paths are prefixed with the second.
1761
# So we can get both the source and target returned
1762
# without any extra work.
1764
def copy_dir(source, dest):
1767
def copy_link(source, dest):
1768
"""Copy the contents of a symlink"""
1769
link_to = os.readlink(source)
1770
os.symlink(link_to, dest)
1772
real_handlers = {'file':shutil.copy2,
1773
'symlink':copy_link,
1774
'directory':copy_dir,
1776
real_handlers.update(handlers)
1778
if not os.path.exists(to_path):
1779
real_handlers['directory'](from_path, to_path)
1781
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1782
for relpath, name, kind, st, abspath in entries:
1783
real_handlers[kind](abspath, relpath)
1786
def path_prefix_key(path):
1787
"""Generate a prefix-order path key for path.
1789
This can be used to sort paths in the same way that walkdirs does.
1791
return (dirname(path) , path)
1794
def compare_paths_prefix_order(path_a, path_b):
1795
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1796
key_a = path_prefix_key(path_a)
1797
key_b = path_prefix_key(path_b)
1798
return cmp(key_a, key_b)
1801
_cached_user_encoding = None
1804
def get_user_encoding(use_cache=True):
1805
"""Find out what the preferred user encoding is.
1807
This is generally the encoding that is used for command line parameters
1808
and file contents. This may be different from the terminal encoding
1809
or the filesystem encoding.
1811
:param use_cache: Enable cache for detected encoding.
1812
(This parameter is turned on by default,
1813
and required only for selftesting)
1815
:return: A string defining the preferred user encoding
1817
global _cached_user_encoding
1818
if _cached_user_encoding is not None and use_cache:
1819
return _cached_user_encoding
1821
if sys.platform == 'darwin':
1822
# python locale.getpreferredencoding() always return
1823
# 'mac-roman' on darwin. That's a lie.
1824
sys.platform = 'posix'
1826
if os.environ.get('LANG', None) is None:
1827
# If LANG is not set, we end up with 'ascii', which is bad
1828
# ('mac-roman' is more than ascii), so we set a default which
1829
# will give us UTF-8 (which appears to work in all cases on
1830
# OSX). Users are still free to override LANG of course, as
1831
# long as it give us something meaningful. This work-around
1832
# *may* not be needed with python 3k and/or OSX 10.5, but will
1833
# work with them too -- vila 20080908
1834
os.environ['LANG'] = 'en_US.UTF-8'
1837
sys.platform = 'darwin'
1842
user_encoding = locale.getpreferredencoding()
1843
except locale.Error, e:
1844
sys.stderr.write('bzr: warning: %s\n'
1845
' Could not determine what text encoding to use.\n'
1846
' This error usually means your Python interpreter\n'
1847
' doesn\'t support the locale set by $LANG (%s)\n'
1848
" Continuing with ascii encoding.\n"
1849
% (e, os.environ.get('LANG')))
1850
user_encoding = 'ascii'
1852
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1853
# treat that as ASCII, and not support printing unicode characters to the
1856
# For python scripts run under vim, we get '', so also treat that as ASCII
1857
if user_encoding in (None, 'cp0', ''):
1858
user_encoding = 'ascii'
1862
codecs.lookup(user_encoding)
1864
sys.stderr.write('bzr: warning:'
1865
' unknown encoding %s.'
1866
' Continuing with ascii encoding.\n'
1869
user_encoding = 'ascii'
1872
_cached_user_encoding = user_encoding
1874
return user_encoding
1877
def get_host_name():
1878
"""Return the current unicode host name.
1880
This is meant to be used in place of socket.gethostname() because that
1881
behaves inconsistently on different platforms.
1883
if sys.platform == "win32":
1885
return win32utils.get_host_name()
1888
return socket.gethostname().decode(get_user_encoding())
1891
def recv_all(socket, bytes):
1892
"""Receive an exact number of bytes.
1894
Regular Socket.recv() may return less than the requested number of bytes,
1895
dependning on what's in the OS buffer. MSG_WAITALL is not available
1896
on all platforms, but this should work everywhere. This will return
1897
less than the requested amount if the remote end closes.
1899
This isn't optimized and is intended mostly for use in testing.
1902
while len(b) < bytes:
1903
new = until_no_eintr(socket.recv, bytes - len(b))
1910
def send_all(socket, bytes, report_activity=None):
1911
"""Send all bytes on a socket.
1913
Regular socket.sendall() can give socket error 10053 on Windows. This
1914
implementation sends no more than 64k at a time, which avoids this problem.
1916
:param report_activity: Call this as bytes are read, see
1917
Transport._report_activity
1920
for pos in xrange(0, len(bytes), chunk_size):
1921
block = bytes[pos:pos+chunk_size]
1922
if report_activity is not None:
1923
report_activity(len(block), 'write')
1924
until_no_eintr(socket.sendall, block)
1927
def dereference_path(path):
1928
"""Determine the real path to a file.
1930
All parent elements are dereferenced. But the file itself is not
1932
:param path: The original path. May be absolute or relative.
1933
:return: the real path *to* the file
1935
parent, base = os.path.split(path)
1936
# The pathjoin for '.' is a workaround for Python bug #1213894.
1937
# (initial path components aren't dereferenced)
1938
return pathjoin(realpath(pathjoin('.', parent)), base)
1941
def supports_mapi():
1942
"""Return True if we can use MAPI to launch a mail client."""
1943
return sys.platform == "win32"
1946
def resource_string(package, resource_name):
1947
"""Load a resource from a package and return it as a string.
1949
Note: Only packages that start with bzrlib are currently supported.
1951
This is designed to be a lightweight implementation of resource
1952
loading in a way which is API compatible with the same API from
1954
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1955
If and when pkg_resources becomes a standard library, this routine
1958
# Check package name is within bzrlib
1959
if package == "bzrlib":
1960
resource_relpath = resource_name
1961
elif package.startswith("bzrlib."):
1962
package = package[len("bzrlib."):].replace('.', os.sep)
1963
resource_relpath = pathjoin(package, resource_name)
1965
raise errors.BzrError('resource package %s not in bzrlib' % package)
1967
# Map the resource to a file and read its contents
1968
base = dirname(bzrlib.__file__)
1969
if getattr(sys, 'frozen', None): # bzr.exe
1970
base = abspath(pathjoin(base, '..', '..'))
1971
filename = pathjoin(base, resource_relpath)
1972
return open(filename, 'rU').read()
1975
def file_kind_from_stat_mode_thunk(mode):
1976
global file_kind_from_stat_mode
1977
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1979
from bzrlib._readdir_pyx import UTF8DirReader
1980
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1981
except ImportError, e:
1982
# This is one time where we won't warn that an extension failed to
1983
# load. The extension is never available on Windows anyway.
1984
from bzrlib._readdir_py import (
1985
_kind_from_mode as file_kind_from_stat_mode
1987
return file_kind_from_stat_mode(mode)
1988
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1991
def file_kind(f, _lstat=os.lstat):
1993
return file_kind_from_stat_mode(_lstat(f).st_mode)
1995
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1996
raise errors.NoSuchFile(f)
2000
def until_no_eintr(f, *a, **kw):
2001
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2002
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2006
except (IOError, OSError), e:
2007
if e.errno == errno.EINTR:
2011
def re_compile_checked(re_string, flags=0, where=""):
2012
"""Return a compiled re, or raise a sensible error.
2014
This should only be used when compiling user-supplied REs.
2016
:param re_string: Text form of regular expression.
2017
:param flags: eg re.IGNORECASE
2018
:param where: Message explaining to the user the context where
2019
it occurred, eg 'log search filter'.
2021
# from https://bugs.launchpad.net/bzr/+bug/251352
2023
re_obj = re.compile(re_string, flags)
2028
where = ' in ' + where
2029
# despite the name 'error' is a type
2030
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2031
% (where, re_string, e))
2034
if sys.platform == "win32":
2037
return msvcrt.getch()
2042
fd = sys.stdin.fileno()
2043
settings = termios.tcgetattr(fd)
2046
ch = sys.stdin.read(1)
2048
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2052
if sys.platform == 'linux2':
2053
def _local_concurrency():
2055
prefix = 'processor'
2056
for line in file('/proc/cpuinfo', 'rb'):
2057
if line.startswith(prefix):
2058
concurrency = int(line[line.find(':')+1:]) + 1
2060
elif sys.platform == 'darwin':
2061
def _local_concurrency():
2062
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2063
stdout=subprocess.PIPE).communicate()[0]
2064
elif sys.platform[0:7] == 'freebsd':
2065
def _local_concurrency():
2066
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2067
stdout=subprocess.PIPE).communicate()[0]
2068
elif sys.platform == 'sunos5':
2069
def _local_concurrency():
2070
return subprocess.Popen(['psrinfo', '-p',],
2071
stdout=subprocess.PIPE).communicate()[0]
2072
elif sys.platform == "win32":
2073
def _local_concurrency():
2074
# This appears to return the number of cores.
2075
return os.environ.get('NUMBER_OF_PROCESSORS')
2077
def _local_concurrency():
2082
_cached_local_concurrency = None
2084
def local_concurrency(use_cache=True):
2085
"""Return how many processes can be run concurrently.
2087
Rely on platform specific implementations and default to 1 (one) if
2088
anything goes wrong.
2090
global _cached_local_concurrency
2092
if _cached_local_concurrency is not None and use_cache:
2093
return _cached_local_concurrency
2095
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2096
if concurrency is None:
2098
concurrency = _local_concurrency()
2099
except (OSError, IOError):
2102
concurrency = int(concurrency)
2103
except (TypeError, ValueError):
2106
_cached_concurrency = concurrency
2110
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2111
"""A stream writer that doesn't decode str arguments."""
2113
def __init__(self, encode, stream, errors='strict'):
2114
codecs.StreamWriter.__init__(self, stream, errors)
2115
self.encode = encode
2117
def write(self, object):
2118
if type(object) is str:
2119
self.stream.write(object)
2121
data, _ = self.encode(object, self.errors)
2122
self.stream.write(data)
2124
if sys.platform == 'win32':
2125
def open_file(filename, mode='r', bufsize=-1):
2126
"""This function is used to override the ``open`` builtin.
2128
But it uses O_NOINHERIT flag so the file handle is not inherited by
2129
child processes. Deleting or renaming a closed file opened with this
2130
function is not blocking child processes.
2132
writing = 'w' in mode
2133
appending = 'a' in mode
2134
updating = '+' in mode
2135
binary = 'b' in mode
2138
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2139
# for flags for each modes.
2149
flags |= os.O_WRONLY
2150
flags |= os.O_CREAT | os.O_TRUNC
2155
flags |= os.O_WRONLY
2156
flags |= os.O_CREAT | os.O_APPEND
2161
flags |= os.O_RDONLY
2163
return os.fdopen(os.open(filename, flags), mode, bufsize)