252
264
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
267
def _win98_abspath(path):
268
"""Return the absolute version of a path.
269
Windows 98 safe implementation (python reimplementation
270
of Win32 API function GetFullPathNameW)
275
# \\HOST\path => //HOST/path
276
# //HOST/path => //HOST/path
277
# path => C:/cwd/path
280
# check for absolute path
281
drive = _nt_splitdrive(path)[0]
282
if drive == '' and path[:2] not in('//','\\\\'):
284
# we cannot simply os.path.join cwd and path
285
# because os.path.join('C:','/path') produce '/path'
286
# and this is incorrect
287
if path[:1] in ('/','\\'):
288
cwd = _nt_splitdrive(cwd)[0]
290
path = cwd + '\\' + path
291
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
293
if win32utils.winver == 'Windows 98':
294
_win32_abspath = _win98_abspath
255
297
def _win32_realpath(path):
256
298
# Real _nt_realpath doesn't have a problem with a unicode cwd
257
299
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
555
601
def local_time_offset(t=None):
556
602
"""Return offset of local zone from GMT, either at present or at time t."""
557
# python2.3 localtime() can't take None
561
if time.localtime(t).tm_isdst and time.daylight:
564
return -time.timezone
605
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
606
return offset.days * 86400 + offset.seconds
567
def format_date(t, offset=0, timezone='original', date_fmt=None,
609
def format_date(t, offset=0, timezone='original', date_fmt=None,
568
610
show_offset=True):
569
## TODO: Perhaps a global option to use either universal or local time?
570
## Or perhaps just let people set $TZ?
571
assert isinstance(t, float)
611
"""Return a formatted date string.
613
:param t: Seconds since the epoch.
614
:param offset: Timezone offset in seconds east of utc.
615
:param timezone: How to display the time: 'utc', 'original' for the
616
timezone specified by offset, or 'local' for the process's current
618
:param show_offset: Whether to append the timezone.
619
:param date_fmt: strftime format.
573
621
if timezone == 'utc':
574
622
tt = time.gmtime(t)
596
644
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
647
def format_delta(delta):
648
"""Get a nice looking string for a time delta.
650
:param delta: The time difference in seconds, can be positive or negative.
651
positive indicates time in the past, negative indicates time in the
652
future. (usually time.time() - stored_time)
653
:return: String formatted to show approximate resolution
659
direction = 'in the future'
663
if seconds < 90: # print seconds up to 90 seconds
665
return '%d second %s' % (seconds, direction,)
667
return '%d seconds %s' % (seconds, direction)
669
minutes = int(seconds / 60)
670
seconds -= 60 * minutes
675
if minutes < 90: # print minutes, seconds up to 90 minutes
677
return '%d minute, %d second%s %s' % (
678
minutes, seconds, plural_seconds, direction)
680
return '%d minutes, %d second%s %s' % (
681
minutes, seconds, plural_seconds, direction)
683
hours = int(minutes / 60)
684
minutes -= 60 * hours
691
return '%d hour, %d minute%s %s' % (hours, minutes,
692
plural_minutes, direction)
693
return '%d hours, %d minute%s %s' % (hours, minutes,
694
plural_minutes, direction)
601
697
"""Return size of given open file."""
798
891
return unicode_or_utf8_string.decode('utf8')
799
892
except UnicodeDecodeError:
800
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
893
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
896
def safe_utf8(unicode_or_utf8_string):
897
"""Coerce unicode_or_utf8_string to a utf8 string.
899
If it is a str, it is returned.
900
If it is Unicode, it is encoded into a utf-8 string.
902
if isinstance(unicode_or_utf8_string, str):
903
# TODO: jam 20070209 This is overkill, and probably has an impact on
904
# performance if we are dealing with lots of apis that want a
907
# Make sure it is a valid utf-8 string
908
unicode_or_utf8_string.decode('utf-8')
909
except UnicodeDecodeError:
910
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
911
return unicode_or_utf8_string
912
return unicode_or_utf8_string.encode('utf-8')
915
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
916
' Revision id generators should be creating utf8'
920
def safe_revision_id(unicode_or_utf8_string, warn=True):
921
"""Revision ids should now be utf8, but at one point they were unicode.
923
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
925
:param warn: Functions that are sanitizing user data can set warn=False
926
:return: None or a utf8 revision id.
928
if (unicode_or_utf8_string is None
929
or unicode_or_utf8_string.__class__ == str):
930
return unicode_or_utf8_string
932
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
934
return cache_utf8.encode(unicode_or_utf8_string)
937
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
938
' generators should be creating utf8 file ids.')
941
def safe_file_id(unicode_or_utf8_string, warn=True):
942
"""File ids should now be utf8, but at one point they were unicode.
944
This is the same as safe_utf8, except it uses the cached encode functions
945
to save a little bit of performance.
947
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
949
:param warn: Functions that are sanitizing user data can set warn=False
950
:return: None or a utf8 file id.
952
if (unicode_or_utf8_string is None
953
or unicode_or_utf8_string.__class__ == str):
954
return unicode_or_utf8_string
956
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
958
return cache_utf8.encode(unicode_or_utf8_string)
803
961
_platform_normalizes_filenames = False
938
1108
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
939
1109
# potentially confusing output. We should make this more robust - but
940
1110
# not at a speed cost. RBC 20060731
943
1112
_directory = _directory_kind
945
pending = [(prefix, "", _directory, None, top)]
1113
_listdir = os.listdir
1114
_kind_from_mode = _formats.get
1115
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
948
currentdir = pending.pop()
949
1117
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
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:
1118
relroot, _, _, _, top = pending.pop()
1120
relprefix = relroot + u'/'
1123
top_slash = top + u'/'
1126
append = dirblock.append
1127
for name in sorted(_listdir(top)):
1128
abspath = top_slash + name
1129
statvalue = _lstat(abspath)
1130
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1131
append((relprefix + name, name, kind, statvalue, abspath))
1132
yield (relroot, top), dirblock
1134
# push the user specified dirs from dirblock
1135
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1138
def _walkdirs_utf8(top, prefix=""):
1139
"""Yield data about all the directories in a tree.
1141
This yields the same information as walkdirs() only each entry is yielded
1142
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1143
are returned as exact byte-strings.
1145
:return: yields a tuple of (dir_info, [file_info])
1146
dir_info is (utf8_relpath, path-from-top)
1147
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1148
if top is an absolute path, path-from-top is also an absolute path.
1149
path-from-top might be unicode or utf8, but it is the correct path to
1150
pass to os functions to affect the file in question. (such as os.lstat)
1152
fs_encoding = sys.getfilesystemencoding().upper()
1153
if (sys.platform == 'win32' or
1154
fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1155
return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1157
return _walkdirs_fs_utf8(top, prefix=prefix)
1160
def _walkdirs_fs_utf8(top, prefix=""):
1161
"""See _walkdirs_utf8.
1163
This sub-function is called when we know the filesystem is already in utf8
1164
encoding. So we don't need to transcode filenames.
1167
_directory = _directory_kind
1168
_listdir = os.listdir
1169
_kind_from_mode = _formats.get
1171
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1172
# But we don't actually uses 1-3 in pending, so set them to None
1173
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1175
relroot, _, _, _, top = pending.pop()
1177
relprefix = relroot + '/'
1180
top_slash = top + '/'
1183
append = dirblock.append
1184
for name in sorted(_listdir(top)):
1185
abspath = top_slash + name
1186
statvalue = _lstat(abspath)
1187
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1188
append((relprefix + name, name, kind, statvalue, abspath))
1189
yield (relroot, top), dirblock
1191
# push the user specified dirs from dirblock
1192
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1195
def _walkdirs_unicode_to_utf8(top, prefix=""):
1196
"""See _walkdirs_utf8
1198
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1200
This is currently the fallback code path when the filesystem encoding is
1201
not UTF-8. It may be better to implement an alternative so that we can
1202
safely handle paths that are not properly decodable in the current
1205
_utf8_encode = codecs.getencoder('utf8')
1207
_directory = _directory_kind
1208
_listdir = os.listdir
1209
_kind_from_mode = _formats.get
1211
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1213
relroot, _, _, _, top = pending.pop()
1215
relprefix = relroot + '/'
1218
top_slash = top + u'/'
1221
append = dirblock.append
1222
for name in sorted(_listdir(top)):
1223
name_utf8 = _utf8_encode(name)[0]
1224
abspath = top_slash + name
1225
statvalue = _lstat(abspath)
1226
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1227
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1228
yield (relroot, top), dirblock
1230
# push the user specified dirs from dirblock
1231
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
968
1234
def copy_tree(from_path, to_path, handlers={}):
1052
_cached_user_encoding = locale.getpreferredencoding()
1322
user_encoding = locale.getpreferredencoding()
1053
1323
except locale.Error, e:
1054
1324
sys.stderr.write('bzr: warning: %s\n'
1055
' Could not what text encoding to use.\n'
1325
' Could not determine what text encoding to use.\n'
1056
1326
' This error usually means your Python interpreter\n'
1057
1327
' doesn\'t support the locale set by $LANG (%s)\n'
1058
1328
" Continuing with ascii encoding.\n"
1059
1329
% (e, os.environ.get('LANG')))
1061
if _cached_user_encoding is None:
1062
_cached_user_encoding = 'ascii'
1063
return _cached_user_encoding
1330
user_encoding = 'ascii'
1332
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1333
# treat that as ASCII, and not support printing unicode characters to the
1335
if user_encoding in (None, 'cp0'):
1336
user_encoding = 'ascii'
1340
codecs.lookup(user_encoding)
1342
sys.stderr.write('bzr: warning:'
1343
' unknown encoding %s.'
1344
' Continuing with ascii encoding.\n'
1347
user_encoding = 'ascii'
1350
_cached_user_encoding = user_encoding
1352
return user_encoding
1355
def recv_all(socket, bytes):
1356
"""Receive an exact number of bytes.
1358
Regular Socket.recv() may return less than the requested number of bytes,
1359
dependning on what's in the OS buffer. MSG_WAITALL is not available
1360
on all platforms, but this should work everywhere. This will return
1361
less than the requested amount if the remote end closes.
1363
This isn't optimized and is intended mostly for use in testing.
1366
while len(b) < bytes:
1367
new = socket.recv(bytes - len(b))
1373
def dereference_path(path):
1374
"""Determine the real path to a file.
1376
All parent elements are dereferenced. But the file itself is not
1378
:param path: The original path. May be absolute or relative.
1379
:return: the real path *to* the file
1381
parent, base = os.path.split(path)
1382
# The pathjoin for '.' is a workaround for Python bug #1213894.
1383
# (initial path components aren't dereferenced)
1384
return pathjoin(realpath(pathjoin('.', parent)), base)