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)
21
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
26
26
from bzrlib.lazy_import import lazy_import
27
27
lazy_import(globals(), """
29
28
from datetime import datetime
31
30
from ntpath import (abspath as _nt_abspath,
33
32
normpath as _nt_normpath,
85
90
# be opened in binary mode, rather than text mode.
86
91
# On other platforms, O_BINARY doesn't exist, because
87
92
# they always open in binary mode, so it is okay to
88
# OR with 0 on those platforms
93
# OR with 0 on those platforms.
94
# O_NOINHERIT and O_TEXT exists only on win32 too.
89
95
O_BINARY = getattr(os, 'O_BINARY', 0)
96
O_TEXT = getattr(os, 'O_TEXT', 0)
97
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
92
100
def get_unicode_argv():
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.
1319
1348
On platforms where the system normalizes filenames (Mac OSX),
1320
1349
you can access a file by any path which will normalize correctly.
1321
1350
On platforms where the system does not normalize filenames
1322
(Windows, Linux), you have to access a file by its exact path.
1351
(everything else), you have to access a file by its exact path.
1324
1353
Internally, bzr only supports NFC normalization, since that is
1325
1354
the standard for XML documents.
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)
1877
trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
1772
1880
def path_prefix_key(path):
1773
1881
"""Generate a prefix-order path key for path.
1874
1986
return socket.gethostname().decode(get_user_encoding())
1877
def recv_all(socket, bytes):
1989
# We must not read/write any more than 64k at a time from/to a socket so we
1990
# don't risk "no buffer space available" errors on some platforms. Windows in
1991
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
1993
MAX_SOCKET_CHUNK = 64 * 1024
1995
def read_bytes_from_socket(sock, report_activity=None,
1996
max_read_size=MAX_SOCKET_CHUNK):
1997
"""Read up to max_read_size of bytes from sock and notify of progress.
1999
Translates "Connection reset by peer" into file-like EOF (return an
2000
empty string rather than raise an error), and repeats the recv if
2001
interrupted by a signal.
2005
bytes = sock.recv(max_read_size)
2006
except socket.error, e:
2008
if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2009
# The connection was closed by the other side. Callers expect
2010
# an empty string to signal end-of-stream.
2012
elif eno == errno.EINTR:
2013
# Retry the interrupted recv.
2017
if report_activity is not None:
2018
report_activity(len(bytes), 'read')
2022
def recv_all(socket, count):
1878
2023
"""Receive an exact number of bytes.
1880
2025
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
2026
depending on what's in the OS buffer. MSG_WAITALL is not available
1882
2027
on all platforms, but this should work everywhere. This will return
1883
2028
less than the requested amount if the remote end closes.
1885
2030
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))
2033
while len(b) < count:
2034
new = read_bytes_from_socket(socket, None, count - len(b))
1896
def send_all(socket, bytes, report_activity=None):
2041
def send_all(sock, bytes, report_activity=None):
1897
2042
"""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.
2044
Breaks large blocks in smaller chunks to avoid buffering limitations on
2045
some platforms, and catches EINTR which may be thrown if the send is
2046
interrupted by a signal.
2048
This is preferred to socket.sendall(), because it avoids portability bugs
2049
and provides activity reporting.
1902
2051
:param report_activity: Call this as bytes are read, see
1903
2052
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)
2055
byte_count = len(bytes)
2056
while sent_total < byte_count:
2058
sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
2059
except socket.error, e:
2060
if e.args[0] != errno.EINTR:
2064
report_activity(sent, 'write')
1913
2067
def dereference_path(path):
1954
2108
base = dirname(bzrlib.__file__)
1955
2109
if getattr(sys, 'frozen', None): # bzr.exe
1956
2110
base = abspath(pathjoin(base, '..', '..'))
1957
filename = pathjoin(base, resource_relpath)
1958
return open(filename, 'rU').read()
2111
f = file(pathjoin(base, resource_relpath), "rU")
1961
2117
def file_kind_from_stat_mode_thunk(mode):
1962
2118
global file_kind_from_stat_mode
1986
2142
def until_no_eintr(f, *a, **kw):
1987
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2143
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2145
WARNING: you must be certain that it is safe to retry the call repeatedly
2146
if EINTR does occur. This is typically only true for low-level operations
2147
like os.read. If in any doubt, don't use this.
2149
Keep in mind that this is not a complete solution to EINTR. There is
2150
probably code in the Python standard library and other dependencies that
2151
may encounter EINTR if a signal arrives (and there is signal handler for
2152
that signal). So this function can reduce the impact for IO that bzrlib
2153
directly controls, but it is not a complete solution.
1988
2155
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2107
2275
data, _ = self.encode(object, self.errors)
2108
2276
self.stream.write(data)
2278
if sys.platform == 'win32':
2279
def open_file(filename, mode='r', bufsize=-1):
2280
"""This function is used to override the ``open`` builtin.
2282
But it uses O_NOINHERIT flag so the file handle is not inherited by
2283
child processes. Deleting or renaming a closed file opened with this
2284
function is not blocking child processes.
2286
writing = 'w' in mode
2287
appending = 'a' in mode
2288
updating = '+' in mode
2289
binary = 'b' in mode
2292
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2293
# for flags for each modes.
2303
flags |= os.O_WRONLY
2304
flags |= os.O_CREAT | os.O_TRUNC
2309
flags |= os.O_WRONLY
2310
flags |= os.O_CREAT | os.O_APPEND
2315
flags |= os.O_RDONLY
2317
return os.fdopen(os.open(filename, flags), mode, bufsize)
2322
def getuser_unicode():
2323
"""Return the username as unicode.
2326
user_encoding = get_user_encoding()
2327
username = getpass.getuser().decode(user_encoding)
2328
except UnicodeDecodeError:
2329
raise errors.BzrError("Can't decode username as %s." % \