26
27
lazy_import(globals(), """
27
28
from datetime import datetime
30
from ntpath import (abspath as _nt_abspath,
32
normpath as _nt_normpath,
33
realpath as _nt_realpath,
34
splitdrive as _nt_splitdrive,
31
# We need to import both shutil and rmtree as we export the later on posix
32
# and need the former on windows
34
from shutil import rmtree
37
# We need to import both tempfile and mkdtemp as we export the later on posix
38
# and need the former on windows
40
from tempfile import mkdtemp
44
from tempfile import (
43
49
from bzrlib import (
293
304
running python.exe under cmd.exe return capital C:\\
294
305
running win32 python inside a cygwin shell returns lowercase c:\\
296
drive, path = ntpath.splitdrive(path)
307
drive, path = _nt_splitdrive(path)
297
308
return drive.upper() + path
300
311
def _win32_abspath(path):
301
# Real ntpath.abspath doesn't have a problem with a unicode cwd
302
return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
312
# Real _nt_abspath doesn't have a problem with a unicode cwd
313
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
305
316
def _win98_abspath(path):
316
327
# /path => C:/path
317
328
path = unicode(path)
318
329
# check for absolute path
319
drive = ntpath.splitdrive(path)[0]
330
drive = _nt_splitdrive(path)[0]
320
331
if drive == '' and path[:2] not in('//','\\\\'):
321
332
cwd = os.getcwdu()
322
333
# we cannot simply os.path.join cwd and path
323
334
# because os.path.join('C:','/path') produce '/path'
324
335
# and this is incorrect
325
336
if path[:1] in ('/','\\'):
326
cwd = ntpath.splitdrive(cwd)[0]
337
cwd = _nt_splitdrive(cwd)[0]
328
339
path = cwd + '\\' + path
329
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
340
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
332
343
def _win32_realpath(path):
333
# Real ntpath.realpath doesn't have a problem with a unicode cwd
334
return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
344
# Real _nt_realpath doesn't have a problem with a unicode cwd
345
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
337
348
def _win32_pathjoin(*args):
338
return ntpath.join(*args).replace('\\', '/')
349
return _nt_join(*args).replace('\\', '/')
341
352
def _win32_normpath(path):
342
return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
353
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
345
356
def _win32_getcwd():
1470
1468
# a similar effect.
1472
1470
# If BZR_COLUMNS is set, take it, user is always right
1473
# Except if they specified 0 in which case, impose no limit here
1475
width = int(os.environ['BZR_COLUMNS'])
1472
return int(os.environ['BZR_COLUMNS'])
1476
1473
except (KeyError, ValueError):
1478
if width is not None:
1484
1476
isatty = getattr(sys.stdout, 'isatty', None)
1485
1477
if isatty is None or not isatty():
2010
1999
# data at once.
2011
2000
MAX_SOCKET_CHUNK = 64 * 1024
2013
_end_of_stream_errors = [errno.ECONNRESET]
2014
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2015
_eno = getattr(errno, _eno, None)
2016
if _eno is not None:
2017
_end_of_stream_errors.append(_eno)
2021
2002
def read_bytes_from_socket(sock, report_activity=None,
2022
2003
max_read_size=MAX_SOCKET_CHUNK):
2023
2004
"""Read up to max_read_size of bytes from sock and notify of progress.
2090
2071
report_activity(sent, 'write')
2093
def connect_socket(address):
2094
# Slight variation of the socket.create_connection() function (provided by
2095
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2096
# provide it for previous python versions. Also, we don't use the timeout
2097
# parameter (provided by the python implementation) so we don't implement
2099
err = socket.error('getaddrinfo returns an empty list')
2100
host, port = address
2101
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2102
af, socktype, proto, canonname, sa = res
2105
sock = socket.socket(af, socktype, proto)
2109
except socket.error, err:
2110
# 'err' is now the most recent error
2111
if sock is not None:
2116
2074
def dereference_path(path):
2117
2075
"""Determine the real path to a file.
2252
2209
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2255
2213
if sys.platform == 'linux2':
2256
2214
def _local_concurrency():
2258
return os.sysconf('SC_NPROCESSORS_ONLN')
2259
except (ValueError, OSError, AttributeError):
2216
prefix = 'processor'
2217
for line in file('/proc/cpuinfo', 'rb'):
2218
if line.startswith(prefix):
2219
concurrency = int(line[line.find(':')+1:]) + 1
2261
2221
elif sys.platform == 'darwin':
2262
2222
def _local_concurrency():
2263
2223
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2264
2224
stdout=subprocess.PIPE).communicate()[0]
2265
elif "bsd" in sys.platform:
2225
elif sys.platform[0:7] == 'freebsd':
2266
2226
def _local_concurrency():
2267
2227
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2268
2228
stdout=subprocess.PIPE).communicate()[0]
2296
2256
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2297
2257
if concurrency is None:
2299
import multiprocessing
2301
# multiprocessing is only available on Python >= 2.6
2303
concurrency = _local_concurrency()
2304
except (OSError, IOError):
2307
concurrency = multiprocessing.cpu_count()
2259
concurrency = _local_concurrency()
2260
except (OSError, IOError):
2309
2263
concurrency = int(concurrency)
2310
2264
except (TypeError, ValueError):
2381
2335
except UnicodeDecodeError:
2382
2336
raise errors.BzrError("Can't decode username as %s." % \
2384
except ImportError, e:
2385
if sys.platform != 'win32':
2387
if str(e) != 'No module named pwd':
2389
# https://bugs.launchpad.net/bzr/+bug/660174
2390
# getpass.getuser() is unable to return username on Windows
2391
# if there is no USERNAME environment variable set.
2392
# That could be true if bzr is running as a service,
2393
# e.g. running `bzr serve` as a service on Windows.
2394
# We should not fail with traceback in this case.
2395
username = u'UNKNOWN'
2396
2338
return username
2399
def available_backup_name(base, exists):
2400
"""Find a non-existing backup file name.
2402
This will *not* create anything, this only return a 'free' entry. This
2403
should be used for checking names in a directory below a locked
2404
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2405
Leap) and generally discouraged.
2407
:param base: The base name.
2409
:param exists: A callable returning True if the path parameter exists.
2412
name = "%s.~%d~" % (base, counter)
2415
name = "%s.~%d~" % (base, counter)
2419
def set_fd_cloexec(fd):
2420
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2421
support for this is not available.
2425
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2426
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2427
except (ImportError, AttributeError):
2428
# Either the fcntl module or specific constants are not present
2432
def find_executable_on_path(name):
2433
"""Finds an executable on the PATH.
2435
On Windows, this will try to append each extension in the PATHEXT
2436
environment variable to the name, if it cannot be found with the name
2439
:param name: The base name of the executable.
2440
:return: The path to the executable found or None.
2442
path = os.environ.get('PATH')
2445
path = path.split(os.pathsep)
2446
if sys.platform == 'win32':
2447
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2448
exts = [ext.lower() for ext in exts]
2449
base, ext = os.path.splitext(name)
2451
if ext.lower() not in exts:
2459
f = os.path.join(d, name) + ext
2460
if os.access(f, os.X_OK):
2465
def _posix_is_local_pid_dead(pid):
2466
"""True if pid doesn't correspond to live process on this machine"""
2468
# Special meaning of unix kill: just check if it's there.
2471
if e.errno == errno.ESRCH:
2472
# On this machine, and really not found: as sure as we can be
2475
elif e.errno == errno.EPERM:
2476
# exists, though not ours
2479
mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2480
# Don't really know.
2483
# Exists and our process: not dead.
2486
if sys.platform == "win32":
2487
is_local_pid_dead = win32utils.is_local_pid_dead
2489
is_local_pid_dead = _posix_is_local_pid_dead