58
143
# TODO: I'm not really sure this is the best format either.x
145
if _QUOTE_RE is None:
61
146
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
63
148
if _QUOTE_RE.search(f):
64
149
return '"' + f + '"'
70
mode = os.lstat(f)[ST_MODE]
154
_directory_kind = 'directory'
157
"""Return the current umask"""
158
# Assume that people aren't messing with the umask while running
159
# XXX: This is not thread safe, but there is no way to get the
160
# umask without setting it
168
_directory_kind: "/",
170
'tree-reference': '+',
89
174
def kind_marker(kind):
176
return _kind_marker_map[kind]
178
# Slightly faster than using .get(, '') when the common case is that
92
elif kind == 'directory':
94
elif kind == 'symlink':
97
raise BzrError('invalid file kind %r' % kind)
101
if hasattr(os, 'lstat'):
107
if e.errno == errno.ENOENT:
110
raise BzrError("lstat/stat of (%r): %r" % (f, e))
183
lexists = getattr(os.path, 'lexists', None)
187
stat = getattr(os, 'lstat', os.stat)
191
if e.errno == errno.ENOENT:
194
raise errors.BzrError(gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
197
def fancy_rename(old, new, rename_func, unlink_func):
198
"""A fancy rename, when you don't have atomic rename.
200
:param old: The old path, to rename from
201
:param new: The new path, to rename to
202
:param rename_func: The potentially non-atomic rename function
203
:param unlink_func: A way to delete the target file if the full rename
206
# sftp rename doesn't allow overwriting, so play tricks:
207
base = os.path.basename(new)
208
dirname = os.path.dirname(new)
209
# callers use different encodings for the paths so the following MUST
210
# respect that. We rely on python upcasting to unicode if new is unicode
211
# and keeping a str if not.
212
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
213
os.getpid(), rand_chars(10))
214
tmp_name = pathjoin(dirname, tmp_name)
216
# Rename the file out of the way, but keep track if it didn't exist
217
# We don't want to grab just any exception
218
# something like EACCES should prevent us from continuing
219
# The downside is that the rename_func has to throw an exception
220
# with an errno = ENOENT, or NoSuchFile
223
rename_func(new, tmp_name)
224
except (errors.NoSuchFile,), e:
227
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
228
# function raises an IOError with errno is None when a rename fails.
229
# This then gets caught here.
230
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
233
if (getattr(e, 'errno', None) is None
234
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
243
# This may throw an exception, in which case success will
245
rename_func(old, new)
247
except (IOError, OSError), e:
248
# source and target may be aliases of each other (e.g. on a
249
# case-insensitive filesystem), so we may have accidentally renamed
250
# source by when we tried to rename target
251
failure_exc = sys.exc_info()
252
if (file_existed and e.errno in (None, errno.ENOENT)
253
and old.lower() == new.lower()):
254
# source and target are the same file on a case-insensitive
255
# filesystem, so we don't generate an exception
259
# If the file used to exist, rename it back into place
260
# otherwise just delete it from the tmp location
262
unlink_func(tmp_name)
264
rename_func(tmp_name, new)
265
if failure_exc is not None:
267
raise failure_exc[0], failure_exc[1], failure_exc[2]
272
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
273
# choke on a Unicode string containing a relative path if
274
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
276
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
277
def _posix_abspath(path):
278
# jam 20060426 rather than encoding to fsencoding
279
# copy posixpath.abspath, but use os.getcwdu instead
280
if not posixpath.isabs(path):
281
path = posixpath.join(getcwd(), path)
282
return _posix_normpath(path)
285
def _posix_realpath(path):
286
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
289
def _posix_normpath(path):
290
path = posixpath.normpath(path)
291
# Bug 861008: posixpath.normpath() returns a path normalized according to
292
# the POSIX standard, which stipulates (for compatibility reasons) that two
293
# leading slashes must not be simplified to one, and only if there are 3 or
294
# more should they be simplified as one. So we treat the leading 2 slashes
295
# as a special case here by simply removing the first slash, as we consider
296
# that breaking POSIX compatibility for this obscure feature is acceptable.
297
# This is not a paranoid precaution, as we notably get paths like this when
298
# the repo is hosted at the root of the filesystem, i.e. in "/".
299
if path.startswith('//'):
304
def _win32_fixdrive(path):
305
"""Force drive letters to be consistent.
307
win32 is inconsistent whether it returns lower or upper case
308
and even if it was consistent the user might type the other
309
so we force it to uppercase
310
running python.exe under cmd.exe return capital C:\\
311
running win32 python inside a cygwin shell returns lowercase c:\\
313
drive, path = ntpath.splitdrive(path)
314
return drive.upper() + path
317
def _win32_abspath(path):
318
# Real ntpath.abspath doesn't have a problem with a unicode cwd
319
return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
322
def _win98_abspath(path):
323
"""Return the absolute version of a path.
324
Windows 98 safe implementation (python reimplementation
325
of Win32 API function GetFullPathNameW)
330
# \\HOST\path => //HOST/path
331
# //HOST/path => //HOST/path
332
# path => C:/cwd/path
335
# check for absolute path
336
drive = ntpath.splitdrive(path)[0]
337
if drive == '' and path[:2] not in('//','\\\\'):
339
# we cannot simply os.path.join cwd and path
340
# because os.path.join('C:','/path') produce '/path'
341
# and this is incorrect
342
if path[:1] in ('/','\\'):
343
cwd = ntpath.splitdrive(cwd)[0]
345
path = cwd + '\\' + path
346
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
349
def _win32_realpath(path):
350
# Real ntpath.realpath doesn't have a problem with a unicode cwd
351
return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
354
def _win32_pathjoin(*args):
355
return ntpath.join(*args).replace('\\', '/')
358
def _win32_normpath(path):
359
return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
363
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
366
def _win32_mkdtemp(*args, **kwargs):
367
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
370
def _win32_rename(old, new):
371
"""We expect to be able to atomically replace 'new' with old.
373
On win32, if new exists, it must be moved out of the way first,
377
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
379
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
380
# If we try to rename a non-existant file onto cwd, we get
381
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
382
# if the old path doesn't exist, sometimes we get EACCES
383
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
389
return unicodedata.normalize('NFC', os.getcwdu())
392
# Default is to just use the python builtins, but these can be rebound on
393
# particular platforms.
394
abspath = _posix_abspath
395
realpath = _posix_realpath
396
pathjoin = os.path.join
397
normpath = _posix_normpath
400
dirname = os.path.dirname
401
basename = os.path.basename
402
split = os.path.split
403
splitext = os.path.splitext
404
# These were already lazily imported into local scope
405
# mkdtemp = tempfile.mkdtemp
406
# rmtree = shutil.rmtree
414
MIN_ABS_PATHLENGTH = 1
417
if sys.platform == 'win32':
418
if win32utils.winver == 'Windows 98':
419
abspath = _win98_abspath
421
abspath = _win32_abspath
422
realpath = _win32_realpath
423
pathjoin = _win32_pathjoin
424
normpath = _win32_normpath
425
getcwd = _win32_getcwd
426
mkdtemp = _win32_mkdtemp
427
rename = _win32_rename
429
from bzrlib import _walkdirs_win32
433
lstat = _walkdirs_win32.lstat
434
fstat = _walkdirs_win32.fstat
435
wrap_stat = _walkdirs_win32.wrap_stat
437
MIN_ABS_PATHLENGTH = 3
439
def _win32_delete_readonly(function, path, excinfo):
440
"""Error handler for shutil.rmtree function [for win32]
441
Helps to remove files and dirs marked as read-only.
443
exception = excinfo[1]
444
if function in (os.remove, os.rmdir) \
445
and isinstance(exception, OSError) \
446
and exception.errno == errno.EACCES:
452
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
453
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
454
return shutil.rmtree(path, ignore_errors, onerror)
456
f = win32utils.get_unicode_argv # special function or None
460
elif sys.platform == 'darwin':
464
def get_terminal_encoding(trace=False):
465
"""Find the best encoding for printing to the screen.
467
This attempts to check both sys.stdout and sys.stdin to see
468
what encoding they are in, and if that fails it falls back to
469
osutils.get_user_encoding().
470
The problem is that on Windows, locale.getpreferredencoding()
471
is not the same encoding as that used by the console:
472
http://mail.python.org/pipermail/python-list/2003-May/162357.html
474
On my standard US Windows XP, the preferred encoding is
475
cp1252, but the console is cp437
477
:param trace: If True trace the selected encoding via mutter().
479
from bzrlib.trace import mutter
480
output_encoding = getattr(sys.stdout, 'encoding', None)
481
if not output_encoding:
482
input_encoding = getattr(sys.stdin, 'encoding', None)
483
if not input_encoding:
484
output_encoding = get_user_encoding()
486
mutter('encoding stdout as osutils.get_user_encoding() %r',
489
output_encoding = input_encoding
491
mutter('encoding stdout as sys.stdin encoding %r',
495
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
496
if output_encoding == 'cp0':
497
# invalid encoding (cp0 means 'no codepage' on Windows)
498
output_encoding = get_user_encoding()
500
mutter('cp0 is invalid encoding.'
501
' encoding stdout as osutils.get_user_encoding() %r',
505
codecs.lookup(output_encoding)
507
sys.stderr.write('bzr: warning:'
508
' unknown terminal encoding %s.\n'
509
' Using encoding %s instead.\n'
510
% (output_encoding, get_user_encoding())
512
output_encoding = get_user_encoding()
514
return output_encoding
112
517
def normalizepath(f):
113
if hasattr(os.path, 'realpath'):
518
if getattr(os.path, 'realpath', None) is not None:
117
522
[p,e] = os.path.split(f)
118
523
if e == "" or e == "." or e == "..":
121
return os.path.join(F(p), e)
123
if os.name == "posix":
124
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
125
# choke on a Unicode string containing a relative path if
126
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
128
_fs_enc = sys.getfilesystemencoding()
130
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
132
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
134
# We need to use the Unicode-aware os.path.abspath and
135
# os.path.realpath on Windows systems.
136
abspath = os.path.abspath
137
realpath = os.path.realpath
140
"""Copy a file to a backup.
142
Backups are named in GNU-style, with a ~ suffix.
144
If the file is already a backup, it's not copied.
150
if has_symlinks() and os.path.islink(fn):
151
target = os.readlink(fn)
152
os.symlink(target, bfn)
160
outf = file(bfn, 'wb')
526
return pathjoin(F(p), e)
174
530
"""True if f is an accessible directory."""
176
return S_ISDIR(os.lstat(f)[ST_MODE])
532
return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
462
1157
def relpath(base, path):
463
"""Return path relative to base, or raise exception.
1158
"""Return path relative to base, or raise PathNotChild exception.
465
1160
The path may be either an absolute path or a path relative to the
466
1161
current working directory.
468
1163
os.path.commonprefix (python2.4) has a bad bug that it works just
469
1164
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
470
avoids that problem."""
1165
avoids that problem.
1167
NOTE: `base` should not have a trailing slash otherwise you'll get
1168
PathNotChild exceptions regardless of `path`.
1171
if len(base) < MIN_ABS_PATHLENGTH:
1172
# must have space for e.g. a drive letter
1173
raise ValueError(gettext('%r is too short to calculate a relative path')
471
1176
rp = abspath(path)
475
while len(head) >= len(base):
1181
if len(head) <= len(base) and head != base:
1182
raise errors.PathNotChild(rp, base)
476
1183
if head == base:
478
head, tail = os.path.split(head)
1185
head, tail = split(head)
482
# XXX This should raise a NotChildPath exception, as its not tied
484
raise NotBranchError("path %r is not within branch %r" % (rp, base))
486
return os.sep.join(s)
1190
return pathjoin(*reversed(s))
1195
def _cicp_canonical_relpath(base, path):
1196
"""Return the canonical path relative to base.
1198
Like relpath, but on case-insensitive-case-preserving file-systems, this
1199
will return the relpath as stored on the file-system rather than in the
1200
case specified in the input string, for all existing portions of the path.
1202
This will cause O(N) behaviour if called for every path in a tree; if you
1203
have a number of paths to convert, you should use canonical_relpaths().
1205
# TODO: it should be possible to optimize this for Windows by using the
1206
# win32 API FindFiles function to look for the specified name - but using
1207
# os.listdir() still gives us the correct, platform agnostic semantics in
1210
rel = relpath(base, path)
1211
# '.' will have been turned into ''
1215
abs_base = abspath(base)
1217
_listdir = os.listdir
1219
# use an explicit iterator so we can easily consume the rest on early exit.
1220
bit_iter = iter(rel.split('/'))
1221
for bit in bit_iter:
1224
next_entries = _listdir(current)
1225
except OSError: # enoent, eperm, etc
1226
# We can't find this in the filesystem, so just append the
1228
current = pathjoin(current, bit, *list(bit_iter))
1230
for look in next_entries:
1231
if lbit == look.lower():
1232
current = pathjoin(current, look)
1235
# got to the end, nothing matched, so we just return the
1236
# non-existing bits as they were specified (the filename may be
1237
# the target of a move, for example).
1238
current = pathjoin(current, bit, *list(bit_iter))
1240
return current[len(abs_base):].lstrip('/')
1242
# XXX - TODO - we need better detection/integration of case-insensitive
1243
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1244
# filesystems), for example, so could probably benefit from the same basic
1245
# support there. For now though, only Windows and OSX get that support, and
1246
# they get it for *all* file-systems!
1247
if sys.platform in ('win32', 'darwin'):
1248
canonical_relpath = _cicp_canonical_relpath
1250
canonical_relpath = relpath
1252
def canonical_relpaths(base, paths):
1253
"""Create an iterable to canonicalize a sequence of relative paths.
1255
The intent is for this implementation to use a cache, vastly speeding
1256
up multiple transformations in the same directory.
1258
# but for now, we haven't optimized...
1259
return [canonical_relpath(base, p) for p in paths]
1262
def decode_filename(filename):
1263
"""Decode the filename using the filesystem encoding
1265
If it is unicode, it is returned.
1266
Otherwise it is decoded from the the filesystem's encoding. If decoding
1267
fails, a errors.BadFilenameEncoding exception is raised.
1269
if type(filename) is unicode:
1272
return filename.decode(_fs_enc)
1273
except UnicodeDecodeError:
1274
raise errors.BadFilenameEncoding(filename, _fs_enc)
1277
def safe_unicode(unicode_or_utf8_string):
1278
"""Coerce unicode_or_utf8_string into unicode.
1280
If it is unicode, it is returned.
1281
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1282
wrapped in a BzrBadParameterNotUnicode exception.
1284
if isinstance(unicode_or_utf8_string, unicode):
1285
return unicode_or_utf8_string
1287
return unicode_or_utf8_string.decode('utf8')
1288
except UnicodeDecodeError:
1289
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1292
def safe_utf8(unicode_or_utf8_string):
1293
"""Coerce unicode_or_utf8_string to a utf8 string.
1295
If it is a str, it is returned.
1296
If it is Unicode, it is encoded into a utf-8 string.
1298
if isinstance(unicode_or_utf8_string, str):
1299
# TODO: jam 20070209 This is overkill, and probably has an impact on
1300
# performance if we are dealing with lots of apis that want a
1303
# Make sure it is a valid utf-8 string
1304
unicode_or_utf8_string.decode('utf-8')
1305
except UnicodeDecodeError:
1306
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1307
return unicode_or_utf8_string
1308
return unicode_or_utf8_string.encode('utf-8')
1311
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1312
' Revision id generators should be creating utf8'
1316
def safe_revision_id(unicode_or_utf8_string, warn=True):
1317
"""Revision ids should now be utf8, but at one point they were unicode.
1319
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1321
:param warn: Functions that are sanitizing user data can set warn=False
1322
:return: None or a utf8 revision id.
1324
if (unicode_or_utf8_string is None
1325
or unicode_or_utf8_string.__class__ == str):
1326
return unicode_or_utf8_string
1328
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1330
return cache_utf8.encode(unicode_or_utf8_string)
1333
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1334
' generators should be creating utf8 file ids.')
1337
def safe_file_id(unicode_or_utf8_string, warn=True):
1338
"""File ids should now be utf8, but at one point they were unicode.
1340
This is the same as safe_utf8, except it uses the cached encode functions
1341
to save a little bit of performance.
1343
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1345
:param warn: Functions that are sanitizing user data can set warn=False
1346
:return: None or a utf8 file id.
1348
if (unicode_or_utf8_string is None
1349
or unicode_or_utf8_string.__class__ == str):
1350
return unicode_or_utf8_string
1352
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1354
return cache_utf8.encode(unicode_or_utf8_string)
1357
_platform_normalizes_filenames = False
1358
if sys.platform == 'darwin':
1359
_platform_normalizes_filenames = True
1362
def normalizes_filenames():
1363
"""Return True if this platform normalizes unicode filenames.
1367
return _platform_normalizes_filenames
1370
def _accessible_normalized_filename(path):
1371
"""Get the unicode normalized path, and if you can access the file.
1373
On platforms where the system normalizes filenames (Mac OSX),
1374
you can access a file by any path which will normalize correctly.
1375
On platforms where the system does not normalize filenames
1376
(everything else), you have to access a file by its exact path.
1378
Internally, bzr only supports NFC normalization, since that is
1379
the standard for XML documents.
1381
So return the normalized path, and a flag indicating if the file
1382
can be accessed by that path.
1385
return unicodedata.normalize('NFC', unicode(path)), True
1388
def _inaccessible_normalized_filename(path):
1389
__doc__ = _accessible_normalized_filename.__doc__
1391
normalized = unicodedata.normalize('NFC', unicode(path))
1392
return normalized, normalized == path
1395
if _platform_normalizes_filenames:
1396
normalized_filename = _accessible_normalized_filename
1398
normalized_filename = _inaccessible_normalized_filename
1401
def set_signal_handler(signum, handler, restart_syscall=True):
1402
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1403
on platforms that support that.
1405
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1406
automatically restart (by calling `signal.siginterrupt(signum,
1407
False)`). May be ignored if the feature is not available on this
1408
platform or Python version.
1412
siginterrupt = signal.siginterrupt
1414
# This python implementation doesn't provide signal support, hence no
1417
except AttributeError:
1418
# siginterrupt doesn't exist on this platform, or for this version
1420
siginterrupt = lambda signum, flag: None
1422
def sig_handler(*args):
1423
# Python resets the siginterrupt flag when a signal is
1424
# received. <http://bugs.python.org/issue8354>
1425
# As a workaround for some cases, set it back the way we want it.
1426
siginterrupt(signum, False)
1427
# Now run the handler function passed to set_signal_handler.
1430
sig_handler = handler
1431
old_handler = signal.signal(signum, sig_handler)
1433
siginterrupt(signum, False)
1437
default_terminal_width = 80
1438
"""The default terminal width for ttys.
1440
This is defined so that higher levels can share a common fallback value when
1441
terminal_width() returns None.
1444
# Keep some state so that terminal_width can detect if _terminal_size has
1445
# returned a different size since the process started. See docstring and
1446
# comments of terminal_width for details.
1447
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1448
_terminal_size_state = 'no_data'
1449
_first_terminal_size = None
1451
def terminal_width():
1452
"""Return terminal width.
1454
None is returned if the width can't established precisely.
1457
- if BZR_COLUMNS is set, returns its value
1458
- if there is no controlling terminal, returns None
1459
- query the OS, if the queried size has changed since the last query,
1461
- if COLUMNS is set, returns its value,
1462
- if the OS has a value (even though it's never changed), return its value.
1464
From there, we need to query the OS to get the size of the controlling
1467
On Unices we query the OS by:
1468
- get termios.TIOCGWINSZ
1469
- if an error occurs or a negative value is obtained, returns None
1471
On Windows we query the OS by:
1472
- win32utils.get_console_size() decides,
1473
- returns None on error (provided default value)
1475
# Note to implementors: if changing the rules for determining the width,
1476
# make sure you've considered the behaviour in these cases:
1477
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1478
# - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1480
# - (add more interesting cases here, if you find any)
1481
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1482
# but we don't want to register a signal handler because it is impossible
1483
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1484
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1485
# time so we can notice if the reported size has changed, which should have
1488
# If BZR_COLUMNS is set, take it, user is always right
1489
# Except if they specified 0 in which case, impose no limit here
1491
width = int(os.environ['BZR_COLUMNS'])
1492
except (KeyError, ValueError):
1494
if width is not None:
1500
isatty = getattr(sys.stdout, 'isatty', None)
1501
if isatty is None or not isatty():
1502
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1506
width, height = os_size = _terminal_size(None, None)
1507
global _first_terminal_size, _terminal_size_state
1508
if _terminal_size_state == 'no_data':
1509
_first_terminal_size = os_size
1510
_terminal_size_state = 'unchanged'
1511
elif (_terminal_size_state == 'unchanged' and
1512
_first_terminal_size != os_size):
1513
_terminal_size_state = 'changed'
1515
# If the OS claims to know how wide the terminal is, and this value has
1516
# ever changed, use that.
1517
if _terminal_size_state == 'changed':
1518
if width is not None and width > 0:
1521
# If COLUMNS is set, use it.
1523
return int(os.environ['COLUMNS'])
1524
except (KeyError, ValueError):
1527
# Finally, use an unchanged size from the OS, if we have one.
1528
if _terminal_size_state == 'unchanged':
1529
if width is not None and width > 0:
1532
# The width could not be determined.
1536
def _win32_terminal_size(width, height):
1537
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1538
return width, height
1541
def _ioctl_terminal_size(width, height):
1543
import struct, fcntl, termios
1544
s = struct.pack('HHHH', 0, 0, 0, 0)
1545
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1546
height, width = struct.unpack('HHHH', x)[0:2]
1547
except (IOError, AttributeError):
1549
return width, height
1551
_terminal_size = None
1552
"""Returns the terminal size as (width, height).
1554
:param width: Default value for width.
1555
:param height: Default value for height.
1557
This is defined specifically for each OS and query the size of the controlling
1558
terminal. If any error occurs, the provided default values should be returned.
1560
if sys.platform == 'win32':
1561
_terminal_size = _win32_terminal_size
1563
_terminal_size = _ioctl_terminal_size
1566
def supports_executable():
1567
return sys.platform != "win32"
1570
def supports_posix_readonly():
1571
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1573
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1574
directory controls creation/deletion, etc.
1576
And under win32, readonly means that the directory itself cannot be
1577
deleted. The contents of a readonly directory can be changed, unlike POSIX
1578
where files in readonly directories cannot be added, deleted or renamed.
1580
return sys.platform != "win32"
1583
def set_or_unset_env(env_variable, value):
1584
"""Modify the environment, setting or removing the env_variable.
1586
:param env_variable: The environment variable in question
1587
:param value: The value to set the environment to. If None, then
1588
the variable will be removed.
1589
:return: The original value of the environment variable.
1591
orig_val = os.environ.get(env_variable)
1593
if orig_val is not None:
1594
del os.environ[env_variable]
1596
if isinstance(value, unicode):
1597
value = value.encode(get_user_encoding())
1598
os.environ[env_variable] = value
1602
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1605
def check_legal_path(path):
1606
"""Check whether the supplied path is legal.
1607
This is only required on Windows, so we don't test on other platforms
1610
if sys.platform != "win32":
1612
if _validWin32PathRE.match(path) is None:
1613
raise errors.IllegalPath(path)
1616
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1618
def _is_error_enotdir(e):
1619
"""Check if this exception represents ENOTDIR.
1621
Unfortunately, python is very inconsistent about the exception
1622
here. The cases are:
1623
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1624
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1625
which is the windows error code.
1626
3) Windows, Python2.5 uses errno == EINVAL and
1627
winerror == ERROR_DIRECTORY
1629
:param e: An Exception object (expected to be OSError with an errno
1630
attribute, but we should be able to cope with anything)
1631
:return: True if this represents an ENOTDIR error. False otherwise.
1633
en = getattr(e, 'errno', None)
1634
if (en == errno.ENOTDIR
1635
or (sys.platform == 'win32'
1636
and (en == _WIN32_ERROR_DIRECTORY
1637
or (en == errno.EINVAL
1638
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1644
def walkdirs(top, prefix=""):
1645
"""Yield data about all the directories in a tree.
1647
This yields all the data about the contents of a directory at a time.
1648
After each directory has been yielded, if the caller has mutated the list
1649
to exclude some directories, they are then not descended into.
1651
The data yielded is of the form:
1652
((directory-relpath, directory-path-from-top),
1653
[(relpath, basename, kind, lstat, path-from-top), ...]),
1654
- directory-relpath is the relative path of the directory being returned
1655
with respect to top. prefix is prepended to this.
1656
- directory-path-from-root is the path including top for this directory.
1657
It is suitable for use with os functions.
1658
- relpath is the relative path within the subtree being walked.
1659
- basename is the basename of the path
1660
- kind is the kind of the file now. If unknown then the file is not
1661
present within the tree - but it may be recorded as versioned. See
1663
- lstat is the stat data *if* the file was statted.
1664
- planned, not implemented:
1665
path_from_tree_root is the path from the root of the tree.
1667
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1668
allows one to walk a subtree but get paths that are relative to a tree
1670
:return: an iterator over the dirs.
1672
#TODO there is a bit of a smell where the results of the directory-
1673
# summary in this, and the path from the root, may not agree
1674
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1675
# potentially confusing output. We should make this more robust - but
1676
# not at a speed cost. RBC 20060731
1678
_directory = _directory_kind
1679
_listdir = os.listdir
1680
_kind_from_mode = file_kind_from_stat_mode
1681
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1683
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1684
relroot, _, _, _, top = pending.pop()
1686
relprefix = relroot + u'/'
1689
top_slash = top + u'/'
1692
append = dirblock.append
1694
names = sorted(map(decode_filename, _listdir(top)))
1696
if not _is_error_enotdir(e):
1700
abspath = top_slash + name
1701
statvalue = _lstat(abspath)
1702
kind = _kind_from_mode(statvalue.st_mode)
1703
append((relprefix + name, name, kind, statvalue, abspath))
1704
yield (relroot, top), dirblock
1706
# push the user specified dirs from dirblock
1707
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1710
class DirReader(object):
1711
"""An interface for reading directories."""
1713
def top_prefix_to_starting_dir(self, top, prefix=""):
1714
"""Converts top and prefix to a starting dir entry
1716
:param top: A utf8 path
1717
:param prefix: An optional utf8 path to prefix output relative paths
1719
:return: A tuple starting with prefix, and ending with the native
1722
raise NotImplementedError(self.top_prefix_to_starting_dir)
1724
def read_dir(self, prefix, top):
1725
"""Read a specific dir.
1727
:param prefix: A utf8 prefix to be preprended to the path basenames.
1728
:param top: A natively encoded path to read.
1729
:return: A list of the directories contents. Each item contains:
1730
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1732
raise NotImplementedError(self.read_dir)
1735
_selected_dir_reader = None
1738
def _walkdirs_utf8(top, prefix=""):
1739
"""Yield data about all the directories in a tree.
1741
This yields the same information as walkdirs() only each entry is yielded
1742
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1743
are returned as exact byte-strings.
1745
:return: yields a tuple of (dir_info, [file_info])
1746
dir_info is (utf8_relpath, path-from-top)
1747
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1748
if top is an absolute path, path-from-top is also an absolute path.
1749
path-from-top might be unicode or utf8, but it is the correct path to
1750
pass to os functions to affect the file in question. (such as os.lstat)
1752
global _selected_dir_reader
1753
if _selected_dir_reader is None:
1754
fs_encoding = _fs_enc.upper()
1755
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1756
# Win98 doesn't have unicode apis like FindFirstFileW
1757
# TODO: We possibly could support Win98 by falling back to the
1758
# original FindFirstFile, and using TCHAR instead of WCHAR,
1759
# but that gets a bit tricky, and requires custom compiling
1762
from bzrlib._walkdirs_win32 import Win32ReadDir
1763
_selected_dir_reader = Win32ReadDir()
1766
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1767
# ANSI_X3.4-1968 is a form of ASCII
1769
from bzrlib._readdir_pyx import UTF8DirReader
1770
_selected_dir_reader = UTF8DirReader()
1771
except ImportError, e:
1772
failed_to_load_extension(e)
1775
if _selected_dir_reader is None:
1776
# Fallback to the python version
1777
_selected_dir_reader = UnicodeDirReader()
1779
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1780
# But we don't actually uses 1-3 in pending, so set them to None
1781
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1782
read_dir = _selected_dir_reader.read_dir
1783
_directory = _directory_kind
1785
relroot, _, _, _, top = pending[-1].pop()
1788
dirblock = sorted(read_dir(relroot, top))
1789
yield (relroot, top), dirblock
1790
# push the user specified dirs from dirblock
1791
next = [d for d in reversed(dirblock) if d[2] == _directory]
1793
pending.append(next)
1796
class UnicodeDirReader(DirReader):
1797
"""A dir reader for non-utf8 file systems, which transcodes."""
1799
__slots__ = ['_utf8_encode']
1802
self._utf8_encode = codecs.getencoder('utf8')
1804
def top_prefix_to_starting_dir(self, top, prefix=""):
1805
"""See DirReader.top_prefix_to_starting_dir."""
1806
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1808
def read_dir(self, prefix, top):
1809
"""Read a single directory from a non-utf8 file system.
1811
top, and the abspath element in the output are unicode, all other paths
1812
are utf8. Local disk IO is done via unicode calls to listdir etc.
1814
This is currently the fallback code path when the filesystem encoding is
1815
not UTF-8. It may be better to implement an alternative so that we can
1816
safely handle paths that are not properly decodable in the current
1819
See DirReader.read_dir for details.
1821
_utf8_encode = self._utf8_encode
1823
_listdir = os.listdir
1824
_kind_from_mode = file_kind_from_stat_mode
1827
relprefix = prefix + '/'
1830
top_slash = top + u'/'
1833
append = dirblock.append
1834
for name in sorted(_listdir(top)):
1836
name_utf8 = _utf8_encode(name)[0]
1837
except UnicodeDecodeError:
1838
raise errors.BadFilenameEncoding(
1839
_utf8_encode(relprefix)[0] + name, _fs_enc)
1840
abspath = top_slash + name
1841
statvalue = _lstat(abspath)
1842
kind = _kind_from_mode(statvalue.st_mode)
1843
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1847
def copy_tree(from_path, to_path, handlers={}):
1848
"""Copy all of the entries in from_path into to_path.
1850
:param from_path: The base directory to copy.
1851
:param to_path: The target directory. If it does not exist, it will
1853
:param handlers: A dictionary of functions, which takes a source and
1854
destinations for files, directories, etc.
1855
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1856
'file', 'directory', and 'symlink' should always exist.
1857
If they are missing, they will be replaced with 'os.mkdir()',
1858
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1860
# Now, just copy the existing cached tree to the new location
1861
# We use a cheap trick here.
1862
# Absolute paths are prefixed with the first parameter
1863
# relative paths are prefixed with the second.
1864
# So we can get both the source and target returned
1865
# without any extra work.
1867
def copy_dir(source, dest):
1870
def copy_link(source, dest):
1871
"""Copy the contents of a symlink"""
1872
link_to = os.readlink(source)
1873
os.symlink(link_to, dest)
1875
real_handlers = {'file':shutil.copy2,
1876
'symlink':copy_link,
1877
'directory':copy_dir,
1879
real_handlers.update(handlers)
1881
if not os.path.exists(to_path):
1882
real_handlers['directory'](from_path, to_path)
1884
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1885
for relpath, name, kind, st, abspath in entries:
1886
real_handlers[kind](abspath, relpath)
1889
def copy_ownership_from_path(dst, src=None):
1890
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1892
If src is None, the containing directory is used as source. If chown
1893
fails, the error is ignored and a warning is printed.
1895
chown = getattr(os, 'chown', None)
1900
src = os.path.dirname(dst)
1906
chown(dst, s.st_uid, s.st_gid)
1909
'Unable to copy ownership from "%s" to "%s". '
1910
'You may want to set it manually.', src, dst)
1911
trace.log_exception_quietly()
1914
def path_prefix_key(path):
1915
"""Generate a prefix-order path key for path.
1917
This can be used to sort paths in the same way that walkdirs does.
1919
return (dirname(path) , path)
1922
def compare_paths_prefix_order(path_a, path_b):
1923
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1924
key_a = path_prefix_key(path_a)
1925
key_b = path_prefix_key(path_b)
1926
return cmp(key_a, key_b)
1929
_cached_user_encoding = None
1932
def get_user_encoding(use_cache=True):
1933
"""Find out what the preferred user encoding is.
1935
This is generally the encoding that is used for command line parameters
1936
and file contents. This may be different from the terminal encoding
1937
or the filesystem encoding.
1939
:param use_cache: Enable cache for detected encoding.
1940
(This parameter is turned on by default,
1941
and required only for selftesting)
1943
:return: A string defining the preferred user encoding
1945
global _cached_user_encoding
1946
if _cached_user_encoding is not None and use_cache:
1947
return _cached_user_encoding
1949
if sys.platform == 'darwin':
1950
# python locale.getpreferredencoding() always return
1951
# 'mac-roman' on darwin. That's a lie.
1952
sys.platform = 'posix'
1954
if os.environ.get('LANG', None) is None:
1955
# If LANG is not set, we end up with 'ascii', which is bad
1956
# ('mac-roman' is more than ascii), so we set a default which
1957
# will give us UTF-8 (which appears to work in all cases on
1958
# OSX). Users are still free to override LANG of course, as
1959
# long as it give us something meaningful. This work-around
1960
# *may* not be needed with python 3k and/or OSX 10.5, but will
1961
# work with them too -- vila 20080908
1962
os.environ['LANG'] = 'en_US.UTF-8'
1965
sys.platform = 'darwin'
1970
user_encoding = locale.getpreferredencoding()
1971
except locale.Error, e:
1972
sys.stderr.write('bzr: warning: %s\n'
1973
' Could not determine what text encoding to use.\n'
1974
' This error usually means your Python interpreter\n'
1975
' doesn\'t support the locale set by $LANG (%s)\n'
1976
" Continuing with ascii encoding.\n"
1977
% (e, os.environ.get('LANG')))
1978
user_encoding = 'ascii'
1980
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1981
# treat that as ASCII, and not support printing unicode characters to the
1984
# For python scripts run under vim, we get '', so also treat that as ASCII
1985
if user_encoding in (None, 'cp0', ''):
1986
user_encoding = 'ascii'
1990
codecs.lookup(user_encoding)
1992
sys.stderr.write('bzr: warning:'
1993
' unknown encoding %s.'
1994
' Continuing with ascii encoding.\n'
1997
user_encoding = 'ascii'
2000
_cached_user_encoding = user_encoding
2002
return user_encoding
2005
def get_diff_header_encoding():
2006
return get_terminal_encoding()
2009
def get_host_name():
2010
"""Return the current unicode host name.
2012
This is meant to be used in place of socket.gethostname() because that
2013
behaves inconsistently on different platforms.
2015
if sys.platform == "win32":
2017
return win32utils.get_host_name()
2020
return socket.gethostname().decode(get_user_encoding())
2023
# We must not read/write any more than 64k at a time from/to a socket so we
2024
# don't risk "no buffer space available" errors on some platforms. Windows in
2025
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2027
MAX_SOCKET_CHUNK = 64 * 1024
2029
_end_of_stream_errors = [errno.ECONNRESET]
2030
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2031
_eno = getattr(errno, _eno, None)
2032
if _eno is not None:
2033
_end_of_stream_errors.append(_eno)
2037
def read_bytes_from_socket(sock, report_activity=None,
2038
max_read_size=MAX_SOCKET_CHUNK):
2039
"""Read up to max_read_size of bytes from sock and notify of progress.
2041
Translates "Connection reset by peer" into file-like EOF (return an
2042
empty string rather than raise an error), and repeats the recv if
2043
interrupted by a signal.
2047
bytes = sock.recv(max_read_size)
2048
except socket.error, e:
2050
if eno in _end_of_stream_errors:
2051
# The connection was closed by the other side. Callers expect
2052
# an empty string to signal end-of-stream.
2054
elif eno == errno.EINTR:
2055
# Retry the interrupted recv.
2059
if report_activity is not None:
2060
report_activity(len(bytes), 'read')
2064
def recv_all(socket, count):
2065
"""Receive an exact number of bytes.
2067
Regular Socket.recv() may return less than the requested number of bytes,
2068
depending on what's in the OS buffer. MSG_WAITALL is not available
2069
on all platforms, but this should work everywhere. This will return
2070
less than the requested amount if the remote end closes.
2072
This isn't optimized and is intended mostly for use in testing.
2075
while len(b) < count:
2076
new = read_bytes_from_socket(socket, None, count - len(b))
2083
def send_all(sock, bytes, report_activity=None):
2084
"""Send all bytes on a socket.
2086
Breaks large blocks in smaller chunks to avoid buffering limitations on
2087
some platforms, and catches EINTR which may be thrown if the send is
2088
interrupted by a signal.
2090
This is preferred to socket.sendall(), because it avoids portability bugs
2091
and provides activity reporting.
2093
:param report_activity: Call this as bytes are read, see
2094
Transport._report_activity
2097
byte_count = len(bytes)
2098
while sent_total < byte_count:
2100
sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
2101
except socket.error, e:
2102
if e.args[0] != errno.EINTR:
2106
report_activity(sent, 'write')
2109
def connect_socket(address):
2110
# Slight variation of the socket.create_connection() function (provided by
2111
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2112
# provide it for previous python versions. Also, we don't use the timeout
2113
# parameter (provided by the python implementation) so we don't implement
2115
err = socket.error('getaddrinfo returns an empty list')
2116
host, port = address
2117
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2118
af, socktype, proto, canonname, sa = res
2121
sock = socket.socket(af, socktype, proto)
2125
except socket.error, err:
2126
# 'err' is now the most recent error
2127
if sock is not None:
2132
def dereference_path(path):
2133
"""Determine the real path to a file.
2135
All parent elements are dereferenced. But the file itself is not
2137
:param path: The original path. May be absolute or relative.
2138
:return: the real path *to* the file
2140
parent, base = os.path.split(path)
2141
# The pathjoin for '.' is a workaround for Python bug #1213894.
2142
# (initial path components aren't dereferenced)
2143
return pathjoin(realpath(pathjoin('.', parent)), base)
2146
def supports_mapi():
2147
"""Return True if we can use MAPI to launch a mail client."""
2148
return sys.platform == "win32"
2151
def resource_string(package, resource_name):
2152
"""Load a resource from a package and return it as a string.
2154
Note: Only packages that start with bzrlib are currently supported.
2156
This is designed to be a lightweight implementation of resource
2157
loading in a way which is API compatible with the same API from
2159
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
2160
If and when pkg_resources becomes a standard library, this routine
2163
# Check package name is within bzrlib
2164
if package == "bzrlib":
2165
resource_relpath = resource_name
2166
elif package.startswith("bzrlib."):
2167
package = package[len("bzrlib."):].replace('.', os.sep)
2168
resource_relpath = pathjoin(package, resource_name)
2170
raise errors.BzrError('resource package %s not in bzrlib' % package)
2172
# Map the resource to a file and read its contents
2173
base = dirname(bzrlib.__file__)
2174
if getattr(sys, 'frozen', None): # bzr.exe
2175
base = abspath(pathjoin(base, '..', '..'))
2176
f = file(pathjoin(base, resource_relpath), "rU")
2182
def file_kind_from_stat_mode_thunk(mode):
2183
global file_kind_from_stat_mode
2184
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2186
from bzrlib._readdir_pyx import UTF8DirReader
2187
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2188
except ImportError, e:
2189
# This is one time where we won't warn that an extension failed to
2190
# load. The extension is never available on Windows anyway.
2191
from bzrlib._readdir_py import (
2192
_kind_from_mode as file_kind_from_stat_mode
2194
return file_kind_from_stat_mode(mode)
2195
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2197
def file_stat(f, _lstat=os.lstat):
2202
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2203
raise errors.NoSuchFile(f)
2206
def file_kind(f, _lstat=os.lstat):
2207
stat_value = file_stat(f, _lstat)
2208
return file_kind_from_stat_mode(stat_value.st_mode)
2210
def until_no_eintr(f, *a, **kw):
2211
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2213
WARNING: you must be certain that it is safe to retry the call repeatedly
2214
if EINTR does occur. This is typically only true for low-level operations
2215
like os.read. If in any doubt, don't use this.
2217
Keep in mind that this is not a complete solution to EINTR. There is
2218
probably code in the Python standard library and other dependencies that
2219
may encounter EINTR if a signal arrives (and there is signal handler for
2220
that signal). So this function can reduce the impact for IO that bzrlib
2221
directly controls, but it is not a complete solution.
2223
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2227
except (IOError, OSError), e:
2228
if e.errno == errno.EINTR:
2233
@deprecated_function(deprecated_in((2, 2, 0)))
2234
def re_compile_checked(re_string, flags=0, where=""):
2235
"""Return a compiled re, or raise a sensible error.
2237
This should only be used when compiling user-supplied REs.
2239
:param re_string: Text form of regular expression.
2240
:param flags: eg re.IGNORECASE
2241
:param where: Message explaining to the user the context where
2242
it occurred, eg 'log search filter'.
2244
# from https://bugs.launchpad.net/bzr/+bug/251352
2246
re_obj = re.compile(re_string, flags)
2249
except errors.InvalidPattern, e:
2251
where = ' in ' + where
2252
# despite the name 'error' is a type
2253
raise errors.BzrCommandError('Invalid regular expression%s: %s'
2257
if sys.platform == "win32":
2260
return msvcrt.getch()
2265
fd = sys.stdin.fileno()
2266
settings = termios.tcgetattr(fd)
2269
ch = sys.stdin.read(1)
2271
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2274
if sys.platform.startswith('linux'):
2275
def _local_concurrency():
2277
return os.sysconf('SC_NPROCESSORS_ONLN')
2278
except (ValueError, OSError, AttributeError):
2280
elif sys.platform == 'darwin':
2281
def _local_concurrency():
2282
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2283
stdout=subprocess.PIPE).communicate()[0]
2284
elif "bsd" in sys.platform:
2285
def _local_concurrency():
2286
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2287
stdout=subprocess.PIPE).communicate()[0]
2288
elif sys.platform == 'sunos5':
2289
def _local_concurrency():
2290
return subprocess.Popen(['psrinfo', '-p',],
2291
stdout=subprocess.PIPE).communicate()[0]
2292
elif sys.platform == "win32":
2293
def _local_concurrency():
2294
# This appears to return the number of cores.
2295
return os.environ.get('NUMBER_OF_PROCESSORS')
2297
def _local_concurrency():
2302
_cached_local_concurrency = None
2304
def local_concurrency(use_cache=True):
2305
"""Return how many processes can be run concurrently.
2307
Rely on platform specific implementations and default to 1 (one) if
2308
anything goes wrong.
2310
global _cached_local_concurrency
2312
if _cached_local_concurrency is not None and use_cache:
2313
return _cached_local_concurrency
2315
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2316
if concurrency is None:
2318
import multiprocessing
2320
# multiprocessing is only available on Python >= 2.6
2322
concurrency = _local_concurrency()
2323
except (OSError, IOError):
2326
concurrency = multiprocessing.cpu_count()
2328
concurrency = int(concurrency)
2329
except (TypeError, ValueError):
2332
_cached_concurrency = concurrency
2336
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2337
"""A stream writer that doesn't decode str arguments."""
2339
def __init__(self, encode, stream, errors='strict'):
2340
codecs.StreamWriter.__init__(self, stream, errors)
2341
self.encode = encode
2343
def write(self, object):
2344
if type(object) is str:
2345
self.stream.write(object)
2347
data, _ = self.encode(object, self.errors)
2348
self.stream.write(data)
2350
if sys.platform == 'win32':
2351
def open_file(filename, mode='r', bufsize=-1):
2352
"""This function is used to override the ``open`` builtin.
2354
But it uses O_NOINHERIT flag so the file handle is not inherited by
2355
child processes. Deleting or renaming a closed file opened with this
2356
function is not blocking child processes.
2358
writing = 'w' in mode
2359
appending = 'a' in mode
2360
updating = '+' in mode
2361
binary = 'b' in mode
2364
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2365
# for flags for each modes.
2375
flags |= os.O_WRONLY
2376
flags |= os.O_CREAT | os.O_TRUNC
2381
flags |= os.O_WRONLY
2382
flags |= os.O_CREAT | os.O_APPEND
2387
flags |= os.O_RDONLY
2389
return os.fdopen(os.open(filename, flags), mode, bufsize)
2394
def getuser_unicode():
2395
"""Return the username as unicode.
2398
user_encoding = get_user_encoding()
2399
username = getpass.getuser().decode(user_encoding)
2400
except UnicodeDecodeError:
2401
raise errors.BzrError("Can't decode username as %s." % \
2403
except ImportError, e:
2404
if sys.platform != 'win32':
2406
if str(e) != 'No module named pwd':
2408
# https://bugs.launchpad.net/bzr/+bug/660174
2409
# getpass.getuser() is unable to return username on Windows
2410
# if there is no USERNAME environment variable set.
2411
# That could be true if bzr is running as a service,
2412
# e.g. running `bzr serve` as a service on Windows.
2413
# We should not fail with traceback in this case.
2414
username = u'UNKNOWN'
2418
def available_backup_name(base, exists):
2419
"""Find a non-existing backup file name.
2421
This will *not* create anything, this only return a 'free' entry. This
2422
should be used for checking names in a directory below a locked
2423
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2424
Leap) and generally discouraged.
2426
:param base: The base name.
2428
:param exists: A callable returning True if the path parameter exists.
2431
name = "%s.~%d~" % (base, counter)
2434
name = "%s.~%d~" % (base, counter)
2438
def set_fd_cloexec(fd):
2439
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2440
support for this is not available.
2444
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2445
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2446
except (ImportError, AttributeError):
2447
# Either the fcntl module or specific constants are not present
2451
def find_executable_on_path(name):
2452
"""Finds an executable on the PATH.
2454
On Windows, this will try to append each extension in the PATHEXT
2455
environment variable to the name, if it cannot be found with the name
2458
:param name: The base name of the executable.
2459
:return: The path to the executable found or None.
2461
path = os.environ.get('PATH')
2464
path = path.split(os.pathsep)
2465
if sys.platform == 'win32':
2466
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2467
exts = [ext.lower() for ext in exts]
2468
base, ext = os.path.splitext(name)
2470
if ext.lower() not in exts:
2478
f = os.path.join(d, name) + ext
2479
if os.access(f, os.X_OK):
2484
def _posix_is_local_pid_dead(pid):
2485
"""True if pid doesn't correspond to live process on this machine"""
2487
# Special meaning of unix kill: just check if it's there.
2490
if e.errno == errno.ESRCH:
2491
# On this machine, and really not found: as sure as we can be
2494
elif e.errno == errno.EPERM:
2495
# exists, though not ours
2498
mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2499
# Don't really know.
2502
# Exists and our process: not dead.
2505
if sys.platform == "win32":
2506
is_local_pid_dead = win32utils.is_local_pid_dead
2508
is_local_pid_dead = _posix_is_local_pid_dead
2511
def fdatasync(fileno):
2512
"""Flush file contents to disk if possible.
2514
:param fileno: Integer OS file handle.
2515
:raises TransportNotPossible: If flushing to disk is not possible.
2517
fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))