48
154
# TODO: I'm not really sure this is the best format either.x
51
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
156
if _QUOTE_RE is None:
157
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
53
159
if _QUOTE_RE.search(f):
54
160
return '"' + f + '"'
60
mode = os.lstat(f)[ST_MODE]
68
raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
165
_directory_kind = 'directory'
169
"""Return the current umask"""
170
# Assume that people aren't messing with the umask while running
171
# XXX: This is not thread safe, but there is no way to get the
172
# umask without setting it
180
_directory_kind: "/",
182
'tree-reference': '+',
71
186
def kind_marker(kind):
188
return _kind_marker_map[kind]
190
# Slightly faster than using .get(, '') when the common case is that
74
elif kind == 'directory':
76
elif kind == 'symlink':
79
raise BzrError('invalid file kind %r' % kind)
84
"""Copy a file to a backup.
86
Backups are named in GNU-style, with a ~ suffix.
88
If the file is already a backup, it's not copied.
101
outf = file(bfn, 'wb')
107
def rename(path_from, path_to):
108
"""Basically the same as os.rename() just special for win32"""
109
if sys.platform == 'win32':
113
if e.errno != e.ENOENT:
115
os.rename(path_from, path_to)
195
lexists = getattr(os.path, 'lexists', None)
199
stat = getattr(os, 'lstat', os.stat)
203
if e.errno == errno.ENOENT:
206
raise errors.BzrError(
207
gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
210
def fancy_rename(old, new, rename_func, unlink_func):
211
"""A fancy rename, when you don't have atomic rename.
213
:param old: The old path, to rename from
214
:param new: The new path, to rename to
215
:param rename_func: The potentially non-atomic rename function
216
:param unlink_func: A way to delete the target file if the full rename
219
# sftp rename doesn't allow overwriting, so play tricks:
220
base = os.path.basename(new)
221
dirname = os.path.dirname(new)
222
# callers use different encodings for the paths so the following MUST
223
# respect that. We rely on python upcasting to unicode if new is unicode
224
# and keeping a str if not.
225
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
226
os.getpid(), rand_chars(10))
227
tmp_name = pathjoin(dirname, tmp_name)
229
# Rename the file out of the way, but keep track if it didn't exist
230
# We don't want to grab just any exception
231
# something like EACCES should prevent us from continuing
232
# The downside is that the rename_func has to throw an exception
233
# with an errno = ENOENT, or NoSuchFile
236
rename_func(new, tmp_name)
237
except (errors.NoSuchFile,):
240
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
241
# function raises an IOError with errno is None when a rename fails.
242
# This then gets caught here.
243
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
245
except Exception as e:
246
if (getattr(e, 'errno', None) is None
247
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
254
# This may throw an exception, in which case success will
256
rename_func(old, new)
258
except (IOError, OSError) as e:
259
# source and target may be aliases of each other (e.g. on a
260
# case-insensitive filesystem), so we may have accidentally renamed
261
# source by when we tried to rename target
262
if (file_existed and e.errno in (None, errno.ENOENT)
263
and old.lower() == new.lower()):
264
# source and target are the same file on a case-insensitive
265
# filesystem, so we don't generate an exception
271
# If the file used to exist, rename it back into place
272
# otherwise just delete it from the tmp location
274
unlink_func(tmp_name)
276
rename_func(tmp_name, new)
279
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
280
# choke on a Unicode string containing a relative path if
281
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
283
def _posix_abspath(path):
284
# jam 20060426 rather than encoding to fsencoding
285
# copy posixpath.abspath, but use os.getcwdu instead
286
if not posixpath.isabs(path):
287
path = posixpath.join(getcwd(), path)
288
return _posix_normpath(path)
291
def _posix_realpath(path):
292
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
295
def _posix_normpath(path):
296
path = posixpath.normpath(path)
297
# Bug 861008: posixpath.normpath() returns a path normalized according to
298
# the POSIX standard, which stipulates (for compatibility reasons) that two
299
# leading slashes must not be simplified to one, and only if there are 3 or
300
# more should they be simplified as one. So we treat the leading 2 slashes
301
# as a special case here by simply removing the first slash, as we consider
302
# that breaking POSIX compatibility for this obscure feature is acceptable.
303
# This is not a paranoid precaution, as we notably get paths like this when
304
# the repo is hosted at the root of the filesystem, i.e. in "/".
305
if path.startswith('//'):
310
def _posix_get_home_dir():
311
"""Get the home directory of the current user as a unicode path"""
312
path = posixpath.expanduser("~")
314
return path.decode(_fs_enc)
315
except AttributeError:
317
except UnicodeDecodeError:
318
raise errors.BadFilenameEncoding(path, _fs_enc)
321
def _posix_getuser_unicode():
322
"""Get username from environment or password database as unicode"""
323
return getpass.getuser()
326
def _win32_fixdrive(path):
327
"""Force drive letters to be consistent.
329
win32 is inconsistent whether it returns lower or upper case
330
and even if it was consistent the user might type the other
331
so we force it to uppercase
332
running python.exe under cmd.exe return capital C:\\
333
running win32 python inside a cygwin shell returns lowercase c:\\
335
drive, path = ntpath.splitdrive(path)
336
return drive.upper() + path
339
def _win32_abspath(path):
340
# Real ntpath.abspath doesn't have a problem with a unicode cwd
341
return _win32_fixdrive(ntpath.abspath(path).replace('\\', '/'))
344
def _win32_realpath(path):
345
# Real ntpath.realpath doesn't have a problem with a unicode cwd
346
return _win32_fixdrive(ntpath.realpath(path).replace('\\', '/'))
349
def _win32_pathjoin(*args):
350
return ntpath.join(*args).replace('\\', '/')
353
def _win32_normpath(path):
354
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
358
return _win32_fixdrive(_getcwd().replace('\\', '/'))
361
def _win32_mkdtemp(*args, **kwargs):
362
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
365
def _win32_rename(old, new):
366
"""We expect to be able to atomically replace 'new' with old.
368
On win32, if new exists, it must be moved out of the way first,
372
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
374
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
375
# If we try to rename a non-existant file onto cwd, we get
376
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
377
# if the old path doesn't exist, sometimes we get EACCES
378
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
384
return unicodedata.normalize('NFC', _getcwd())
387
def _rename_wrap_exception(rename_func):
388
"""Adds extra information to any exceptions that come from rename().
390
The exception has an updated message and 'old_filename' and 'new_filename'
394
def _rename_wrapper(old, new):
396
rename_func(old, new)
398
detailed_error = OSError(e.errno, e.strerror +
399
" [occurred when renaming '%s' to '%s']" %
401
detailed_error.old_filename = old
402
detailed_error.new_filename = new
405
return _rename_wrapper
411
# Default rename wraps os.rename()
412
rename = _rename_wrap_exception(os.rename)
414
# Default is to just use the python builtins, but these can be rebound on
415
# particular platforms.
416
abspath = _posix_abspath
417
realpath = _posix_realpath
418
pathjoin = os.path.join
419
normpath = _posix_normpath
420
_get_home_dir = _posix_get_home_dir
421
getuser_unicode = _posix_getuser_unicode
423
dirname = os.path.dirname
424
basename = os.path.basename
425
split = os.path.split
426
splitext = os.path.splitext
427
# These were already lazily imported into local scope
428
# mkdtemp = tempfile.mkdtemp
429
# rmtree = shutil.rmtree
438
MIN_ABS_PATHLENGTH = 1
441
if sys.platform == 'win32':
442
abspath = _win32_abspath
443
realpath = _win32_realpath
444
pathjoin = _win32_pathjoin
445
normpath = _win32_normpath
446
getcwd = _win32_getcwd
447
mkdtemp = _win32_mkdtemp
448
rename = _rename_wrap_exception(_win32_rename)
450
from . import _walkdirs_win32
454
lstat = _walkdirs_win32.lstat
455
fstat = _walkdirs_win32.fstat
456
wrap_stat = _walkdirs_win32.wrap_stat
458
MIN_ABS_PATHLENGTH = 3
460
def _win32_delete_readonly(function, path, excinfo):
461
"""Error handler for shutil.rmtree function [for win32]
462
Helps to remove files and dirs marked as read-only.
464
exception = excinfo[1]
465
if function in (os.remove, os.rmdir) \
466
and isinstance(exception, OSError) \
467
and exception.errno == errno.EACCES:
473
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
474
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
475
return shutil.rmtree(path, ignore_errors, onerror)
477
_get_home_dir = win32utils.get_home_location
478
getuser_unicode = win32utils.get_user_name
480
elif sys.platform == 'darwin':
484
def get_terminal_encoding(trace=False):
485
"""Find the best encoding for printing to the screen.
487
This attempts to check both sys.stdout and sys.stdin to see
488
what encoding they are in, and if that fails it falls back to
489
osutils.get_user_encoding().
490
The problem is that on Windows, locale.getpreferredencoding()
491
is not the same encoding as that used by the console:
492
http://mail.python.org/pipermail/python-list/2003-May/162357.html
494
On my standard US Windows XP, the preferred encoding is
495
cp1252, but the console is cp437
497
:param trace: If True trace the selected encoding via mutter().
499
from .trace import mutter
500
output_encoding = getattr(sys.stdout, 'encoding', None)
501
if not output_encoding:
502
input_encoding = getattr(sys.stdin, 'encoding', None)
503
if not input_encoding:
504
output_encoding = get_user_encoding()
506
mutter('encoding stdout as osutils.get_user_encoding() %r',
509
output_encoding = input_encoding
511
mutter('encoding stdout as sys.stdin encoding %r',
515
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
516
if output_encoding == 'cp0':
517
# invalid encoding (cp0 means 'no codepage' on Windows)
518
output_encoding = get_user_encoding()
520
mutter('cp0 is invalid encoding.'
521
' encoding stdout as osutils.get_user_encoding() %r',
525
codecs.lookup(output_encoding)
527
sys.stderr.write('brz: warning:'
528
' unknown terminal encoding %s.\n'
529
' Using encoding %s instead.\n'
530
% (output_encoding, get_user_encoding())
532
output_encoding = get_user_encoding()
534
return output_encoding
537
def normalizepath(f):
538
if getattr(os.path, 'realpath', None) is not None:
542
[p, e] = os.path.split(f)
543
if e == "" or e == "." or e == "..":
546
return pathjoin(F(p), e)
122
550
"""True if f is an accessible directory."""
124
return S_ISDIR(os.lstat(f)[ST_MODE])
552
return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
131
558
"""True if f is a regular file."""
133
return S_ISREG(os.lstat(f)[ST_MODE])
560
return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
566
"""True if f is a symlink."""
568
return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
138
573
def is_inside(dir, fname):
139
574
"""True if fname is inside dir.
141
The parameters should typically be passed to os.path.normpath first, so
576
The parameters should typically be passed to osutils.normpath first, so
142
577
that . and .. and repeated slashes are eliminated, and the separators
143
578
are canonical for the platform.
145
The empty string as a dir name is taken as top-of-tree and matches
580
The empty string as a dir name is taken as top-of-tree and matches
148
>>> is_inside('src', 'src/foo.c')
150
>>> is_inside('src', 'srccontrol')
152
>>> is_inside('src', 'src/a/a/a/foo.c')
154
>>> is_inside('foo.c', 'foo.c')
156
>>> is_inside('foo.c', '')
158
>>> is_inside('', 'foo.c')
161
# XXX: Most callers of this can actually do something smarter by
583
# XXX: Most callers of this can actually do something smarter by
162
584
# looking at the inventory
169
if dir[-1] != os.sep:
591
if isinstance(dir, bytes):
592
if not dir.endswith(b'/'):
595
if not dir.endswith('/'):
172
598
return fname.startswith(dir)
432
## TODO: We could later have path objects that remember their list
433
## decomposition (might be too tricksy though.)
952
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
956
"""Return a random string of num alphanumeric characters
958
The result only contains lowercase chars because it may be used on
959
case-insensitive filesystems.
962
for raw_byte in rand_bytes(num):
963
s += ALNUM[raw_byte % 36]
967
# TODO: We could later have path objects that remember their list
968
# decomposition (might be too tricksy though.)
435
970
def splitpath(p):
436
"""Turn string into list of parts.
442
>>> splitpath('a/./b')
444
>>> splitpath('a/.b')
446
>>> splitpath('a/../b')
447
Traceback (most recent call last):
449
BzrError: sorry, '..' not allowed in path
451
assert isinstance(p, types.StringTypes)
453
# split on either delimiter because people might use either on
455
ps = re.split(r'[\\/]', p)
971
"""Turn string into list of parts."""
972
use_bytes = isinstance(p, bytes)
973
if os.path.sep == '\\':
974
# split on either delimiter because people might use either on
977
ps = re.split(b'[\\\\/]', p)
979
ps = re.split(r'[\\/]', p)
988
current_empty_dir = (b'.', b'')
991
current_empty_dir = ('.', '')
460
raise BzrError("sorry, %r not allowed in path" % f)
461
elif (f == '.') or (f == ''):
996
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
997
elif f in current_empty_dir:
467
1004
def joinpath(p):
468
assert isinstance(p, list)
470
if (f == '..') or (f == None) or (f == ''):
471
raise BzrError("sorry, %r not allowed in path" % f)
472
return os.path.join(*p)
475
def appendpath(p1, p2):
479
return os.path.join(p1, p2)
482
def extern_command(cmd, ignore_errors = False):
483
mutter('external command: %s' % `cmd`)
485
if not ignore_errors:
486
raise BzrError('command failed')
489
def _read_config_value(name):
490
"""Read a config value from the file ~/.bzr.conf/<name>
491
Return None if the file does not exist"""
493
f = file(os.path.join(config_dir(), name), "r")
494
return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
496
if e.errno == errno.ENOENT:
1006
if (f == '..') or (f is None) or (f == ''):
1007
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
1011
def parent_directories(filename):
1012
"""Return the list of parent directories, deepest first.
1014
For example, parent_directories("a/b/c") -> ["a/b", "a"].
1017
parts = splitpath(dirname(filename))
1019
parents.append(joinpath(parts))
1024
_extension_load_failures = []
1027
def failed_to_load_extension(exception):
1028
"""Handle failing to load a binary extension.
1030
This should be called from the ImportError block guarding the attempt to
1031
import the native extension. If this function returns, the pure-Python
1032
implementation should be loaded instead::
1035
>>> import breezy._fictional_extension_pyx
1036
>>> except ImportError, e:
1037
>>> breezy.osutils.failed_to_load_extension(e)
1038
>>> import breezy._fictional_extension_py
1040
# NB: This docstring is just an example, not a doctest, because doctest
1041
# currently can't cope with the use of lazy imports in this namespace --
1044
# This currently doesn't report the failure at the time it occurs, because
1045
# they tend to happen very early in startup when we can't check config
1046
# files etc, and also we want to report all failures but not spam the user
1048
exception_str = str(exception)
1049
if exception_str not in _extension_load_failures:
1050
trace.mutter("failed to load compiled extension: %s" % exception_str)
1051
_extension_load_failures.append(exception_str)
1054
def report_extension_load_failures():
1055
if not _extension_load_failures:
1057
if config.GlobalConfig().suppress_warning('missing_extensions'):
1059
# the warnings framework should by default show this only once
1060
from .trace import warning
1062
"brz: warning: some compiled extensions could not be loaded; "
1063
"see ``brz help missing-extensions``")
1064
# we no longer show the specific missing extensions here, because it makes
1065
# the message too long and scary - see
1066
# https://bugs.launchpad.net/bzr/+bug/430529
1070
from ._chunks_to_lines_pyx import chunks_to_lines
1071
except ImportError as e:
1072
failed_to_load_extension(e)
1073
from ._chunks_to_lines_py import chunks_to_lines
1077
"""Split s into lines, but without removing the newline characters."""
1078
# Trivially convert a fulltext into a 'chunked' representation, and let
1079
# chunks_to_lines do the heavy lifting.
1080
if isinstance(s, bytes):
1081
# chunks_to_lines only supports 8-bit strings
1082
return chunks_to_lines([s])
1084
return _split_lines(s)
1087
def _split_lines(s):
1088
"""Split s into lines, but without removing the newline characters.
1090
This supports Unicode or plain string objects.
1092
nl = b'\n' if isinstance(s, bytes) else u'\n'
1094
result = [line + nl for line in lines[:-1]]
1096
result.append(lines[-1])
1100
def hardlinks_good():
1101
return sys.platform not in ('win32', 'cygwin', 'darwin')
1104
def link_or_copy(src, dest):
1105
"""Hardlink a file, or copy it if it can't be hardlinked."""
1106
if not hardlinks_good():
1107
shutil.copyfile(src, dest)
1111
except (OSError, IOError) as e:
1112
if e.errno != errno.EXDEV:
1114
shutil.copyfile(src, dest)
1117
def delete_any(path):
1118
"""Delete a file, symlink or directory.
1120
Will delete even if readonly.
1123
_delete_file_or_dir(path)
1124
except (OSError, IOError) as e:
1125
if e.errno in (errno.EPERM, errno.EACCES):
1126
# make writable and try again
1129
except (OSError, IOError):
1131
_delete_file_or_dir(path)
1136
def _delete_file_or_dir(path):
1137
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1138
# Forgiveness than Permission (EAFP) because:
1139
# - root can damage a solaris file system by using unlink,
1140
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1141
# EACCES, OSX: EPERM) when invoked on a directory.
1142
if isdir(path): # Takes care of symlinks
1149
if getattr(os, 'symlink', None) is not None:
1155
def has_hardlinks():
1156
if getattr(os, 'link', None) is not None:
1162
def host_os_dereferences_symlinks():
1163
return (has_symlinks()
1164
and sys.platform not in ('cygwin', 'win32'))
1167
def readlink(abspath):
1168
"""Return a string representing the path to which the symbolic link points.
1170
:param abspath: The link absolute unicode path.
1172
This his guaranteed to return the symbolic link in unicode in all python
1175
link = abspath.encode(_fs_enc)
1176
target = os.readlink(link)
1177
target = target.decode(_fs_enc)
1181
def contains_whitespace(s):
1182
"""True if there are any whitespace characters in s."""
1183
# string.whitespace can include '\xa0' in certain locales, because it is
1184
# considered "non-breaking-space" as part of ISO-8859-1. But it
1185
# 1) Isn't a breaking whitespace
1186
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1188
# 3) '\xa0' isn't unicode safe since it is >128.
1190
if isinstance(s, str):
1193
ws = (b' ', b'\t', b'\n', b'\r', b'\v', b'\f')
1201
def contains_linebreaks(s):
1202
"""True if there is any vertical whitespace in s."""
1210
def relpath(base, path):
1211
"""Return path relative to base, or raise PathNotChild exception.
1213
The path may be either an absolute path or a path relative to the
1214
current working directory.
1216
os.path.commonprefix (python2.4) has a bad bug that it works just
1217
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1218
avoids that problem.
1220
NOTE: `base` should not have a trailing slash otherwise you'll get
1221
PathNotChild exceptions regardless of `path`.
1224
if len(base) < MIN_ABS_PATHLENGTH:
1225
# must have space for e.g. a drive letter
1226
raise ValueError(gettext('%r is too short to calculate a relative path')
1234
if len(head) <= len(base) and head != base:
1235
raise errors.PathNotChild(rp, base)
1238
head, tail = split(head)
1243
return pathjoin(*reversed(s))
1248
def _cicp_canonical_relpath(base, path):
1249
"""Return the canonical path relative to base.
1251
Like relpath, but on case-insensitive-case-preserving file-systems, this
1252
will return the relpath as stored on the file-system rather than in the
1253
case specified in the input string, for all existing portions of the path.
1255
This will cause O(N) behaviour if called for every path in a tree; if you
1256
have a number of paths to convert, you should use canonical_relpaths().
1258
# TODO: it should be possible to optimize this for Windows by using the
1259
# win32 API FindFiles function to look for the specified name - but using
1260
# os.listdir() still gives us the correct, platform agnostic semantics in
1263
rel = relpath(base, path)
1264
# '.' will have been turned into ''
1268
abs_base = abspath(base)
1271
# use an explicit iterator so we can easily consume the rest on early exit.
1272
bit_iter = iter(rel.split('/'))
1273
for bit in bit_iter:
1276
next_entries = scandir(current)
1277
except OSError: # enoent, eperm, etc
1278
# We can't find this in the filesystem, so just append the
1280
current = pathjoin(current, bit, *list(bit_iter))
1282
for entry in next_entries:
1283
if lbit == entry.name.lower():
1284
current = entry.path
1287
# got to the end, nothing matched, so we just return the
1288
# non-existing bits as they were specified (the filename may be
1289
# the target of a move, for example).
1290
current = pathjoin(current, bit, *list(bit_iter))
1292
return current[len(abs_base):].lstrip('/')
1295
# XXX - TODO - we need better detection/integration of case-insensitive
1296
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1297
# filesystems), for example, so could probably benefit from the same basic
1298
# support there. For now though, only Windows and OSX get that support, and
1299
# they get it for *all* file-systems!
1300
if sys.platform in ('win32', 'darwin'):
1301
canonical_relpath = _cicp_canonical_relpath
1303
canonical_relpath = relpath
1306
def canonical_relpaths(base, paths):
1307
"""Create an iterable to canonicalize a sequence of relative paths.
1309
The intent is for this implementation to use a cache, vastly speeding
1310
up multiple transformations in the same directory.
1312
# but for now, we haven't optimized...
1313
return [canonical_relpath(base, p) for p in paths]
1316
def decode_filename(filename):
1317
"""Decode the filename using the filesystem encoding
1319
If it is unicode, it is returned.
1320
Otherwise it is decoded from the the filesystem's encoding. If decoding
1321
fails, a errors.BadFilenameEncoding exception is raised.
1323
if isinstance(filename, str):
1326
return filename.decode(_fs_enc)
1327
except UnicodeDecodeError:
1328
raise errors.BadFilenameEncoding(filename, _fs_enc)
1331
def safe_unicode(unicode_or_utf8_string):
1332
"""Coerce unicode_or_utf8_string into unicode.
1334
If it is unicode, it is returned.
1335
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1336
wrapped in a BzrBadParameterNotUnicode exception.
1338
if isinstance(unicode_or_utf8_string, str):
1339
return unicode_or_utf8_string
1341
return unicode_or_utf8_string.decode('utf8')
1342
except UnicodeDecodeError:
1343
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1346
def safe_utf8(unicode_or_utf8_string):
1347
"""Coerce unicode_or_utf8_string to a utf8 string.
1349
If it is a str, it is returned.
1350
If it is Unicode, it is encoded into a utf-8 string.
1352
if isinstance(unicode_or_utf8_string, bytes):
1353
# TODO: jam 20070209 This is overkill, and probably has an impact on
1354
# performance if we are dealing with lots of apis that want a
1357
# Make sure it is a valid utf-8 string
1358
unicode_or_utf8_string.decode('utf-8')
1359
except UnicodeDecodeError:
1360
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1361
return unicode_or_utf8_string
1362
return unicode_or_utf8_string.encode('utf-8')
1365
_platform_normalizes_filenames = False
1366
if sys.platform == 'darwin':
1367
_platform_normalizes_filenames = True
1370
def normalizes_filenames():
1371
"""Return True if this platform normalizes unicode filenames.
1375
return _platform_normalizes_filenames
1378
def _accessible_normalized_filename(path):
1379
"""Get the unicode normalized path, and if you can access the file.
1381
On platforms where the system normalizes filenames (Mac OSX),
1382
you can access a file by any path which will normalize correctly.
1383
On platforms where the system does not normalize filenames
1384
(everything else), you have to access a file by its exact path.
1386
Internally, bzr only supports NFC normalization, since that is
1387
the standard for XML documents.
1389
So return the normalized path, and a flag indicating if the file
1390
can be accessed by that path.
1393
if isinstance(path, bytes):
1394
path = path.decode(sys.getfilesystemencoding())
1395
return unicodedata.normalize('NFC', path), True
1398
def _inaccessible_normalized_filename(path):
1399
__doc__ = _accessible_normalized_filename.__doc__
1401
if isinstance(path, bytes):
1402
path = path.decode(sys.getfilesystemencoding())
1403
normalized = unicodedata.normalize('NFC', path)
1404
return normalized, normalized == path
1407
if _platform_normalizes_filenames:
1408
normalized_filename = _accessible_normalized_filename
1410
normalized_filename = _inaccessible_normalized_filename
1413
def set_signal_handler(signum, handler, restart_syscall=True):
1414
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1415
on platforms that support that.
1417
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1418
automatically restart (by calling `signal.siginterrupt(signum,
1419
False)`). May be ignored if the feature is not available on this
1420
platform or Python version.
1424
siginterrupt = signal.siginterrupt
1426
# This python implementation doesn't provide signal support, hence no
1429
except AttributeError:
1430
# siginterrupt doesn't exist on this platform, or for this version
1432
def siginterrupt(signum, flag): return None
1434
def sig_handler(*args):
1435
# Python resets the siginterrupt flag when a signal is
1436
# received. <http://bugs.python.org/issue8354>
1437
# As a workaround for some cases, set it back the way we want it.
1438
siginterrupt(signum, False)
1439
# Now run the handler function passed to set_signal_handler.
1442
sig_handler = handler
1443
old_handler = signal.signal(signum, sig_handler)
1445
siginterrupt(signum, False)
1449
default_terminal_width = 80
1450
"""The default terminal width for ttys.
1452
This is defined so that higher levels can share a common fallback value when
1453
terminal_width() returns None.
1456
# Keep some state so that terminal_width can detect if _terminal_size has
1457
# returned a different size since the process started. See docstring and
1458
# comments of terminal_width for details.
1459
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1460
_terminal_size_state = 'no_data'
1461
_first_terminal_size = None
1464
def terminal_width():
1465
"""Return terminal width.
1467
None is returned if the width can't established precisely.
1470
- if BRZ_COLUMNS is set, returns its value
1471
- if there is no controlling terminal, returns None
1472
- query the OS, if the queried size has changed since the last query,
1474
- if COLUMNS is set, returns its value,
1475
- if the OS has a value (even though it's never changed), return its value.
1477
From there, we need to query the OS to get the size of the controlling
1480
On Unices we query the OS by:
1481
- get termios.TIOCGWINSZ
1482
- if an error occurs or a negative value is obtained, returns None
1484
On Windows we query the OS by:
1485
- win32utils.get_console_size() decides,
1486
- returns None on error (provided default value)
1488
# Note to implementors: if changing the rules for determining the width,
1489
# make sure you've considered the behaviour in these cases:
1490
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1491
# - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1493
# - (add more interesting cases here, if you find any)
1494
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1495
# but we don't want to register a signal handler because it is impossible
1496
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1497
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1498
# time so we can notice if the reported size has changed, which should have
1501
# If BRZ_COLUMNS is set, take it, user is always right
1502
# Except if they specified 0 in which case, impose no limit here
1504
width = int(os.environ['BRZ_COLUMNS'])
1505
except (KeyError, ValueError):
1507
if width is not None:
1513
isatty = getattr(sys.stdout, 'isatty', None)
1514
if isatty is None or not isatty():
1515
# Don't guess, setting BRZ_COLUMNS is the recommended way to override.
1519
width, height = os_size = _terminal_size(None, None)
1520
global _first_terminal_size, _terminal_size_state
1521
if _terminal_size_state == 'no_data':
1522
_first_terminal_size = os_size
1523
_terminal_size_state = 'unchanged'
1524
elif (_terminal_size_state == 'unchanged' and
1525
_first_terminal_size != os_size):
1526
_terminal_size_state = 'changed'
1528
# If the OS claims to know how wide the terminal is, and this value has
1529
# ever changed, use that.
1530
if _terminal_size_state == 'changed':
1531
if width is not None and width > 0:
1534
# If COLUMNS is set, use it.
1536
return int(os.environ['COLUMNS'])
1537
except (KeyError, ValueError):
1540
# Finally, use an unchanged size from the OS, if we have one.
1541
if _terminal_size_state == 'unchanged':
1542
if width is not None and width > 0:
1545
# The width could not be determined.
1549
def _win32_terminal_size(width, height):
1550
width, height = win32utils.get_console_size(
1551
defaultx=width, defaulty=height)
1552
return width, height
1555
def _ioctl_terminal_size(width, height):
1560
s = struct.pack('HHHH', 0, 0, 0, 0)
1561
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1562
height, width = struct.unpack('HHHH', x)[0:2]
1563
except (IOError, AttributeError):
1565
return width, height
1568
_terminal_size = None
1569
"""Returns the terminal size as (width, height).
1571
:param width: Default value for width.
1572
:param height: Default value for height.
1574
This is defined specifically for each OS and query the size of the controlling
1575
terminal. If any error occurs, the provided default values should be returned.
1577
if sys.platform == 'win32':
1578
_terminal_size = _win32_terminal_size
1580
_terminal_size = _ioctl_terminal_size
1583
def supports_executable(path):
1584
"""Return if filesystem at path supports executable bit.
1586
:param path: Path for which to check the file system
1587
:return: boolean indicating whether executable bit can be stored/relied upon
1589
if sys.platform == 'win32':
1592
fs_type = get_fs_type(path)
1593
except errors.DependencyNotPresent as e:
1594
trace.mutter('Unable to get fs type for %r: %s', path, e)
1596
if fs_type in ('vfat', 'ntfs'):
1597
# filesystems known to not support executable bit
1602
def supports_symlinks(path):
1603
"""Return if the filesystem at path supports the creation of symbolic links.
1606
if not has_symlinks():
1609
fs_type = get_fs_type(path)
1610
except errors.DependencyNotPresent as e:
1611
trace.mutter('Unable to get fs type for %r: %s', path, e)
1613
if fs_type in ('vfat', 'ntfs'):
1614
# filesystems known to not support symlinks
1619
def supports_posix_readonly():
1620
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1622
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1623
directory controls creation/deletion, etc.
1625
And under win32, readonly means that the directory itself cannot be
1626
deleted. The contents of a readonly directory can be changed, unlike POSIX
1627
where files in readonly directories cannot be added, deleted or renamed.
1629
return sys.platform != "win32"
1632
def set_or_unset_env(env_variable, value):
1633
"""Modify the environment, setting or removing the env_variable.
1635
:param env_variable: The environment variable in question
1636
:param value: The value to set the environment to. If None, then
1637
the variable will be removed.
1638
:return: The original value of the environment variable.
1640
orig_val = os.environ.get(env_variable)
1642
if orig_val is not None:
1643
del os.environ[env_variable]
1645
os.environ[env_variable] = value
1649
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1652
def check_legal_path(path):
1653
"""Check whether the supplied path is legal.
1654
This is only required on Windows, so we don't test on other platforms
1657
if sys.platform != "win32":
1659
if _validWin32PathRE.match(path) is None:
1660
raise errors.IllegalPath(path)
1663
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1667
scandir = os.scandir
1668
except AttributeError: # Python < 3
1669
lazy_import(globals(), """\
1670
from scandir import scandir
1674
def _is_error_enotdir(e):
1675
"""Check if this exception represents ENOTDIR.
1677
Unfortunately, python is very inconsistent about the exception
1678
here. The cases are:
1679
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1680
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1681
which is the windows error code.
1682
3) Windows, Python2.5 uses errno == EINVAL and
1683
winerror == ERROR_DIRECTORY
1685
:param e: An Exception object (expected to be OSError with an errno
1686
attribute, but we should be able to cope with anything)
1687
:return: True if this represents an ENOTDIR error. False otherwise.
1689
en = getattr(e, 'errno', None)
1690
if (en == errno.ENOTDIR or
1691
(sys.platform == 'win32' and
1692
(en == _WIN32_ERROR_DIRECTORY or
1694
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1700
def walkdirs(top, prefix=""):
1701
"""Yield data about all the directories in a tree.
1703
This yields all the data about the contents of a directory at a time.
1704
After each directory has been yielded, if the caller has mutated the list
1705
to exclude some directories, they are then not descended into.
1707
The data yielded is of the form:
1708
((directory-relpath, directory-path-from-top),
1709
[(relpath, basename, kind, lstat, path-from-top), ...]),
1710
- directory-relpath is the relative path of the directory being returned
1711
with respect to top. prefix is prepended to this.
1712
- directory-path-from-root is the path including top for this directory.
1713
It is suitable for use with os functions.
1714
- relpath is the relative path within the subtree being walked.
1715
- basename is the basename of the path
1716
- kind is the kind of the file now. If unknown then the file is not
1717
present within the tree - but it may be recorded as versioned. See
1719
- lstat is the stat data *if* the file was statted.
1720
- planned, not implemented:
1721
path_from_tree_root is the path from the root of the tree.
1723
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1724
allows one to walk a subtree but get paths that are relative to a tree
1726
:return: an iterator over the dirs.
1728
# TODO there is a bit of a smell where the results of the directory-
1729
# summary in this, and the path from the root, may not agree
1730
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1731
# potentially confusing output. We should make this more robust - but
1732
# not at a speed cost. RBC 20060731
1733
_directory = _directory_kind
1734
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1736
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1737
relroot, _, _, _, top = pending.pop()
1739
relprefix = relroot + u'/'
1742
top_slash = top + u'/'
1746
for entry in scandir(top):
1747
name = decode_filename(entry.name)
1748
statvalue = entry.stat(follow_symlinks=False)
1749
kind = file_kind_from_stat_mode(statvalue.st_mode)
1750
dirblock.append((relprefix + name, name, kind, statvalue, entry.path))
1751
except OSError as e:
1752
if not _is_error_enotdir(e):
1754
except UnicodeDecodeError as e:
1755
raise errors.BadFilenameEncoding(e.object, _fs_enc)
1757
yield (relroot, top), dirblock
1759
# push the user specified dirs from dirblock
1760
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1763
class DirReader(object):
1764
"""An interface for reading directories."""
1766
def top_prefix_to_starting_dir(self, top, prefix=""):
1767
"""Converts top and prefix to a starting dir entry
1769
:param top: A utf8 path
1770
:param prefix: An optional utf8 path to prefix output relative paths
1772
:return: A tuple starting with prefix, and ending with the native
1775
raise NotImplementedError(self.top_prefix_to_starting_dir)
1777
def read_dir(self, prefix, top):
1778
"""Read a specific dir.
1780
:param prefix: A utf8 prefix to be preprended to the path basenames.
1781
:param top: A natively encoded path to read.
1782
:return: A list of the directories contents. Each item contains:
1783
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1785
raise NotImplementedError(self.read_dir)
1788
_selected_dir_reader = None
1791
def _walkdirs_utf8(top, prefix=""):
1792
"""Yield data about all the directories in a tree.
1794
This yields the same information as walkdirs() only each entry is yielded
1795
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1796
are returned as exact byte-strings.
1798
:return: yields a tuple of (dir_info, [file_info])
1799
dir_info is (utf8_relpath, path-from-top)
1800
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1801
if top is an absolute path, path-from-top is also an absolute path.
1802
path-from-top might be unicode or utf8, but it is the correct path to
1803
pass to os functions to affect the file in question. (such as os.lstat)
1805
global _selected_dir_reader
1806
if _selected_dir_reader is None:
1807
if sys.platform == "win32":
1809
from ._walkdirs_win32 import Win32ReadDir
1810
_selected_dir_reader = Win32ReadDir()
1813
elif _fs_enc in ('utf-8', 'ascii'):
1815
from ._readdir_pyx import UTF8DirReader
1816
_selected_dir_reader = UTF8DirReader()
1817
except ImportError as e:
1818
failed_to_load_extension(e)
1821
if _selected_dir_reader is None:
1822
# Fallback to the python version
1823
_selected_dir_reader = UnicodeDirReader()
1825
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1826
# But we don't actually uses 1-3 in pending, so set them to None
1827
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1828
read_dir = _selected_dir_reader.read_dir
1829
_directory = _directory_kind
1831
relroot, _, _, _, top = pending[-1].pop()
1834
dirblock = sorted(read_dir(relroot, top))
1835
yield (relroot, top), dirblock
1836
# push the user specified dirs from dirblock
1837
next = [d for d in reversed(dirblock) if d[2] == _directory]
1839
pending.append(next)
1842
class UnicodeDirReader(DirReader):
1843
"""A dir reader for non-utf8 file systems, which transcodes."""
1845
__slots__ = ['_utf8_encode']
1848
self._utf8_encode = codecs.getencoder('utf8')
1850
def top_prefix_to_starting_dir(self, top, prefix=""):
1851
"""See DirReader.top_prefix_to_starting_dir."""
1852
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1854
def read_dir(self, prefix, top):
1855
"""Read a single directory from a non-utf8 file system.
1857
top, and the abspath element in the output are unicode, all other paths
1858
are utf8. Local disk IO is done via unicode calls to listdir etc.
1860
This is currently the fallback code path when the filesystem encoding is
1861
not UTF-8. It may be better to implement an alternative so that we can
1862
safely handle paths that are not properly decodable in the current
1865
See DirReader.read_dir for details.
1867
_utf8_encode = self._utf8_encode
1869
def _fs_decode(s): return s.decode(_fs_enc)
1871
def _fs_encode(s): return s.encode(_fs_enc)
1874
relprefix = prefix + b'/'
1877
top_slash = top + '/'
1880
append = dirblock.append
1881
for entry in scandir(safe_utf8(top)):
1883
name = _fs_decode(entry.name)
1884
except UnicodeDecodeError:
1885
raise errors.BadFilenameEncoding(
1886
relprefix + entry.name, _fs_enc)
1887
abspath = top_slash + name
1888
name_utf8 = _utf8_encode(name)[0]
1889
statvalue = entry.stat(follow_symlinks=False)
1890
kind = file_kind_from_stat_mode(statvalue.st_mode)
1891
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1892
return sorted(dirblock)
1895
def copy_tree(from_path, to_path, handlers={}):
1896
"""Copy all of the entries in from_path into to_path.
1898
:param from_path: The base directory to copy.
1899
:param to_path: The target directory. If it does not exist, it will
1901
:param handlers: A dictionary of functions, which takes a source and
1902
destinations for files, directories, etc.
1903
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1904
'file', 'directory', and 'symlink' should always exist.
1905
If they are missing, they will be replaced with 'os.mkdir()',
1906
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1908
# Now, just copy the existing cached tree to the new location
1909
# We use a cheap trick here.
1910
# Absolute paths are prefixed with the first parameter
1911
# relative paths are prefixed with the second.
1912
# So we can get both the source and target returned
1913
# without any extra work.
1915
def copy_dir(source, dest):
1918
def copy_link(source, dest):
1919
"""Copy the contents of a symlink"""
1920
link_to = os.readlink(source)
1921
os.symlink(link_to, dest)
1923
real_handlers = {'file': shutil.copy2,
1924
'symlink': copy_link,
1925
'directory': copy_dir,
1927
real_handlers.update(handlers)
1929
if not os.path.exists(to_path):
1930
real_handlers['directory'](from_path, to_path)
1932
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1933
for relpath, name, kind, st, abspath in entries:
1934
real_handlers[kind](abspath, relpath)
1937
def copy_ownership_from_path(dst, src=None):
1938
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1940
If src is None, the containing directory is used as source. If chown
1941
fails, the error is ignored and a warning is printed.
1943
chown = getattr(os, 'chown', None)
1948
src = os.path.dirname(dst)
1954
chown(dst, s.st_uid, s.st_gid)
1957
'Unable to copy ownership from "%s" to "%s". '
1958
'You may want to set it manually.', src, dst)
1959
trace.log_exception_quietly()
1962
def path_prefix_key(path):
1963
"""Generate a prefix-order path key for path.
1965
This can be used to sort paths in the same way that walkdirs does.
1967
return (dirname(path), path)
1970
def compare_paths_prefix_order(path_a, path_b):
1971
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1972
key_a = path_prefix_key(path_a)
1973
key_b = path_prefix_key(path_b)
1974
return (key_a > key_b) - (key_a < key_b)
1977
_cached_user_encoding = None
1980
def get_user_encoding():
1981
"""Find out what the preferred user encoding is.
1983
This is generally the encoding that is used for command line parameters
1984
and file contents. This may be different from the terminal encoding
1985
or the filesystem encoding.
1987
:return: A string defining the preferred user encoding
1989
global _cached_user_encoding
1990
if _cached_user_encoding is not None:
1991
return _cached_user_encoding
1993
if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
1994
# Use the existing locale settings and call nl_langinfo directly
1995
# rather than going through getpreferredencoding. This avoids
1996
# <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
1997
# possibility of the setlocale call throwing an error.
1998
user_encoding = locale.nl_langinfo(locale.CODESET)
2000
# GZ 2011-12-19: On windows could call GetACP directly instead.
2001
user_encoding = locale.getpreferredencoding(False)
2004
user_encoding = codecs.lookup(user_encoding).name
2006
if user_encoding not in ("", "cp0"):
2007
sys.stderr.write('brz: warning:'
2008
' unknown encoding %s.'
2009
' Continuing with ascii encoding.\n'
2012
user_encoding = 'ascii'
2014
# Get 'ascii' when setlocale has not been called or LANG=C or unset.
2015
if user_encoding == 'ascii':
2016
if sys.platform == 'darwin':
2017
# OSX is special-cased in Python to have a UTF-8 filesystem
2018
# encoding and previously had LANG set here if not present.
2019
user_encoding = 'utf-8'
2020
# GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2021
# for some other posix platforms as well.
2023
_cached_user_encoding = user_encoding
2024
return user_encoding
2027
def get_diff_header_encoding():
2028
return get_terminal_encoding()
2031
def get_host_name():
2032
"""Return the current unicode host name.
2034
This is meant to be used in place of socket.gethostname() because that
2035
behaves inconsistently on different platforms.
2037
if sys.platform == "win32":
2038
return win32utils.get_host_name()
2041
return socket.gethostname()
2044
# We must not read/write any more than 64k at a time from/to a socket so we
2045
# don't risk "no buffer space available" errors on some platforms. Windows in
2046
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2048
MAX_SOCKET_CHUNK = 64 * 1024
2050
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
2051
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2052
_eno = getattr(errno, _eno, None)
2053
if _eno is not None:
2054
_end_of_stream_errors.append(_eno)
2058
def read_bytes_from_socket(sock, report_activity=None,
2059
max_read_size=MAX_SOCKET_CHUNK):
2060
"""Read up to max_read_size of bytes from sock and notify of progress.
2062
Translates "Connection reset by peer" into file-like EOF (return an
2063
empty string rather than raise an error), and repeats the recv if
2064
interrupted by a signal.
2068
data = sock.recv(max_read_size)
2069
except socket.error as e:
2071
if eno in _end_of_stream_errors:
2072
# The connection was closed by the other side. Callers expect
2073
# an empty string to signal end-of-stream.
2075
elif eno == errno.EINTR:
2076
# Retry the interrupted recv.
2080
if report_activity is not None:
2081
report_activity(len(data), 'read')
2085
def recv_all(socket, count):
2086
"""Receive an exact number of bytes.
2088
Regular Socket.recv() may return less than the requested number of bytes,
2089
depending on what's in the OS buffer. MSG_WAITALL is not available
2090
on all platforms, but this should work everywhere. This will return
2091
less than the requested amount if the remote end closes.
2093
This isn't optimized and is intended mostly for use in testing.
2096
while len(b) < count:
2097
new = read_bytes_from_socket(socket, None, count - len(b))
2104
def send_all(sock, bytes, report_activity=None):
2105
"""Send all bytes on a socket.
2107
Breaks large blocks in smaller chunks to avoid buffering limitations on
2108
some platforms, and catches EINTR which may be thrown if the send is
2109
interrupted by a signal.
2111
This is preferred to socket.sendall(), because it avoids portability bugs
2112
and provides activity reporting.
2114
:param report_activity: Call this as bytes are read, see
2115
Transport._report_activity
2118
byte_count = len(bytes)
2119
view = memoryview(bytes)
2120
while sent_total < byte_count:
2122
sent = sock.send(view[sent_total:sent_total + MAX_SOCKET_CHUNK])
2123
except (socket.error, IOError) as e:
2124
if e.args[0] in _end_of_stream_errors:
2125
raise errors.ConnectionReset(
2126
"Error trying to write to socket", e)
2127
if e.args[0] != errno.EINTR:
2131
raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2134
if report_activity is not None:
2135
report_activity(sent, 'write')
2138
def connect_socket(address):
2139
# Slight variation of the socket.create_connection() function (provided by
2140
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2141
# provide it for previous python versions. Also, we don't use the timeout
2142
# parameter (provided by the python implementation) so we don't implement
2144
err = socket.error('getaddrinfo returns an empty list')
2145
host, port = address
2146
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2147
af, socktype, proto, canonname, sa = res
2150
sock = socket.socket(af, socktype, proto)
2154
except socket.error as e:
2156
# 'err' is now the most recent error
2157
if sock is not None:
2162
def dereference_path(path):
2163
"""Determine the real path to a file.
2165
All parent elements are dereferenced. But the file itself is not
2167
:param path: The original path. May be absolute or relative.
2168
:return: the real path *to* the file
2170
parent, base = os.path.split(path)
2171
# The pathjoin for '.' is a workaround for Python bug #1213894.
2172
# (initial path components aren't dereferenced)
2173
return pathjoin(realpath(pathjoin('.', parent)), base)
2176
def supports_mapi():
2177
"""Return True if we can use MAPI to launch a mail client."""
2178
return sys.platform == "win32"
2181
def resource_string(package, resource_name):
2182
"""Load a resource from a package and return it as a string.
2184
Note: Only packages that start with breezy are currently supported.
2186
This is designed to be a lightweight implementation of resource
2187
loading in a way which is API compatible with the same API from
2189
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
2190
If and when pkg_resources becomes a standard library, this routine
2193
# Check package name is within breezy
2194
if package == "breezy":
2195
resource_relpath = resource_name
2196
elif package.startswith("breezy."):
2197
package = package[len("breezy."):].replace('.', os.sep)
2198
resource_relpath = pathjoin(package, resource_name)
2200
raise errors.BzrError('resource package %s not in breezy' % package)
2202
# Map the resource to a file and read its contents
2203
base = dirname(breezy.__file__)
2204
if getattr(sys, 'frozen', None): # bzr.exe
2205
base = abspath(pathjoin(base, '..', '..'))
2206
with open(pathjoin(base, resource_relpath), "rt") as f:
2210
def file_kind_from_stat_mode_thunk(mode):
2211
global file_kind_from_stat_mode
2212
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2214
from ._readdir_pyx import UTF8DirReader
2215
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2217
# This is one time where we won't warn that an extension failed to
2218
# load. The extension is never available on Windows anyway.
2219
from ._readdir_py import (
2220
_kind_from_mode as file_kind_from_stat_mode
2222
return file_kind_from_stat_mode(mode)
2225
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2228
def file_stat(f, _lstat=os.lstat):
2232
except OSError as e:
2233
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2234
raise errors.NoSuchFile(f)
2238
def file_kind(f, _lstat=os.lstat):
2239
stat_value = file_stat(f, _lstat)
2240
return file_kind_from_stat_mode(stat_value.st_mode)
2243
def until_no_eintr(f, *a, **kw):
2244
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2246
WARNING: you must be certain that it is safe to retry the call repeatedly
2247
if EINTR does occur. This is typically only true for low-level operations
2248
like os.read. If in any doubt, don't use this.
2250
Keep in mind that this is not a complete solution to EINTR. There is
2251
probably code in the Python standard library and other dependencies that
2252
may encounter EINTR if a signal arrives (and there is signal handler for
2253
that signal). So this function can reduce the impact for IO that breezy
2254
directly controls, but it is not a complete solution.
2256
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2260
except (IOError, OSError) as e:
2261
if e.errno == errno.EINTR:
2266
if sys.platform == "win32":
2269
return msvcrt.getch()
2274
fd = sys.stdin.fileno()
2275
settings = termios.tcgetattr(fd)
2278
ch = sys.stdin.read(1)
2280
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2283
if sys.platform.startswith('linux'):
2284
def _local_concurrency():
2286
return os.sysconf('SC_NPROCESSORS_ONLN')
2287
except (ValueError, OSError, AttributeError):
2289
elif sys.platform == 'darwin':
2290
def _local_concurrency():
2291
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2292
stdout=subprocess.PIPE).communicate()[0]
2293
elif "bsd" in sys.platform:
2294
def _local_concurrency():
2295
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2296
stdout=subprocess.PIPE).communicate()[0]
2297
elif sys.platform == 'sunos5':
2298
def _local_concurrency():
2299
return subprocess.Popen(['psrinfo', '-p', ],
2300
stdout=subprocess.PIPE).communicate()[0]
2301
elif sys.platform == "win32":
2302
def _local_concurrency():
2303
# This appears to return the number of cores.
2304
return os.environ.get('NUMBER_OF_PROCESSORS')
2306
def _local_concurrency():
2311
_cached_local_concurrency = None
2314
def local_concurrency(use_cache=True):
2315
"""Return how many processes can be run concurrently.
2317
Rely on platform specific implementations and default to 1 (one) if
2318
anything goes wrong.
2320
global _cached_local_concurrency
2322
if _cached_local_concurrency is not None and use_cache:
2323
return _cached_local_concurrency
2325
concurrency = os.environ.get('BRZ_CONCURRENCY', None)
2326
if concurrency is None:
2327
import multiprocessing
2329
concurrency = multiprocessing.cpu_count()
2330
except NotImplementedError:
2331
# multiprocessing.cpu_count() isn't implemented on all platforms
2333
concurrency = _local_concurrency()
2334
except (OSError, IOError):
2337
concurrency = int(concurrency)
2338
except (TypeError, ValueError):
2341
_cached_local_concurrency = concurrency
2345
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2346
"""A stream writer that doesn't decode str arguments."""
2348
def __init__(self, encode, stream, errors='strict'):
2349
codecs.StreamWriter.__init__(self, stream, errors)
2350
self.encode = encode
2352
def write(self, object):
2353
if isinstance(object, str):
2354
self.stream.write(object)
2356
data, _ = self.encode(object, self.errors)
2357
self.stream.write(data)
2360
if sys.platform == 'win32':
2361
def open_file(filename, mode='r', bufsize=-1):
2362
"""This function is used to override the ``open`` builtin.
2364
But it uses O_NOINHERIT flag so the file handle is not inherited by
2365
child processes. Deleting or renaming a closed file opened with this
2366
function is not blocking child processes.
2368
writing = 'w' in mode
2369
appending = 'a' in mode
2370
updating = '+' in mode
2371
binary = 'b' in mode
2374
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2375
# for flags for each modes.
2385
flags |= os.O_WRONLY
2386
flags |= os.O_CREAT | os.O_TRUNC
2391
flags |= os.O_WRONLY
2392
flags |= os.O_CREAT | os.O_APPEND
2397
flags |= os.O_RDONLY
2399
return os.fdopen(os.open(filename, flags), mode, bufsize)
2404
def available_backup_name(base, exists):
2405
"""Find a non-existing backup file name.
2407
This will *not* create anything, this only return a 'free' entry. This
2408
should be used for checking names in a directory below a locked
2409
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2410
Leap) and generally discouraged.
2412
:param base: The base name.
2414
:param exists: A callable returning True if the path parameter exists.
2417
name = "%s.~%d~" % (base, counter)
2420
name = "%s.~%d~" % (base, counter)
2424
def set_fd_cloexec(fd):
2425
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2426
support for this is not available.
2430
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2431
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2432
except (ImportError, AttributeError):
2433
# Either the fcntl module or specific constants are not present
2437
def find_executable_on_path(name):
2438
"""Finds an executable on the PATH.
2440
On Windows, this will try to append each extension in the PATHEXT
2441
environment variable to the name, if it cannot be found with the name
2444
:param name: The base name of the executable.
2445
:return: The path to the executable found or None.
2447
if sys.platform == 'win32':
2448
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2449
exts = [ext.lower() for ext in exts]
2450
base, ext = os.path.splitext(name)
2452
if ext.lower() not in exts:
2458
path = os.environ.get('PATH')
2459
if path is not None:
2460
path = path.split(os.pathsep)
2463
f = os.path.join(d, name) + ext
2464
if os.access(f, os.X_OK):
2466
if sys.platform == 'win32':
2467
app_path = win32utils.get_app_path(name)
2468
if app_path != name:
2473
def _posix_is_local_pid_dead(pid):
2474
"""True if pid doesn't correspond to live process on this machine"""
2476
# Special meaning of unix kill: just check if it's there.
2478
except OSError as e:
2479
if e.errno == errno.ESRCH:
2480
# On this machine, and really not found: as sure as we can be
2483
elif e.errno == errno.EPERM:
2484
# exists, though not ours
2487
trace.mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2488
# Don't really know.
2491
# Exists and our process: not dead.
2495
if sys.platform == "win32":
2496
is_local_pid_dead = win32utils.is_local_pid_dead
2498
is_local_pid_dead = _posix_is_local_pid_dead
2500
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2501
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
2502
if getattr(errno, name, None) is not None]
2505
def fdatasync(fileno):
2506
"""Flush file contents to disk if possible.
2508
:param fileno: Integer OS file handle.
2509
:raises TransportNotPossible: If flushing to disk is not possible.
2511
fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2515
except IOError as e:
2516
# See bug #1075108, on some platforms fdatasync exists, but can
2517
# raise ENOTSUP. However, we are calling fdatasync to be helpful
2518
# and reduce the chance of corruption-on-powerloss situations. It
2519
# is not a mandatory call, so it is ok to suppress failures.
2520
trace.mutter("ignoring error calling fdatasync: %s" % (e,))
2521
if getattr(e, 'errno', None) not in _fdatasync_ignored:
2525
def ensure_empty_directory_exists(path, exception_class):
2526
"""Make sure a local directory exists and is empty.
2528
If it does not exist, it is created. If it exists and is not empty, an
2529
instance of exception_class is raised.
2533
except OSError as e:
2534
if e.errno != errno.EEXIST:
2536
if os.listdir(path) != []:
2537
raise exception_class(path)
2540
def read_mtab(path):
2541
"""Read an fstab-style file and extract mountpoint+filesystem information.
2543
:param path: Path to read from
2544
:yield: Tuples with mountpoints (as bytestrings) and filesystem names
2546
with open(path, 'rb') as f:
2548
if line.startswith(b'#'):
2553
yield cols[1], cols[2].decode('ascii', 'replace')
2556
MTAB_PATH = '/etc/mtab'
2558
class FilesystemFinder(object):
2559
"""Find the filesystem for a particular path."""
2561
def __init__(self, mountpoints):
2564
self._mountpoints = sorted(mountpoints, key=key, reverse=True)
2568
"""Create a FilesystemFinder from an mtab-style file.
2570
Note that this will silenty ignore mtab if it doesn't exist or can not
2573
# TODO(jelmer): Use inotify to be notified when /etc/mtab changes and
2574
# we need to re-read it.
2576
return cls(read_mtab(MTAB_PATH))
2577
except EnvironmentError as e:
2578
trace.mutter('Unable to read mtab: %s', e)
2581
def find(self, path):
2582
"""Find the filesystem used by a particular path.
2584
:param path: Path to find (bytestring or text type)
2585
:return: Filesystem name (as text type) or None, if the filesystem is
2588
for mountpoint, filesystem in self._mountpoints:
2589
if is_inside(mountpoint, path):
2594
_FILESYSTEM_FINDER = None
2597
def get_fs_type(path):
2598
"""Return the filesystem type for the partition a path is in.
2600
:param path: Path to search filesystem type for
2601
:return: A FS type, as string. E.g. "ext2"
2603
global _FILESYSTEM_FINDER
2604
if _FILESYSTEM_FINDER is None:
2605
_FILESYSTEM_FINDER = FilesystemFinder.from_mtab()
2607
if not isinstance(path, bytes):
2608
path = path.encode(_fs_enc)
2610
return _FILESYSTEM_FINDER.find(path)
2613
perf_counter = time.perf_counter