269
252
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
272
def _win98_abspath(path):
273
"""Return the absolute version of a path.
274
Windows 98 safe implementation (python reimplementation
275
of Win32 API function GetFullPathNameW)
280
# \\HOST\path => //HOST/path
281
# //HOST/path => //HOST/path
282
# path => C:/cwd/path
285
# check for absolute path
286
drive = _nt_splitdrive(path)[0]
287
if drive == '' and path[:2] not in('//','\\\\'):
289
# we cannot simply os.path.join cwd and path
290
# because os.path.join('C:','/path') produce '/path'
291
# and this is incorrect
292
if path[:1] in ('/','\\'):
293
cwd = _nt_splitdrive(cwd)[0]
295
path = cwd + '\\' + path
296
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
298
if win32utils.winver == 'Windows 98':
299
_win32_abspath = _win98_abspath
302
255
def _win32_realpath(path):
303
256
# Real _nt_realpath doesn't have a problem with a unicode cwd
304
257
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
606
555
def local_time_offset(t=None):
607
556
"""Return offset of local zone from GMT, either at present or at time t."""
557
# python2.3 localtime() can't take None
610
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
611
return offset.days * 86400 + offset.seconds
561
if time.localtime(t).tm_isdst and time.daylight:
564
return -time.timezone
614
def format_date(t, offset=0, timezone='original', date_fmt=None,
567
def format_date(t, offset=0, timezone='original', date_fmt=None,
615
568
show_offset=True):
616
"""Return a formatted date string.
618
:param t: Seconds since the epoch.
619
:param offset: Timezone offset in seconds east of utc.
620
:param timezone: How to display the time: 'utc', 'original' for the
621
timezone specified by offset, or 'local' for the process's current
623
:param show_offset: Whether to append the timezone.
624
:param date_fmt: strftime format.
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)
626
573
if timezone == 'utc':
627
574
tt = time.gmtime(t)
629
576
elif timezone == 'original':
632
579
tt = time.gmtime(t + offset)
633
580
elif timezone == 'local':
634
581
tt = time.localtime(t)
635
582
offset = local_time_offset(t)
637
raise errors.BzrError("unsupported timezone format %r" % timezone,
638
['options are "utc", "original", "local"'])
584
raise BzrError("unsupported timezone format %r" % timezone,
585
['options are "utc", "original", "local"'])
639
586
if date_fmt is None:
640
587
date_fmt = "%a %Y-%m-%d %H:%M:%S"
649
596
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
652
def format_delta(delta):
653
"""Get a nice looking string for a time delta.
655
:param delta: The time difference in seconds, can be positive or negative.
656
positive indicates time in the past, negative indicates time in the
657
future. (usually time.time() - stored_time)
658
:return: String formatted to show approximate resolution
664
direction = 'in the future'
668
if seconds < 90: # print seconds up to 90 seconds
670
return '%d second %s' % (seconds, direction,)
672
return '%d seconds %s' % (seconds, direction)
674
minutes = int(seconds / 60)
675
seconds -= 60 * minutes
680
if minutes < 90: # print minutes, seconds up to 90 minutes
682
return '%d minute, %d second%s %s' % (
683
minutes, seconds, plural_seconds, direction)
685
return '%d minutes, %d second%s %s' % (
686
minutes, seconds, plural_seconds, direction)
688
hours = int(minutes / 60)
689
minutes -= 60 * hours
696
return '%d hour, %d minute%s %s' % (hours, minutes,
697
plural_minutes, direction)
698
return '%d hours, %d minute%s %s' % (hours, minutes,
699
plural_minutes, direction)
702
601
"""Return size of given open file."""
896
798
return unicode_or_utf8_string.decode('utf8')
897
799
except UnicodeDecodeError:
898
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
901
def safe_utf8(unicode_or_utf8_string):
902
"""Coerce unicode_or_utf8_string to a utf8 string.
904
If it is a str, it is returned.
905
If it is Unicode, it is encoded into a utf-8 string.
907
if isinstance(unicode_or_utf8_string, str):
908
# TODO: jam 20070209 This is overkill, and probably has an impact on
909
# performance if we are dealing with lots of apis that want a
912
# Make sure it is a valid utf-8 string
913
unicode_or_utf8_string.decode('utf-8')
914
except UnicodeDecodeError:
915
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
916
return unicode_or_utf8_string
917
return unicode_or_utf8_string.encode('utf-8')
920
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
921
' Revision id generators should be creating utf8'
925
def safe_revision_id(unicode_or_utf8_string, warn=True):
926
"""Revision ids should now be utf8, but at one point they were unicode.
928
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
930
:param warn: Functions that are sanitizing user data can set warn=False
931
:return: None or a utf8 revision id.
933
if (unicode_or_utf8_string is None
934
or unicode_or_utf8_string.__class__ == str):
935
return unicode_or_utf8_string
937
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
939
return cache_utf8.encode(unicode_or_utf8_string)
942
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
943
' generators should be creating utf8 file ids.')
946
def safe_file_id(unicode_or_utf8_string, warn=True):
947
"""File ids should now be utf8, but at one point they were unicode.
949
This is the same as safe_utf8, except it uses the cached encode functions
950
to save a little bit of performance.
952
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
954
:param warn: Functions that are sanitizing user data can set warn=False
955
:return: None or a utf8 file id.
957
if (unicode_or_utf8_string is None
958
or unicode_or_utf8_string.__class__ == str):
959
return unicode_or_utf8_string
961
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
963
return cache_utf8.encode(unicode_or_utf8_string)
800
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
966
803
_platform_normalizes_filenames = False
1033
870
def supports_executable():
1034
871
return sys.platform != "win32"
1037
def supports_posix_readonly():
1038
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1040
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1041
directory controls creation/deletion, etc.
1043
And under win32, readonly means that the directory itself cannot be
1044
deleted. The contents of a readonly directory can be changed, unlike POSIX
1045
where files in readonly directories cannot be added, deleted or renamed.
1047
return sys.platform != "win32"
1050
def set_or_unset_env(env_variable, value):
1051
"""Modify the environment, setting or removing the env_variable.
1053
:param env_variable: The environment variable in question
1054
:param value: The value to set the environment to. If None, then
1055
the variable will be removed.
1056
:return: The original value of the environment variable.
1058
orig_val = os.environ.get(env_variable)
1060
if orig_val is not None:
1061
del os.environ[env_variable]
1063
if isinstance(value, unicode):
1064
value = value.encode(bzrlib.user_encoding)
1065
os.environ[env_variable] = value
1069
874
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1113
918
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1114
919
# potentially confusing output. We should make this more robust - but
1115
920
# not at a speed cost. RBC 20060731
1117
923
_directory = _directory_kind
1118
_listdir = os.listdir
1119
_kind_from_mode = _formats.get
1120
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
925
pending = [(prefix, "", _directory, None, top)]
928
currentdir = pending.pop()
1122
929
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1123
relroot, _, _, _, top = pending.pop()
1125
relprefix = relroot + u'/'
1128
top_slash = top + u'/'
1131
append = dirblock.append
1132
for name in sorted(_listdir(top)):
1133
abspath = top_slash + name
1134
statvalue = _lstat(abspath)
1135
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1136
append((relprefix + name, name, kind, statvalue, abspath))
1137
yield (relroot, top), dirblock
1139
# push the user specified dirs from dirblock
1140
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1143
def _walkdirs_utf8(top, prefix=""):
1144
"""Yield data about all the directories in a tree.
1146
This yields the same information as walkdirs() only each entry is yielded
1147
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1148
are returned as exact byte-strings.
1150
:return: yields a tuple of (dir_info, [file_info])
1151
dir_info is (utf8_relpath, path-from-top)
1152
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1153
if top is an absolute path, path-from-top is also an absolute path.
1154
path-from-top might be unicode or utf8, but it is the correct path to
1155
pass to os functions to affect the file in question. (such as os.lstat)
1157
fs_encoding = _fs_enc.upper()
1158
if (sys.platform == 'win32' or
1159
fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1160
return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1162
return _walkdirs_fs_utf8(top, prefix=prefix)
1165
def _walkdirs_fs_utf8(top, prefix=""):
1166
"""See _walkdirs_utf8.
1168
This sub-function is called when we know the filesystem is already in utf8
1169
encoding. So we don't need to transcode filenames.
1172
_directory = _directory_kind
1173
_listdir = os.listdir
1174
_kind_from_mode = _formats.get
1176
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1177
# But we don't actually uses 1-3 in pending, so set them to None
1178
pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1180
relroot, _, _, _, top = pending.pop()
1182
relprefix = relroot + '/'
1185
top_slash = top + '/'
1188
append = dirblock.append
1189
for name in sorted(_listdir(top)):
1190
abspath = top_slash + name
1191
statvalue = _lstat(abspath)
1192
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1193
append((relprefix + name, name, kind, statvalue, abspath))
1194
yield (relroot, top), dirblock
1196
# push the user specified dirs from dirblock
1197
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1200
def _walkdirs_unicode_to_utf8(top, prefix=""):
1201
"""See _walkdirs_utf8
1203
Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1205
This is currently the fallback code path when the filesystem encoding is
1206
not UTF-8. It may be better to implement an alternative so that we can
1207
safely handle paths that are not properly decodable in the current
1210
_utf8_encode = codecs.getencoder('utf8')
1212
_directory = _directory_kind
1213
_listdir = os.listdir
1214
_kind_from_mode = _formats.get
1216
pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1218
relroot, _, _, _, top = pending.pop()
1220
relprefix = relroot + '/'
1223
top_slash = top + u'/'
1226
append = dirblock.append
1227
for name in sorted(_listdir(top)):
1228
name_utf8 = _utf8_encode(name)[0]
1229
abspath = top_slash + name
1230
statvalue = _lstat(abspath)
1231
kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1232
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1233
yield (relroot, top), dirblock
1235
# push the user specified dirs from dirblock
1236
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
932
relroot = currentdir[0] + '/'
935
for name in sorted(_listdir(top)):
936
abspath = top + '/' + name
937
statvalue = lstat(abspath)
938
dirblock.append((relroot + name, name,
939
file_kind_from_stat_mode(statvalue.st_mode),
941
yield (currentdir[0], top), dirblock
942
# push the user specified dirs from dirblock
943
for dir in reversed(dirblock):
944
if dir[2] == _directory:
1239
948
def copy_tree(from_path, to_path, handlers={}):
1327
user_encoding = locale.getpreferredencoding()
1032
_cached_user_encoding = locale.getpreferredencoding()
1328
1033
except locale.Error, e:
1329
1034
sys.stderr.write('bzr: warning: %s\n'
1330
' Could not determine what text encoding to use.\n'
1035
' Could not what text encoding to use.\n'
1331
1036
' This error usually means your Python interpreter\n'
1332
1037
' doesn\'t support the locale set by $LANG (%s)\n'
1333
1038
" Continuing with ascii encoding.\n"
1334
1039
% (e, os.environ.get('LANG')))
1335
user_encoding = 'ascii'
1337
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1338
# treat that as ASCII, and not support printing unicode characters to the
1340
if user_encoding in (None, 'cp0'):
1341
user_encoding = 'ascii'
1345
codecs.lookup(user_encoding)
1347
sys.stderr.write('bzr: warning:'
1348
' unknown encoding %s.'
1349
' Continuing with ascii encoding.\n'
1352
user_encoding = 'ascii'
1355
_cached_user_encoding = user_encoding
1357
return user_encoding
1360
def recv_all(socket, bytes):
1361
"""Receive an exact number of bytes.
1363
Regular Socket.recv() may return less than the requested number of bytes,
1364
dependning on what's in the OS buffer. MSG_WAITALL is not available
1365
on all platforms, but this should work everywhere. This will return
1366
less than the requested amount if the remote end closes.
1368
This isn't optimized and is intended mostly for use in testing.
1371
while len(b) < bytes:
1372
new = socket.recv(bytes - len(b))
1378
def dereference_path(path):
1379
"""Determine the real path to a file.
1381
All parent elements are dereferenced. But the file itself is not
1383
:param path: The original path. May be absolute or relative.
1384
:return: the real path *to* the file
1386
parent, base = os.path.split(path)
1387
# The pathjoin for '.' is a workaround for Python bug #1213894.
1388
# (initial path components aren't dereferenced)
1389
return pathjoin(realpath(pathjoin('.', parent)), base)
1041
if _cached_user_encoding is None:
1042
_cached_user_encoding = 'ascii'
1043
return _cached_user_encoding