14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
26
25
from bzrlib.lazy_import import lazy_import
27
26
lazy_import(globals(), """
29
27
from datetime import datetime
31
from ntpath import (abspath as _nt_abspath,
33
normpath as _nt_normpath,
34
realpath as _nt_realpath,
35
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
45
from tempfile import (
40
from tempfile import mkdtemp
50
43
from bzrlib import (
51
from bzrlib.symbol_versioning import (
57
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
59
58
if sys.version_info < (2, 5):
85
84
# be opened in binary mode, rather than text mode.
86
85
# On other platforms, O_BINARY doesn't exist, because
87
86
# they always open in binary mode, so it is okay to
88
# OR with 0 on those platforms
87
# OR with 0 on those platforms.
88
# O_NOINHERIT and O_TEXT exists only on win32 too.
89
89
O_BINARY = getattr(os, 'O_BINARY', 0)
90
O_TEXT = getattr(os, 'O_TEXT', 0)
91
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
92
94
def get_unicode_argv():
294
298
running python.exe under cmd.exe return capital C:\\
295
299
running win32 python inside a cygwin shell returns lowercase c:\\
297
drive, path = _nt_splitdrive(path)
301
drive, path = ntpath.splitdrive(path)
298
302
return drive.upper() + path
301
305
def _win32_abspath(path):
302
# Real _nt_abspath doesn't have a problem with a unicode cwd
303
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
306
# Real ntpath.abspath doesn't have a problem with a unicode cwd
307
return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
306
310
def _win98_abspath(path):
317
321
# /path => C:/path
318
322
path = unicode(path)
319
323
# check for absolute path
320
drive = _nt_splitdrive(path)[0]
324
drive = ntpath.splitdrive(path)[0]
321
325
if drive == '' and path[:2] not in('//','\\\\'):
322
326
cwd = os.getcwdu()
323
327
# we cannot simply os.path.join cwd and path
324
328
# because os.path.join('C:','/path') produce '/path'
325
329
# and this is incorrect
326
330
if path[:1] in ('/','\\'):
327
cwd = _nt_splitdrive(cwd)[0]
331
cwd = ntpath.splitdrive(cwd)[0]
329
333
path = cwd + '\\' + path
330
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
334
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
333
337
def _win32_realpath(path):
334
# Real _nt_realpath doesn't have a problem with a unicode cwd
335
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
338
# Real ntpath.realpath doesn't have a problem with a unicode cwd
339
return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
338
342
def _win32_pathjoin(*args):
339
return _nt_join(*args).replace('\\', '/')
343
return ntpath.join(*args).replace('\\', '/')
342
346
def _win32_normpath(path):
343
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
347
return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
346
350
def _win32_getcwd():
450
456
input_encoding = getattr(sys.stdin, 'encoding', None)
451
457
if not input_encoding:
452
458
output_encoding = get_user_encoding()
453
mutter('encoding stdout as osutils.get_user_encoding() %r',
460
mutter('encoding stdout as osutils.get_user_encoding() %r',
456
463
output_encoding = input_encoding
457
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
465
mutter('encoding stdout as sys.stdin encoding %r',
459
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
469
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
460
470
if output_encoding == 'cp0':
461
471
# invalid encoding (cp0 means 'no codepage' on Windows)
462
472
output_encoding = get_user_encoding()
463
mutter('cp0 is invalid encoding.'
474
mutter('cp0 is invalid encoding.'
464
475
' encoding stdout as osutils.get_user_encoding() %r',
1220
1233
# but for now, we haven't optimized...
1221
1234
return [canonical_relpath(base, p) for p in paths]
1237
def decode_filename(filename):
1238
"""Decode the filename using the filesystem encoding
1240
If it is unicode, it is returned.
1241
Otherwise it is decoded from the the filesystem's encoding. If decoding
1242
fails, a errors.BadFilenameEncoding exception is raised.
1244
if type(filename) is unicode:
1247
return filename.decode(_fs_enc)
1248
except UnicodeDecodeError:
1249
raise errors.BadFilenameEncoding(filename, _fs_enc)
1223
1252
def safe_unicode(unicode_or_utf8_string):
1224
1253
"""Coerce unicode_or_utf8_string into unicode.
1344
1373
normalized_filename = _inaccessible_normalized_filename
1376
def set_signal_handler(signum, handler, restart_syscall=True):
1377
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1378
on platforms that support that.
1380
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1381
automatically restart (by calling `signal.siginterrupt(signum,
1382
False)`). May be ignored if the feature is not available on this
1383
platform or Python version.
1387
siginterrupt = signal.siginterrupt
1389
# This python implementation doesn't provide signal support, hence no
1392
except AttributeError:
1393
# siginterrupt doesn't exist on this platform, or for this version
1395
siginterrupt = lambda signum, flag: None
1397
def sig_handler(*args):
1398
# Python resets the siginterrupt flag when a signal is
1399
# received. <http://bugs.python.org/issue8354>
1400
# As a workaround for some cases, set it back the way we want it.
1401
siginterrupt(signum, False)
1402
# Now run the handler function passed to set_signal_handler.
1405
sig_handler = handler
1406
old_handler = signal.signal(signum, sig_handler)
1408
siginterrupt(signum, False)
1347
1412
default_terminal_width = 80
1348
1413
"""The default terminal width for ttys.
1361
1432
- if BZR_COLUMNS is set, returns its value
1362
1433
- if there is no controlling terminal, returns None
1434
- query the OS, if the queried size has changed since the last query,
1363
1436
- if COLUMNS is set, returns its value,
1437
- if the OS has a value (even though it's never changed), return its value.
1365
1439
From there, we need to query the OS to get the size of the controlling
1442
On Unices we query the OS by:
1369
1443
- get termios.TIOCGWINSZ
1370
1444
- if an error occurs or a negative value is obtained, returns None
1446
On Windows we query the OS by:
1374
1447
- win32utils.get_console_size() decides,
1375
1448
- returns None on error (provided default value)
1450
# Note to implementors: if changing the rules for determining the width,
1451
# make sure you've considered the behaviour in these cases:
1452
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1453
# - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1455
# - (add more interesting cases here, if you find any)
1456
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1457
# but we don't want to register a signal handler because it is impossible
1458
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1459
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1460
# time so we can notice if the reported size has changed, which should have
1378
1463
# If BZR_COLUMNS is set, take it, user is always right
1384
1469
isatty = getattr(sys.stdout, 'isatty', None)
1385
if isatty is None or not isatty():
1470
if isatty is None or not isatty():
1386
1471
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1389
# If COLUMNS is set, take it, the terminal knows better (even inside a
1390
# given terminal, the application can decide to set COLUMNS to a lower
1391
# value (splitted screen) or a bigger value (scroll bars))
1475
width, height = os_size = _terminal_size(None, None)
1476
global _first_terminal_size, _terminal_size_state
1477
if _terminal_size_state == 'no_data':
1478
_first_terminal_size = os_size
1479
_terminal_size_state = 'unchanged'
1480
elif (_terminal_size_state == 'unchanged' and
1481
_first_terminal_size != os_size):
1482
_terminal_size_state = 'changed'
1484
# If the OS claims to know how wide the terminal is, and this value has
1485
# ever changed, use that.
1486
if _terminal_size_state == 'changed':
1487
if width is not None and width > 0:
1490
# If COLUMNS is set, use it.
1393
1492
return int(os.environ['COLUMNS'])
1394
1493
except (KeyError, ValueError):
1397
width, height = _terminal_size(None, None)
1399
# Consider invalid values as meaning no width
1496
# Finally, use an unchanged size from the OS, if we have one.
1497
if _terminal_size_state == 'unchanged':
1498
if width is not None and width > 0:
1501
# The width could not be determined.
1405
1505
def _win32_terminal_size(width, height):
1432
1532
_terminal_size = _ioctl_terminal_size
1435
def _terminal_size_changed(signum, frame):
1436
"""Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1437
width, height = _terminal_size(None, None)
1438
if width is not None:
1439
os.environ['COLUMNS'] = str(width)
1441
if sys.platform == 'win32':
1442
# Martin (gz) mentioned WINDOW_BUFFER_SIZE_RECORD from ReadConsoleInput but
1443
# I've no idea how to plug that in the current design -- vila 20091216
1446
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1449
1535
def supports_executable():
1450
1536
return sys.platform != "win32"
1769
1855
real_handlers[kind](abspath, relpath)
1858
def copy_ownership_from_path(dst, src=None):
1859
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1861
If src is None, the containing directory is used as source. If chown
1862
fails, the error is ignored and a warning is printed.
1864
chown = getattr(os, 'chown', None)
1869
src = os.path.dirname(dst)
1875
chown(dst, s.st_uid, s.st_gid)
1878
'Unable to copy ownership from "%s" to "%s". '
1879
'You may want to set it manually.', src, dst)
1880
trace.log_exception_quietly()
1772
1883
def path_prefix_key(path):
1773
1884
"""Generate a prefix-order path key for path.
1874
1989
return socket.gethostname().decode(get_user_encoding())
1877
def recv_all(socket, bytes):
1992
# We must not read/write any more than 64k at a time from/to a socket so we
1993
# don't risk "no buffer space available" errors on some platforms. Windows in
1994
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
1996
MAX_SOCKET_CHUNK = 64 * 1024
1998
def read_bytes_from_socket(sock, report_activity=None,
1999
max_read_size=MAX_SOCKET_CHUNK):
2000
"""Read up to max_read_size of bytes from sock and notify of progress.
2002
Translates "Connection reset by peer" into file-like EOF (return an
2003
empty string rather than raise an error), and repeats the recv if
2004
interrupted by a signal.
2008
bytes = sock.recv(max_read_size)
2009
except socket.error, e:
2011
if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2012
# The connection was closed by the other side. Callers expect
2013
# an empty string to signal end-of-stream.
2015
elif eno == errno.EINTR:
2016
# Retry the interrupted recv.
2020
if report_activity is not None:
2021
report_activity(len(bytes), 'read')
2025
def recv_all(socket, count):
1878
2026
"""Receive an exact number of bytes.
1880
2028
Regular Socket.recv() may return less than the requested number of bytes,
1881
dependning on what's in the OS buffer. MSG_WAITALL is not available
2029
depending on what's in the OS buffer. MSG_WAITALL is not available
1882
2030
on all platforms, but this should work everywhere. This will return
1883
2031
less than the requested amount if the remote end closes.
1885
2033
This isn't optimized and is intended mostly for use in testing.
1888
while len(b) < bytes:
1889
new = until_no_eintr(socket.recv, bytes - len(b))
2036
while len(b) < count:
2037
new = read_bytes_from_socket(socket, None, count - len(b))
1896
def send_all(socket, bytes, report_activity=None):
2044
def send_all(sock, bytes, report_activity=None):
1897
2045
"""Send all bytes on a socket.
1899
Regular socket.sendall() can give socket error 10053 on Windows. This
1900
implementation sends no more than 64k at a time, which avoids this problem.
2047
Breaks large blocks in smaller chunks to avoid buffering limitations on
2048
some platforms, and catches EINTR which may be thrown if the send is
2049
interrupted by a signal.
2051
This is preferred to socket.sendall(), because it avoids portability bugs
2052
and provides activity reporting.
1902
2054
:param report_activity: Call this as bytes are read, see
1903
2055
Transport._report_activity
1906
for pos in xrange(0, len(bytes), chunk_size):
1907
block = bytes[pos:pos+chunk_size]
1908
if report_activity is not None:
1909
report_activity(len(block), 'write')
1910
until_no_eintr(socket.sendall, block)
2058
byte_count = len(bytes)
2059
while sent_total < byte_count:
2061
sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
2062
except socket.error, e:
2063
if e.args[0] != errno.EINTR:
2067
report_activity(sent, 'write')
2070
def connect_socket(address):
2071
# Slight variation of the socket.create_connection() function (provided by
2072
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2073
# provide it for previous python versions. Also, we don't use the timeout
2074
# parameter (provided by the python implementation) so we don't implement
2076
err = socket.error('getaddrinfo returns an empty list')
2077
host, port = address
2078
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2079
af, socktype, proto, canonname, sa = res
2082
sock = socket.socket(af, socktype, proto)
2086
except socket.error, err:
2087
# 'err' is now the most recent error
2088
if sock is not None:
1913
2093
def dereference_path(path):
1986
2168
def until_no_eintr(f, *a, **kw):
1987
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2169
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2171
WARNING: you must be certain that it is safe to retry the call repeatedly
2172
if EINTR does occur. This is typically only true for low-level operations
2173
like os.read. If in any doubt, don't use this.
2175
Keep in mind that this is not a complete solution to EINTR. There is
2176
probably code in the Python standard library and other dependencies that
2177
may encounter EINTR if a signal arrives (and there is signal handler for
2178
that signal). So this function can reduce the impact for IO that bzrlib
2179
directly controls, but it is not a complete solution.
1988
2181
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2107
2302
data, _ = self.encode(object, self.errors)
2108
2303
self.stream.write(data)
2305
if sys.platform == 'win32':
2306
def open_file(filename, mode='r', bufsize=-1):
2307
"""This function is used to override the ``open`` builtin.
2309
But it uses O_NOINHERIT flag so the file handle is not inherited by
2310
child processes. Deleting or renaming a closed file opened with this
2311
function is not blocking child processes.
2313
writing = 'w' in mode
2314
appending = 'a' in mode
2315
updating = '+' in mode
2316
binary = 'b' in mode
2319
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2320
# for flags for each modes.
2330
flags |= os.O_WRONLY
2331
flags |= os.O_CREAT | os.O_TRUNC
2336
flags |= os.O_WRONLY
2337
flags |= os.O_CREAT | os.O_APPEND
2342
flags |= os.O_RDONLY
2344
return os.fdopen(os.open(filename, flags), mode, bufsize)
2349
def getuser_unicode():
2350
"""Return the username as unicode.
2353
user_encoding = get_user_encoding()
2354
username = getpass.getuser().decode(user_encoding)
2355
except UnicodeDecodeError:
2356
raise errors.BzrError("Can't decode username as %s." % \
2361
def available_backup_name(base, exists):
2362
"""Find a non-existing backup file name.
2364
This will *not* create anything, this only return a 'free' entry. This
2365
should be used for checking names in a directory below a locked
2366
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2367
Leap) and generally discouraged.
2369
:param base: The base name.
2371
:param exists: A callable returning True if the path parameter exists.
2374
name = "%s.~%d~" % (base, counter)
2377
name = "%s.~%d~" % (base, counter)