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):
297
298
running python.exe under cmd.exe return capital C:\\
298
299
running win32 python inside a cygwin shell returns lowercase c:\\
300
drive, path = _nt_splitdrive(path)
301
drive, path = ntpath.splitdrive(path)
301
302
return drive.upper() + path
304
305
def _win32_abspath(path):
305
# Real _nt_abspath doesn't have a problem with a unicode cwd
306
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('\\', '/'))
309
310
def _win98_abspath(path):
320
321
# /path => C:/path
321
322
path = unicode(path)
322
323
# check for absolute path
323
drive = _nt_splitdrive(path)[0]
324
drive = ntpath.splitdrive(path)[0]
324
325
if drive == '' and path[:2] not in('//','\\\\'):
325
326
cwd = os.getcwdu()
326
327
# we cannot simply os.path.join cwd and path
327
328
# because os.path.join('C:','/path') produce '/path'
328
329
# and this is incorrect
329
330
if path[:1] in ('/','\\'):
330
cwd = _nt_splitdrive(cwd)[0]
331
cwd = ntpath.splitdrive(cwd)[0]
332
333
path = cwd + '\\' + path
333
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
334
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
336
337
def _win32_realpath(path):
337
# Real _nt_realpath doesn't have a problem with a unicode cwd
338
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('\\', '/'))
341
342
def _win32_pathjoin(*args):
342
return _nt_join(*args).replace('\\', '/')
343
return ntpath.join(*args).replace('\\', '/')
345
346
def _win32_normpath(path):
346
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
347
return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
349
350
def _win32_getcwd():
453
456
input_encoding = getattr(sys.stdin, 'encoding', None)
454
457
if not input_encoding:
455
458
output_encoding = get_user_encoding()
456
mutter('encoding stdout as osutils.get_user_encoding() %r',
460
mutter('encoding stdout as osutils.get_user_encoding() %r',
459
463
output_encoding = input_encoding
460
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
465
mutter('encoding stdout as sys.stdin encoding %r',
462
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
469
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
463
470
if output_encoding == 'cp0':
464
471
# invalid encoding (cp0 means 'no codepage' on Windows)
465
472
output_encoding = get_user_encoding()
466
mutter('cp0 is invalid encoding.'
474
mutter('cp0 is invalid encoding.'
467
475
' encoding stdout as osutils.get_user_encoding() %r',
1223
1234
# but for now, we haven't optimized...
1224
1235
return [canonical_relpath(base, p) for p in paths]
1238
def decode_filename(filename):
1239
"""Decode the filename using the filesystem encoding
1241
If it is unicode, it is returned.
1242
Otherwise it is decoded from the the filesystem's encoding. If decoding
1243
fails, a errors.BadFilenameEncoding exception is raised.
1245
if type(filename) is unicode:
1248
return filename.decode(_fs_enc)
1249
except UnicodeDecodeError:
1250
raise errors.BadFilenameEncoding(filename, _fs_enc)
1226
1253
def safe_unicode(unicode_or_utf8_string):
1227
1254
"""Coerce unicode_or_utf8_string into unicode.
1322
1349
On platforms where the system normalizes filenames (Mac OSX),
1323
1350
you can access a file by any path which will normalize correctly.
1324
1351
On platforms where the system does not normalize filenames
1325
(Windows, Linux), you have to access a file by its exact path.
1352
(everything else), you have to access a file by its exact path.
1327
1354
Internally, bzr only supports NFC normalization, since that is
1328
1355
the standard for XML documents.
1824
1856
real_handlers[kind](abspath, relpath)
1859
def copy_ownership_from_path(dst, src=None):
1860
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1862
If src is None, the containing directory is used as source. If chown
1863
fails, the error is ignored and a warning is printed.
1865
chown = getattr(os, 'chown', None)
1870
src = os.path.dirname(dst)
1876
chown(dst, s.st_uid, s.st_gid)
1878
trace.warning("Unable to copy ownership from '%s' to '%s': IOError: %s." % (src, dst, e))
1827
1881
def path_prefix_key(path):
1828
1882
"""Generate a prefix-order path key for path.
1929
1987
return socket.gethostname().decode(get_user_encoding())
1932
def recv_all(socket, bytes):
1990
# We must not read/write any more than 64k at a time from/to a socket so we
1991
# don't risk "no buffer space available" errors on some platforms. Windows in
1992
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
1994
MAX_SOCKET_CHUNK = 64 * 1024
1996
def read_bytes_from_socket(sock, report_activity=None,
1997
max_read_size=MAX_SOCKET_CHUNK):
1998
"""Read up to max_read_size of bytes from sock and notify of progress.
2000
Translates "Connection reset by peer" into file-like EOF (return an
2001
empty string rather than raise an error), and repeats the recv if
2002
interrupted by a signal.
2006
bytes = sock.recv(max_read_size)
2007
except socket.error, e:
2009
if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
2010
# The connection was closed by the other side. Callers expect
2011
# an empty string to signal end-of-stream.
2013
elif eno == errno.EINTR:
2014
# Retry the interrupted recv.
2018
if report_activity is not None:
2019
report_activity(len(bytes), 'read')
2023
def recv_all(socket, count):
1933
2024
"""Receive an exact number of bytes.
1935
2026
Regular Socket.recv() may return less than the requested number of bytes,
1936
dependning on what's in the OS buffer. MSG_WAITALL is not available
2027
depending on what's in the OS buffer. MSG_WAITALL is not available
1937
2028
on all platforms, but this should work everywhere. This will return
1938
2029
less than the requested amount if the remote end closes.
1940
2031
This isn't optimized and is intended mostly for use in testing.
1943
while len(b) < bytes:
1944
new = until_no_eintr(socket.recv, bytes - len(b))
2034
while len(b) < count:
2035
new = read_bytes_from_socket(socket, None, count - len(b))
1951
def send_all(socket, bytes, report_activity=None):
2042
def send_all(sock, bytes, report_activity=None):
1952
2043
"""Send all bytes on a socket.
1954
Regular socket.sendall() can give socket error 10053 on Windows. This
1955
implementation sends no more than 64k at a time, which avoids this problem.
2045
Breaks large blocks in smaller chunks to avoid buffering limitations on
2046
some platforms, and catches EINTR which may be thrown if the send is
2047
interrupted by a signal.
2049
This is preferred to socket.sendall(), because it avoids portability bugs
2050
and provides activity reporting.
1957
2052
:param report_activity: Call this as bytes are read, see
1958
2053
Transport._report_activity
1961
for pos in xrange(0, len(bytes), chunk_size):
1962
block = bytes[pos:pos+chunk_size]
1963
if report_activity is not None:
1964
report_activity(len(block), 'write')
1965
until_no_eintr(socket.sendall, block)
2056
byte_count = len(bytes)
2057
while sent_total < byte_count:
2059
sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
2060
except socket.error, e:
2061
if e.args[0] != errno.EINTR:
2065
report_activity(sent, 'write')
1968
2068
def dereference_path(path):
2009
2109
base = dirname(bzrlib.__file__)
2010
2110
if getattr(sys, 'frozen', None): # bzr.exe
2011
2111
base = abspath(pathjoin(base, '..', '..'))
2012
filename = pathjoin(base, resource_relpath)
2013
return open(filename, 'rU').read()
2112
f = file(pathjoin(base, resource_relpath), "rU")
2016
2118
def file_kind_from_stat_mode_thunk(mode):
2017
2119
global file_kind_from_stat_mode
2041
2143
def until_no_eintr(f, *a, **kw):
2042
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2144
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2146
WARNING: you must be certain that it is safe to retry the call repeatedly
2147
if EINTR does occur. This is typically only true for low-level operations
2148
like os.read. If in any doubt, don't use this.
2150
Keep in mind that this is not a complete solution to EINTR. There is
2151
probably code in the Python standard library and other dependencies that
2152
may encounter EINTR if a signal arrives (and there is signal handler for
2153
that signal). So this function can reduce the impact for IO that bzrlib
2154
directly controls, but it is not a complete solution.
2043
2156
# Borrowed from Twisted's twisted.python.util.untilConcludes function.