104
_directory_kind = 'directory'
107
stat.S_IFDIR:_directory_kind,
108
stat.S_IFCHR:'chardev',
109
stat.S_IFBLK:'block',
112
stat.S_IFLNK:'symlink',
113
stat.S_IFSOCK:'socket',
117
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
118
"""Generate a file kind from a stat mode. This is used in walkdirs.
120
Its performance is critical: Do not mutate without careful benchmarking.
123
return _formats[stat_mode & 0170000]
128
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
130
return _mapper(_lstat(f).st_mode)
132
if getattr(e, 'errno', None) == errno.ENOENT:
133
raise errors.NoSuchFile(f)
138
"""Return the current umask"""
139
# Assume that people aren't messing with the umask while running
140
# XXX: This is not thread safe, but there is no way to get the
141
# umask without setting it
70
mode = os.lstat(f)[ST_MODE]
147
89
def kind_marker(kind):
148
90
if kind == 'file':
150
elif kind == _directory_kind:
92
elif kind == 'directory':
152
94
elif kind == 'symlink':
155
raise errors.BzrError('invalid file kind %r' % kind)
157
lexists = getattr(os.path, 'lexists', None)
161
if getattr(os, 'lstat') is not None:
167
if e.errno == errno.ENOENT:
170
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
173
def fancy_rename(old, new, rename_func, unlink_func):
174
"""A fancy rename, when you don't have atomic rename.
176
:param old: The old path, to rename from
177
:param new: The new path, to rename to
178
:param rename_func: The potentially non-atomic rename function
179
:param unlink_func: A way to delete the target file if the full rename succeeds
182
# sftp rename doesn't allow overwriting, so play tricks:
184
base = os.path.basename(new)
185
dirname = os.path.dirname(new)
186
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
187
tmp_name = pathjoin(dirname, tmp_name)
189
# Rename the file out of the way, but keep track if it didn't exist
190
# We don't want to grab just any exception
191
# something like EACCES should prevent us from continuing
192
# The downside is that the rename_func has to throw an exception
193
# with an errno = ENOENT, or NoSuchFile
196
rename_func(new, tmp_name)
197
except (errors.NoSuchFile,), e:
200
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
201
# function raises an IOError with errno is None when a rename fails.
202
# This then gets caught here.
203
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
206
if (getattr(e, 'errno', None) is None
207
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
214
# This may throw an exception, in which case success will
216
rename_func(old, new)
220
# If the file used to exist, rename it back into place
221
# otherwise just delete it from the tmp location
223
unlink_func(tmp_name)
225
rename_func(tmp_name, new)
228
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
229
# choke on a Unicode string containing a relative path if
230
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
232
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
233
def _posix_abspath(path):
234
# jam 20060426 rather than encoding to fsencoding
235
# copy posixpath.abspath, but use os.getcwdu instead
236
if not posixpath.isabs(path):
237
path = posixpath.join(getcwd(), path)
238
return posixpath.normpath(path)
241
def _posix_realpath(path):
242
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
245
def _win32_fixdrive(path):
246
"""Force drive letters to be consistent.
248
win32 is inconsistent whether it returns lower or upper case
249
and even if it was consistent the user might type the other
250
so we force it to uppercase
251
running python.exe under cmd.exe return capital C:\\
252
running win32 python inside a cygwin shell returns lowercase c:\\
254
drive, path = _nt_splitdrive(path)
255
return drive.upper() + path
258
def _win32_abspath(path):
259
# Real _nt_abspath doesn't have a problem with a unicode cwd
260
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
263
def _win32_realpath(path):
264
# Real _nt_realpath doesn't have a problem with a unicode cwd
265
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
268
def _win32_pathjoin(*args):
269
return _nt_join(*args).replace('\\', '/')
272
def _win32_normpath(path):
273
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
277
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
280
def _win32_mkdtemp(*args, **kwargs):
281
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
284
def _win32_rename(old, new):
285
"""We expect to be able to atomically replace 'new' with old.
287
On win32, if new exists, it must be moved out of the way first,
291
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
293
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
294
# If we try to rename a non-existant file onto cwd, we get
295
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
296
# if the old path doesn't exist, sometimes we get EACCES
297
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
303
return unicodedata.normalize('NFKC', os.getcwdu())
306
# Default is to just use the python builtins, but these can be rebound on
307
# particular platforms.
308
abspath = _posix_abspath
309
realpath = _posix_realpath
310
pathjoin = os.path.join
311
normpath = os.path.normpath
314
dirname = os.path.dirname
315
basename = os.path.basename
316
split = os.path.split
317
splitext = os.path.splitext
318
# These were already imported into local scope
319
# mkdtemp = tempfile.mkdtemp
320
# rmtree = shutil.rmtree
322
MIN_ABS_PATHLENGTH = 1
325
if sys.platform == 'win32':
326
abspath = _win32_abspath
327
realpath = _win32_realpath
328
pathjoin = _win32_pathjoin
329
normpath = _win32_normpath
330
getcwd = _win32_getcwd
331
mkdtemp = _win32_mkdtemp
332
rename = _win32_rename
334
MIN_ABS_PATHLENGTH = 3
336
def _win32_delete_readonly(function, path, excinfo):
337
"""Error handler for shutil.rmtree function [for win32]
338
Helps to remove files and dirs marked as read-only.
340
exception = excinfo[1]
341
if function in (os.remove, os.rmdir) \
342
and isinstance(exception, OSError) \
343
and exception.errno == errno.EACCES:
349
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
350
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
351
return shutil.rmtree(path, ignore_errors, onerror)
352
elif sys.platform == 'darwin':
356
def get_terminal_encoding():
357
"""Find the best encoding for printing to the screen.
359
This attempts to check both sys.stdout and sys.stdin to see
360
what encoding they are in, and if that fails it falls back to
361
bzrlib.user_encoding.
362
The problem is that on Windows, locale.getpreferredencoding()
363
is not the same encoding as that used by the console:
364
http://mail.python.org/pipermail/python-list/2003-May/162357.html
366
On my standard US Windows XP, the preferred encoding is
367
cp1252, but the console is cp437
369
output_encoding = getattr(sys.stdout, 'encoding', None)
370
if not output_encoding:
371
input_encoding = getattr(sys.stdin, 'encoding', None)
372
if not input_encoding:
373
output_encoding = bzrlib.user_encoding
374
mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
376
output_encoding = input_encoding
377
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
379
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
380
if output_encoding == 'cp0':
381
# invalid encoding (cp0 means 'no codepage' on Windows)
382
output_encoding = bzrlib.user_encoding
383
mutter('cp0 is invalid encoding.'
384
' encoding stdout as bzrlib.user_encoding %r', output_encoding)
387
codecs.lookup(output_encoding)
389
sys.stderr.write('bzr: warning:'
390
' unknown terminal encoding %s.\n'
391
' Using encoding %s instead.\n'
392
% (output_encoding, bzrlib.user_encoding)
394
output_encoding = bzrlib.user_encoding
396
return output_encoding
97
raise BzrError('invalid file kind %r' % kind)
101
if hasattr(os, 'lstat'):
107
if e.errno == errno.ENOENT:
110
raise BzrError("lstat/stat of (%r): %r" % (f, e))
399
112
def normalizepath(f):
400
if getattr(os.path, 'realpath', None) is not None:
113
if hasattr(os.path, 'realpath'):
404
117
[p,e] = os.path.split(f)
405
118
if e == "" or e == "." or e == "..":
408
return pathjoin(F(p), e)
121
return os.path.join(F(p), e)
123
if os.name == "posix":
124
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
125
# choke on a Unicode string containing a relative path if
126
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
128
_fs_enc = sys.getfilesystemencoding()
130
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
132
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
134
# We need to use the Unicode-aware os.path.abspath and
135
# os.path.realpath on Windows systems.
136
abspath = os.path.abspath
137
realpath = os.path.realpath
411
139
def backup_file(fn):
412
140
"""Copy a file to a backup.
821
480
s.insert(0, tail)
823
raise errors.PathNotChild(rp, base)
831
def safe_unicode(unicode_or_utf8_string):
832
"""Coerce unicode_or_utf8_string into unicode.
834
If it is unicode, it is returned.
835
Otherwise it is decoded from utf-8. If a decoding error
836
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
837
as a BzrBadParameter exception.
839
if isinstance(unicode_or_utf8_string, unicode):
840
return unicode_or_utf8_string
842
return unicode_or_utf8_string.decode('utf8')
843
except UnicodeDecodeError:
844
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
847
def safe_utf8(unicode_or_utf8_string):
848
"""Coerce unicode_or_utf8_string to a utf8 string.
850
If it is a str, it is returned.
851
If it is Unicode, it is encoded into a utf-8 string.
853
if isinstance(unicode_or_utf8_string, str):
854
# TODO: jam 20070209 This is overkill, and probably has an impact on
855
# performance if we are dealing with lots of apis that want a
858
# Make sure it is a valid utf-8 string
859
unicode_or_utf8_string.decode('utf-8')
860
except UnicodeDecodeError:
861
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
862
return unicode_or_utf8_string
863
return unicode_or_utf8_string.encode('utf-8')
866
def safe_revision_id(unicode_or_utf8_string):
867
"""Revision ids should now be utf8, but at one point they were unicode.
869
This is the same as safe_utf8, except it uses the cached encode functions
870
to save a little bit of performance.
872
if unicode_or_utf8_string is None:
874
if isinstance(unicode_or_utf8_string, str):
875
# TODO: jam 20070209 Eventually just remove this check.
877
utf8_str = cache_utf8.get_cached_utf8(unicode_or_utf8_string)
878
except UnicodeDecodeError:
879
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
881
return cache_utf8.encode(unicode_or_utf8_string)
884
_platform_normalizes_filenames = False
885
if sys.platform == 'darwin':
886
_platform_normalizes_filenames = True
889
def normalizes_filenames():
890
"""Return True if this platform normalizes unicode filenames.
892
Mac OSX does, Windows/Linux do not.
894
return _platform_normalizes_filenames
897
def _accessible_normalized_filename(path):
898
"""Get the unicode normalized path, and if you can access the file.
900
On platforms where the system normalizes filenames (Mac OSX),
901
you can access a file by any path which will normalize correctly.
902
On platforms where the system does not normalize filenames
903
(Windows, Linux), you have to access a file by its exact path.
905
Internally, bzr only supports NFC/NFKC normalization, since that is
906
the standard for XML documents.
908
So return the normalized path, and a flag indicating if the file
909
can be accessed by that path.
912
return unicodedata.normalize('NFKC', unicode(path)), True
915
def _inaccessible_normalized_filename(path):
916
__doc__ = _accessible_normalized_filename.__doc__
918
normalized = unicodedata.normalize('NFKC', unicode(path))
919
return normalized, normalized == path
922
if _platform_normalizes_filenames:
923
normalized_filename = _accessible_normalized_filename
925
normalized_filename = _inaccessible_normalized_filename
928
def terminal_width():
929
"""Return estimated terminal width."""
930
if sys.platform == 'win32':
931
import bzrlib.win32console
932
return bzrlib.win32console.get_console_size()[0]
935
import struct, fcntl, termios
936
s = struct.pack('HHHH', 0, 0, 0, 0)
937
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
938
width = struct.unpack('HHHH', x)[1]
943
width = int(os.environ['COLUMNS'])
952
def supports_executable():
953
return sys.platform != "win32"
956
def set_or_unset_env(env_variable, value):
957
"""Modify the environment, setting or removing the env_variable.
959
:param env_variable: The environment variable in question
960
:param value: The value to set the environment to. If None, then
961
the variable will be removed.
962
:return: The original value of the environment variable.
964
orig_val = os.environ.get(env_variable)
966
if orig_val is not None:
967
del os.environ[env_variable]
969
if isinstance(value, unicode):
970
value = value.encode(bzrlib.user_encoding)
971
os.environ[env_variable] = value
975
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
978
def check_legal_path(path):
979
"""Check whether the supplied path is legal.
980
This is only required on Windows, so we don't test on other platforms
983
if sys.platform != "win32":
985
if _validWin32PathRE.match(path) is None:
986
raise errors.IllegalPath(path)
989
def walkdirs(top, prefix=""):
990
"""Yield data about all the directories in a tree.
992
This yields all the data about the contents of a directory at a time.
993
After each directory has been yielded, if the caller has mutated the list
994
to exclude some directories, they are then not descended into.
996
The data yielded is of the form:
997
((directory-relpath, directory-path-from-top),
998
[(relpath, basename, kind, lstat), ...]),
999
- directory-relpath is the relative path of the directory being returned
1000
with respect to top. prefix is prepended to this.
1001
- directory-path-from-root is the path including top for this directory.
1002
It is suitable for use with os functions.
1003
- relpath is the relative path within the subtree being walked.
1004
- basename is the basename of the path
1005
- kind is the kind of the file now. If unknown then the file is not
1006
present within the tree - but it may be recorded as versioned. See
1008
- lstat is the stat data *if* the file was statted.
1009
- planned, not implemented:
1010
path_from_tree_root is the path from the root of the tree.
1012
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1013
allows one to walk a subtree but get paths that are relative to a tree
1015
:return: an iterator over the dirs.
1017
#TODO there is a bit of a smell where the results of the directory-
1018
# summary in this, and the path from the root, may not agree
1019
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1020
# potentially confusing output. We should make this more robust - but
1021
# not at a speed cost. RBC 20060731
1024
_directory = _directory_kind
1025
_listdir = os.listdir
1026
pending = [(prefix, "", _directory, None, top)]
1029
currentdir = pending.pop()
1030
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1033
relroot = currentdir[0] + '/'
1036
for name in sorted(_listdir(top)):
1037
abspath = top + '/' + name
1038
statvalue = lstat(abspath)
1039
dirblock.append((relroot + name, name,
1040
file_kind_from_stat_mode(statvalue.st_mode),
1041
statvalue, abspath))
1042
yield (currentdir[0], top), dirblock
1043
# push the user specified dirs from dirblock
1044
for dir in reversed(dirblock):
1045
if dir[2] == _directory:
1049
def copy_tree(from_path, to_path, handlers={}):
1050
"""Copy all of the entries in from_path into to_path.
1052
:param from_path: The base directory to copy.
1053
:param to_path: The target directory. If it does not exist, it will
1055
:param handlers: A dictionary of functions, which takes a source and
1056
destinations for files, directories, etc.
1057
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1058
'file', 'directory', and 'symlink' should always exist.
1059
If they are missing, they will be replaced with 'os.mkdir()',
1060
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1062
# Now, just copy the existing cached tree to the new location
1063
# We use a cheap trick here.
1064
# Absolute paths are prefixed with the first parameter
1065
# relative paths are prefixed with the second.
1066
# So we can get both the source and target returned
1067
# without any extra work.
1069
def copy_dir(source, dest):
1072
def copy_link(source, dest):
1073
"""Copy the contents of a symlink"""
1074
link_to = os.readlink(source)
1075
os.symlink(link_to, dest)
1077
real_handlers = {'file':shutil.copy2,
1078
'symlink':copy_link,
1079
'directory':copy_dir,
1081
real_handlers.update(handlers)
1083
if not os.path.exists(to_path):
1084
real_handlers['directory'](from_path, to_path)
1086
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1087
for relpath, name, kind, st, abspath in entries:
1088
real_handlers[kind](abspath, relpath)
1091
def path_prefix_key(path):
1092
"""Generate a prefix-order path key for path.
1094
This can be used to sort paths in the same way that walkdirs does.
1096
return (dirname(path) , path)
1099
def compare_paths_prefix_order(path_a, path_b):
1100
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1101
key_a = path_prefix_key(path_a)
1102
key_b = path_prefix_key(path_b)
1103
return cmp(key_a, key_b)
1106
_cached_user_encoding = None
1109
def get_user_encoding(use_cache=True):
1110
"""Find out what the preferred user encoding is.
1112
This is generally the encoding that is used for command line parameters
1113
and file contents. This may be different from the terminal encoding
1114
or the filesystem encoding.
1116
:param use_cache: Enable cache for detected encoding.
1117
(This parameter is turned on by default,
1118
and required only for selftesting)
1120
:return: A string defining the preferred user encoding
1122
global _cached_user_encoding
1123
if _cached_user_encoding is not None and use_cache:
1124
return _cached_user_encoding
1126
if sys.platform == 'darwin':
1127
# work around egregious python 2.4 bug
1128
sys.platform = 'posix'
1132
sys.platform = 'darwin'
1137
user_encoding = locale.getpreferredencoding()
1138
except locale.Error, e:
1139
sys.stderr.write('bzr: warning: %s\n'
1140
' Could not determine what text encoding to use.\n'
1141
' This error usually means your Python interpreter\n'
1142
' doesn\'t support the locale set by $LANG (%s)\n'
1143
" Continuing with ascii encoding.\n"
1144
% (e, os.environ.get('LANG')))
1145
user_encoding = 'ascii'
1147
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1148
# treat that as ASCII, and not support printing unicode characters to the
1150
if user_encoding in (None, 'cp0'):
1151
user_encoding = 'ascii'
1155
codecs.lookup(user_encoding)
1157
sys.stderr.write('bzr: warning:'
1158
' unknown encoding %s.'
1159
' Continuing with ascii encoding.\n'
1162
user_encoding = 'ascii'
1165
_cached_user_encoding = user_encoding
1167
return user_encoding
1170
def recv_all(socket, bytes):
1171
"""Receive an exact number of bytes.
1173
Regular Socket.recv() may return less than the requested number of bytes,
1174
dependning on what's in the OS buffer. MSG_WAITALL is not available
1175
on all platforms, but this should work everywhere. This will return
1176
less than the requested amount if the remote end closes.
1178
This isn't optimized and is intended mostly for use in testing.
1181
while len(b) < bytes:
1182
new = socket.recv(bytes - len(b))
1188
def dereference_path(path):
1189
"""Determine the real path to a file.
1191
All parent elements are dereferenced. But the file itself is not
1193
:param path: The original path. May be absolute or relative.
1194
:return: the real path *to* the file
1196
parent, base = os.path.split(path)
1197
# The pathjoin for '.' is a workaround for Python bug #1213894.
1198
# (initial path components aren't dereferenced)
1199
return pathjoin(realpath(pathjoin('.', parent)), base)
482
# XXX This should raise a NotChildPath exception, as its not tied
484
raise NotBranchError("path %r is not within branch %r" % (rp, base))
486
return os.sep.join(s)