171
222
rename_func(tmp_name, new)
173
# Default is to just use the python builtins
174
abspath = os.path.abspath
175
realpath = os.path.realpath
225
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
226
# choke on a Unicode string containing a relative path if
227
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
229
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
230
def _posix_abspath(path):
231
# jam 20060426 rather than encoding to fsencoding
232
# copy posixpath.abspath, but use os.getcwdu instead
233
if not posixpath.isabs(path):
234
path = posixpath.join(getcwd(), path)
235
return posixpath.normpath(path)
238
def _posix_realpath(path):
239
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
242
def _win32_fixdrive(path):
243
"""Force drive letters to be consistent.
245
win32 is inconsistent whether it returns lower or upper case
246
and even if it was consistent the user might type the other
247
so we force it to uppercase
248
running python.exe under cmd.exe return capital C:\\
249
running win32 python inside a cygwin shell returns lowercase c:\\
251
drive, path = _nt_splitdrive(path)
252
return drive.upper() + path
255
def _win32_abspath(path):
256
# Real _nt_abspath doesn't have a problem with a unicode cwd
257
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
260
def _win32_realpath(path):
261
# Real _nt_realpath doesn't have a problem with a unicode cwd
262
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
265
def _win32_pathjoin(*args):
266
return _nt_join(*args).replace('\\', '/')
269
def _win32_normpath(path):
270
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
274
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
277
def _win32_mkdtemp(*args, **kwargs):
278
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
281
def _win32_rename(old, new):
282
"""We expect to be able to atomically replace 'new' with old.
284
On win32, if new exists, it must be moved out of the way first,
288
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
290
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
291
# If we try to rename a non-existant file onto cwd, we get
292
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
293
# if the old path doesn't exist, sometimes we get EACCES
294
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
300
return unicodedata.normalize('NFKC', os.getcwdu())
303
# Default is to just use the python builtins, but these can be rebound on
304
# particular platforms.
305
abspath = _posix_abspath
306
realpath = _posix_realpath
176
307
pathjoin = os.path.join
177
308
normpath = os.path.normpath
178
309
getcwd = os.getcwdu
179
mkdtemp = tempfile.mkdtemp
180
310
rename = os.rename
181
311
dirname = os.path.dirname
182
312
basename = os.path.basename
184
if os.name == "posix":
185
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
186
# choke on a Unicode string containing a relative path if
187
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
189
_fs_enc = sys.getfilesystemencoding()
191
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
194
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
313
# These were already imported into local scope
314
# mkdtemp = tempfile.mkdtemp
315
# rmtree = shutil.rmtree
317
MIN_ABS_PATHLENGTH = 1
196
320
if sys.platform == 'win32':
197
# We need to use the Unicode-aware os.path.abspath and
198
# os.path.realpath on Windows systems.
200
return os.path.abspath(path).replace('\\', '/')
203
return os.path.realpath(path).replace('\\', '/')
206
return os.path.join(*args).replace('\\', '/')
209
return os.path.normpath(path).replace('\\', '/')
212
return os.getcwdu().replace('\\', '/')
214
def mkdtemp(*args, **kwargs):
215
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
217
def rename(old, new):
218
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
321
abspath = _win32_abspath
322
realpath = _win32_realpath
323
pathjoin = _win32_pathjoin
324
normpath = _win32_normpath
325
getcwd = _win32_getcwd
326
mkdtemp = _win32_mkdtemp
327
rename = _win32_rename
329
MIN_ABS_PATHLENGTH = 3
331
def _win32_delete_readonly(function, path, excinfo):
332
"""Error handler for shutil.rmtree function [for win32]
333
Helps to remove files and dirs marked as read-only.
335
exception = excinfo[1]
336
if function in (os.remove, os.rmdir) \
337
and isinstance(exception, OSError) \
338
and exception.errno == errno.EACCES:
344
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
345
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
346
return shutil.rmtree(path, ignore_errors, onerror)
347
elif sys.platform == 'darwin':
351
def get_terminal_encoding():
352
"""Find the best encoding for printing to the screen.
354
This attempts to check both sys.stdout and sys.stdin to see
355
what encoding they are in, and if that fails it falls back to
356
bzrlib.user_encoding.
357
The problem is that on Windows, locale.getpreferredencoding()
358
is not the same encoding as that used by the console:
359
http://mail.python.org/pipermail/python-list/2003-May/162357.html
361
On my standard US Windows XP, the preferred encoding is
362
cp1252, but the console is cp437
364
output_encoding = getattr(sys.stdout, 'encoding', None)
365
if not output_encoding:
366
input_encoding = getattr(sys.stdin, 'encoding', None)
367
if not input_encoding:
368
output_encoding = bzrlib.user_encoding
369
mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
371
output_encoding = input_encoding
372
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
374
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
375
if output_encoding == 'cp0':
376
# invalid encoding (cp0 means 'no codepage' on Windows)
377
output_encoding = bzrlib.user_encoding
378
mutter('cp0 is invalid encoding.'
379
' encoding stdout as bzrlib.user_encoding %r', output_encoding)
380
return output_encoding
221
383
def normalizepath(f):
222
if hasattr(os.path, 'realpath'):
384
if getattr(os.path, 'realpath', None) is not None:
636
830
return unicode_or_utf8_string.decode('utf8')
637
831
except UnicodeDecodeError:
638
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
832
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
835
_platform_normalizes_filenames = False
836
if sys.platform == 'darwin':
837
_platform_normalizes_filenames = True
840
def normalizes_filenames():
841
"""Return True if this platform normalizes unicode filenames.
843
Mac OSX does, Windows/Linux do not.
845
return _platform_normalizes_filenames
848
def _accessible_normalized_filename(path):
849
"""Get the unicode normalized path, and if you can access the file.
851
On platforms where the system normalizes filenames (Mac OSX),
852
you can access a file by any path which will normalize correctly.
853
On platforms where the system does not normalize filenames
854
(Windows, Linux), you have to access a file by its exact path.
856
Internally, bzr only supports NFC/NFKC normalization, since that is
857
the standard for XML documents.
859
So return the normalized path, and a flag indicating if the file
860
can be accessed by that path.
863
return unicodedata.normalize('NFKC', unicode(path)), True
866
def _inaccessible_normalized_filename(path):
867
__doc__ = _accessible_normalized_filename.__doc__
869
normalized = unicodedata.normalize('NFKC', unicode(path))
870
return normalized, normalized == path
873
if _platform_normalizes_filenames:
874
normalized_filename = _accessible_normalized_filename
876
normalized_filename = _inaccessible_normalized_filename
641
879
def terminal_width():
642
880
"""Return estimated terminal width."""
644
# TODO: Do something smart on Windows?
646
# TODO: Is there anything that gets a better update when the window
647
# is resized while the program is running? We could use the Python termcap
881
if sys.platform == 'win32':
882
import bzrlib.win32console
883
return bzrlib.win32console.get_console_size()[0]
650
return int(os.environ['COLUMNS'])
651
except (IndexError, KeyError, ValueError):
886
import struct, fcntl, termios
887
s = struct.pack('HHHH', 0, 0, 0, 0)
888
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
889
width = struct.unpack('HHHH', x)[1]
894
width = int(os.environ['COLUMNS'])
654
903
def supports_executable():
655
904
return sys.platform != "win32"
907
def set_or_unset_env(env_variable, value):
908
"""Modify the environment, setting or removing the env_variable.
910
:param env_variable: The environment variable in question
911
:param value: The value to set the environment to. If None, then
912
the variable will be removed.
913
:return: The original value of the environment variable.
915
orig_val = os.environ.get(env_variable)
917
if orig_val is not None:
918
del os.environ[env_variable]
920
if isinstance(value, unicode):
921
value = value.encode(bzrlib.user_encoding)
922
os.environ[env_variable] = value
926
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
929
def check_legal_path(path):
930
"""Check whether the supplied path is legal.
931
This is only required on Windows, so we don't test on other platforms
934
if sys.platform != "win32":
936
if _validWin32PathRE.match(path) is None:
937
raise errors.IllegalPath(path)
940
def walkdirs(top, prefix=""):
941
"""Yield data about all the directories in a tree.
943
This yields all the data about the contents of a directory at a time.
944
After each directory has been yielded, if the caller has mutated the list
945
to exclude some directories, they are then not descended into.
947
The data yielded is of the form:
948
((directory-relpath, directory-path-from-top),
949
[(relpath, basename, kind, lstat), ...]),
950
- directory-relpath is the relative path of the directory being returned
951
with respect to top. prefix is prepended to this.
952
- directory-path-from-root is the path including top for this directory.
953
It is suitable for use with os functions.
954
- relpath is the relative path within the subtree being walked.
955
- basename is the basename of the path
956
- kind is the kind of the file now. If unknown then the file is not
957
present within the tree - but it may be recorded as versioned. See
959
- lstat is the stat data *if* the file was statted.
960
- planned, not implemented:
961
path_from_tree_root is the path from the root of the tree.
963
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
964
allows one to walk a subtree but get paths that are relative to a tree
966
:return: an iterator over the dirs.
968
#TODO there is a bit of a smell where the results of the directory-
969
# summary in this, and the path from the root, may not agree
970
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
971
# potentially confusing output. We should make this more robust - but
972
# not at a speed cost. RBC 20060731
975
_directory = _directory_kind
976
_listdir = os.listdir
977
pending = [(prefix, "", _directory, None, top)]
980
currentdir = pending.pop()
981
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
984
relroot = currentdir[0] + '/'
987
for name in sorted(_listdir(top)):
988
abspath = top + '/' + name
989
statvalue = lstat(abspath)
990
dirblock.append((relroot + name, name,
991
file_kind_from_stat_mode(statvalue.st_mode),
993
yield (currentdir[0], top), dirblock
994
# push the user specified dirs from dirblock
995
for dir in reversed(dirblock):
996
if dir[2] == _directory:
1000
def copy_tree(from_path, to_path, handlers={}):
1001
"""Copy all of the entries in from_path into to_path.
1003
:param from_path: The base directory to copy.
1004
:param to_path: The target directory. If it does not exist, it will
1006
:param handlers: A dictionary of functions, which takes a source and
1007
destinations for files, directories, etc.
1008
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1009
'file', 'directory', and 'symlink' should always exist.
1010
If they are missing, they will be replaced with 'os.mkdir()',
1011
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1013
# Now, just copy the existing cached tree to the new location
1014
# We use a cheap trick here.
1015
# Absolute paths are prefixed with the first parameter
1016
# relative paths are prefixed with the second.
1017
# So we can get both the source and target returned
1018
# without any extra work.
1020
def copy_dir(source, dest):
1023
def copy_link(source, dest):
1024
"""Copy the contents of a symlink"""
1025
link_to = os.readlink(source)
1026
os.symlink(link_to, dest)
1028
real_handlers = {'file':shutil.copy2,
1029
'symlink':copy_link,
1030
'directory':copy_dir,
1032
real_handlers.update(handlers)
1034
if not os.path.exists(to_path):
1035
real_handlers['directory'](from_path, to_path)
1037
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1038
for relpath, name, kind, st, abspath in entries:
1039
real_handlers[kind](abspath, relpath)
1042
def path_prefix_key(path):
1043
"""Generate a prefix-order path key for path.
1045
This can be used to sort paths in the same way that walkdirs does.
1047
return (dirname(path) , path)
1050
def compare_paths_prefix_order(path_a, path_b):
1051
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1052
key_a = path_prefix_key(path_a)
1053
key_b = path_prefix_key(path_b)
1054
return cmp(key_a, key_b)
1057
_cached_user_encoding = None
1060
def get_user_encoding():
1061
"""Find out what the preferred user encoding is.
1063
This is generally the encoding that is used for command line parameters
1064
and file contents. This may be different from the terminal encoding
1065
or the filesystem encoding.
1067
:return: A string defining the preferred user encoding
1069
global _cached_user_encoding
1070
if _cached_user_encoding is not None:
1071
return _cached_user_encoding
1073
if sys.platform == 'darwin':
1074
# work around egregious python 2.4 bug
1075
sys.platform = 'posix'
1079
sys.platform = 'darwin'
1084
_cached_user_encoding = locale.getpreferredencoding()
1085
except locale.Error, e:
1086
sys.stderr.write('bzr: warning: %s\n'
1087
' Could not determine what text encoding to use.\n'
1088
' This error usually means your Python interpreter\n'
1089
' doesn\'t support the locale set by $LANG (%s)\n'
1090
" Continuing with ascii encoding.\n"
1091
% (e, os.environ.get('LANG')))
1093
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1094
# treat that as ASCII, and not support printing unicode characters to the
1096
if _cached_user_encoding in (None, 'cp0'):
1097
_cached_user_encoding = 'ascii'
1098
return _cached_user_encoding
1101
def recv_all(socket, bytes):
1102
"""Receive an exact number of bytes.
1104
Regular Socket.recv() may return less than the requested number of bytes,
1105
dependning on what's in the OS buffer. MSG_WAITALL is not available
1106
on all platforms, but this should work everywhere. This will return
1107
less than the requested amount if the remote end closes.
1109
This isn't optimized and is intended mostly for use in testing.
1112
while len(b) < bytes:
1113
new = socket.recv(bytes - len(b))
1119
def dereference_path(path):
1120
"""Determine the real path to a file.
1122
All parent elements are dereferenced. But the file itself is not
1124
:param path: The original path. May be absolute or relative.
1125
:return: the real path *to* the file
1127
parent, base = os.path.split(path)
1128
# The pathjoin for '.' is a workaround for Python bug #1213894.
1129
# (initial path components aren't dereferenced)
1130
return pathjoin(realpath(pathjoin('.', parent)), base)