260
252
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
263
def _win98_abspath(path):
264
"""Return the absolute version of a path.
265
Windows 98 safe implementation (python reimplementation
266
of Win32 API function GetFullPathNameW)
271
# \\HOST\path => //HOST/path
272
# //HOST/path => //HOST/path
273
# path => C:/cwd/path
276
# check for absolute path
277
drive = _nt_splitdrive(path)[0]
278
if drive == '' and path[:2] not in('//','\\\\'):
280
# we cannot simply os.path.join cwd and path
281
# because os.path.join('C:','/path') produce '/path'
282
# and this is incorrect
283
if path[:1] in ('/','\\'):
284
cwd = _nt_splitdrive(cwd)[0]
286
path = cwd + '\\' + path
287
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
289
if win32utils.winver == 'Windows 98':
290
_win32_abspath = _win98_abspath
293
255
def _win32_realpath(path):
294
256
# Real _nt_realpath doesn't have a problem with a unicode cwd
295
257
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
636
596
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
639
def format_delta(delta):
640
"""Get a nice looking string for a time delta.
642
:param delta: The time difference in seconds, can be positive or negative.
643
positive indicates time in the past, negative indicates time in the
644
future. (usually time.time() - stored_time)
645
:return: String formatted to show approximate resolution
651
direction = 'in the future'
655
if seconds < 90: # print seconds up to 90 seconds
657
return '%d second %s' % (seconds, direction,)
659
return '%d seconds %s' % (seconds, direction)
661
minutes = int(seconds / 60)
662
seconds -= 60 * minutes
667
if minutes < 90: # print minutes, seconds up to 90 minutes
669
return '%d minute, %d second%s %s' % (
670
minutes, seconds, plural_seconds, direction)
672
return '%d minutes, %d second%s %s' % (
673
minutes, seconds, plural_seconds, direction)
675
hours = int(minutes / 60)
676
minutes -= 60 * hours
683
return '%d hour, %d minute%s %s' % (hours, minutes,
684
plural_minutes, direction)
685
return '%d hours, %d minute%s %s' % (hours, minutes,
686
plural_minutes, direction)
689
601
"""Return size of given open file."""
883
798
return unicode_or_utf8_string.decode('utf8')
884
799
except UnicodeDecodeError:
885
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
888
def safe_utf8(unicode_or_utf8_string):
889
"""Coerce unicode_or_utf8_string to a utf8 string.
891
If it is a str, it is returned.
892
If it is Unicode, it is encoded into a utf-8 string.
894
if isinstance(unicode_or_utf8_string, str):
895
# TODO: jam 20070209 This is overkill, and probably has an impact on
896
# performance if we are dealing with lots of apis that want a
899
# Make sure it is a valid utf-8 string
900
unicode_or_utf8_string.decode('utf-8')
901
except UnicodeDecodeError:
902
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
903
return unicode_or_utf8_string
904
return unicode_or_utf8_string.encode('utf-8')
907
def safe_revision_id(unicode_or_utf8_string):
908
"""Revision ids should now be utf8, but at one point they were unicode.
910
This is the same as safe_utf8, except it uses the cached encode functions
911
to save a little bit of performance.
913
if unicode_or_utf8_string is None:
915
if isinstance(unicode_or_utf8_string, str):
916
# TODO: jam 20070209 Eventually just remove this check.
918
utf8_str = cache_utf8.get_cached_utf8(unicode_or_utf8_string)
919
except UnicodeDecodeError:
920
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
922
return cache_utf8.encode(unicode_or_utf8_string)
925
# TODO: jam 20070217 We start by just re-using safe_revision_id, but ultimately
926
# we want to use a different dictionary cache, because trapping file ids
927
# and revision ids in the same dict seemed to have a noticable effect on
929
safe_file_id = safe_revision_id
800
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
932
803
_platform_normalizes_filenames = False
1079
938
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1080
939
# potentially confusing output. We should make this more robust - but
1081
940
# not at a speed cost. RBC 20060731
1083
943
_directory = _directory_kind
1084
_listdir = os.listdir
1085
_kind_from_mode = _formats.get
1086
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
945
pending = [(prefix, "", _directory, None, top)]
948
currentdir = pending.pop()
1088
949
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1089
relroot, _, _, _, top = pending.pop()
1091
relprefix = relroot + u'/'
1094
top_slash = top + u'/'
1097
append = dirblock.append
1098
for name in sorted(_listdir(top)):
1099
abspath = top_slash + name
1100
statvalue = _lstat(abspath)
1101
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1102
append((relprefix + name, name, kind, statvalue, abspath))
1103
yield (relroot, top), dirblock
1105
# push the user specified dirs from dirblock
1106
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1109
def _walkdirs_utf8(top, prefix=""):
1110
"""Yield data about all the directories in a tree.
1112
This yields the same information as walkdirs() only each entry is yielded
1113
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1114
are returned as exact byte-strings.
1116
:return: yields a tuple of (dir_info, [file_info])
1117
dir_info is (utf8_relpath, path-from-top)
1118
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1119
if top is an absolute path, path-from-top is also an absolute path.
1120
path-from-top might be unicode or utf8, but it is the correct path to
1121
pass to os functions to affect the file in question. (such as os.lstat)
1123
fs_encoding = sys.getfilesystemencoding()
1124
if (sys.platform == 'win32' or
1125
fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1126
return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1128
return _walkdirs_fs_utf8(top, prefix=prefix)
1131
def _walkdirs_fs_utf8(top, prefix=""):
1132
"""See _walkdirs_utf8.
1134
This sub-function is called when we know the filesystem is already in utf8
1135
encoding. So we don't need to transcode filenames.
1138
_directory = _directory_kind
1139
_listdir = os.listdir
1140
_kind_from_mode = _formats.get
1142
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1143
# But we don't actually uses 1-3 in pending, so set them to None
1144
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1146
relroot, _, _, _, top = pending.pop()
1148
relprefix = relroot + '/'
1151
top_slash = top + '/'
1154
append = dirblock.append
1155
for name in sorted(_listdir(top)):
1156
abspath = top_slash + name
1157
statvalue = _lstat(abspath)
1158
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1159
append((relprefix + name, name, kind, statvalue, abspath))
1160
yield (relroot, top), dirblock
1162
# push the user specified dirs from dirblock
1163
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1166
def _walkdirs_unicode_to_utf8(top, prefix=""):
1167
"""See _walkdirs_utf8
1169
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1171
This is currently the fallback code path when the filesystem encoding is
1172
not UTF-8. It may be better to implement an alternative so that we can
1173
safely handle paths that are not properly decodable in the current
1176
_utf8_encode = codecs.getencoder('utf8')
1178
_directory = _directory_kind
1179
_listdir = os.listdir
1180
_kind_from_mode = _formats.get
1182
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1184
relroot, _, _, _, top = pending.pop()
1186
relprefix = relroot + '/'
1189
top_slash = top + u'/'
1192
append = dirblock.append
1193
for name in sorted(_listdir(top)):
1194
name_utf8 = _utf8_encode(name)[0]
1195
abspath = top_slash + name
1196
statvalue = _lstat(abspath)
1197
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1198
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1199
yield (relroot, top), dirblock
1201
# push the user specified dirs from dirblock
1202
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
952
relroot = currentdir[0] + '/'
955
for name in sorted(_listdir(top)):
956
abspath = top + '/' + name
957
statvalue = lstat(abspath)
958
dirblock.append((relroot + name, name,
959
file_kind_from_stat_mode(statvalue.st_mode),
961
yield (currentdir[0], top), dirblock
962
# push the user specified dirs from dirblock
963
for dir in reversed(dirblock):
964
if dir[2] == _directory:
1205
968
def copy_tree(from_path, to_path, handlers={}):
1298
1057
' doesn\'t support the locale set by $LANG (%s)\n'
1299
1058
" Continuing with ascii encoding.\n"
1300
1059
% (e, os.environ.get('LANG')))
1301
user_encoding = 'ascii'
1303
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1304
# treat that as ASCII, and not support printing unicode characters to the
1306
if user_encoding in (None, 'cp0'):
1307
user_encoding = 'ascii'
1311
codecs.lookup(user_encoding)
1313
sys.stderr.write('bzr: warning:'
1314
' unknown encoding %s.'
1315
' Continuing with ascii encoding.\n'
1318
user_encoding = 'ascii'
1321
_cached_user_encoding = user_encoding
1323
return user_encoding
1326
def recv_all(socket, bytes):
1327
"""Receive an exact number of bytes.
1329
Regular Socket.recv() may return less than the requested number of bytes,
1330
dependning on what's in the OS buffer. MSG_WAITALL is not available
1331
on all platforms, but this should work everywhere. This will return
1332
less than the requested amount if the remote end closes.
1334
This isn't optimized and is intended mostly for use in testing.
1337
while len(b) < bytes:
1338
new = socket.recv(bytes - len(b))
1344
def dereference_path(path):
1345
"""Determine the real path to a file.
1347
All parent elements are dereferenced. But the file itself is not
1349
:param path: The original path. May be absolute or relative.
1350
:return: the real path *to* the file
1352
parent, base = os.path.split(path)
1353
# The pathjoin for '.' is a workaround for Python bug #1213894.
1354
# (initial path components aren't dereferenced)
1355
return pathjoin(realpath(pathjoin('.', parent)), base)
1061
if _cached_user_encoding is None:
1062
_cached_user_encoding = 'ascii'
1063
return _cached_user_encoding