1
# Bazaar-NG -- distributed version control
3
# Copyright (C) 2005 by Canonical Ltd
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
7
5
# the Free Software Foundation; either version 2 of the License, or
8
6
# (at your option) any later version.
10
8
# This program is distributed in the hope that it will be useful,
11
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
11
# GNU General Public License for more details.
15
13
# You should have received a copy of the GNU General Public License
16
14
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
import os, types, re, time, errno, sys
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
22
from errors import bailout, BzrError
23
from trace import mutter
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
29
from datetime import datetime
31
from ntpath import (abspath as _nt_abspath,
33
normpath as _nt_normpath,
34
realpath as _nt_realpath,
35
splitdrive as _nt_splitdrive,
45
from tempfile import (
57
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
59
if sys.version_info < (2, 5):
60
import md5 as _mod_md5
62
import sha as _mod_sha
72
from bzrlib import symbol_versioning
75
# Cross platform wall-clock time functionality with decent resolution.
76
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
77
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
78
# synchronized with ``time.time()``, this is only meant to be used to find
79
# delta times by subtracting from another call to this function.
80
timer_func = time.time
81
if sys.platform == 'win32':
82
timer_func = time.clock
84
# On win32, O_BINARY is used to indicate the file should
85
# be opened in binary mode, rather than text mode.
86
# On other platforms, O_BINARY doesn't exist, because
87
# they always open in binary mode, so it is okay to
88
# OR with 0 on those platforms
89
O_BINARY = getattr(os, 'O_BINARY', 0)
92
def get_unicode_argv():
94
user_encoding = get_user_encoding()
95
return [a.decode(user_encoding) for a in sys.argv[1:]]
96
except UnicodeDecodeError:
97
raise errors.BzrError(("Parameter '%r' is unsupported by the current "
26
101
def make_readonly(filename):
27
102
"""Make a filename read-only."""
28
# TODO: probably needs to be fixed for windows
29
mod = os.stat(filename).st_mode
31
os.chmod(filename, mod)
103
mod = os.lstat(filename).st_mode
104
if not stat.S_ISLNK(mod):
106
os.chmod(filename, mod)
34
109
def make_writable(filename):
35
mod = os.stat(filename).st_mode
37
os.chmod(filename, mod)
40
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
110
mod = os.lstat(filename).st_mode
111
if not stat.S_ISLNK(mod):
113
os.chmod(filename, mod)
116
def minimum_path_selection(paths):
117
"""Return the smallset subset of paths which are outside paths.
119
:param paths: A container (and hence not None) of paths.
120
:return: A set of paths sufficient to include everything in paths via
121
is_inside, drawn from the paths parameter.
127
return path.split('/')
128
sorted_paths = sorted(list(paths), key=sort_key)
130
search_paths = [sorted_paths[0]]
131
for path in sorted_paths[1:]:
132
if not is_inside(search_paths[-1], path):
133
# This path is unique, add it
134
search_paths.append(path)
136
return set(search_paths)
42
"""Return shell-quoted filename"""
43
## We could be a bit more terse by using double-quotes etc
44
f = _QUOTE_RE.sub(r'\\\1', f)
51
mode = os.lstat(f)[ST_MODE]
59
raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
143
"""Return a quoted filename filename
145
This previously used backslash quoting, but that works poorly on
147
# TODO: I'm not really sure this is the best format either.x
149
if _QUOTE_RE is None:
150
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
152
if _QUOTE_RE.search(f):
158
_directory_kind = 'directory'
161
"""Return the current umask"""
162
# Assume that people aren't messing with the umask while running
163
# XXX: This is not thread safe, but there is no way to get the
164
# umask without setting it
172
_directory_kind: "/",
174
'tree-reference': '+',
178
def kind_marker(kind):
180
return _kind_marker_map[kind]
182
raise errors.BzrError('invalid file kind %r' % kind)
185
lexists = getattr(os.path, 'lexists', None)
189
stat = getattr(os, 'lstat', os.stat)
193
if e.errno == errno.ENOENT:
196
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
199
def fancy_rename(old, new, rename_func, unlink_func):
200
"""A fancy rename, when you don't have atomic rename.
202
:param old: The old path, to rename from
203
:param new: The new path, to rename to
204
:param rename_func: The potentially non-atomic rename function
205
:param unlink_func: A way to delete the target file if the full rename succeeds
208
# sftp rename doesn't allow overwriting, so play tricks:
209
base = os.path.basename(new)
210
dirname = os.path.dirname(new)
211
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
212
tmp_name = pathjoin(dirname, tmp_name)
214
# Rename the file out of the way, but keep track if it didn't exist
215
# We don't want to grab just any exception
216
# something like EACCES should prevent us from continuing
217
# The downside is that the rename_func has to throw an exception
218
# with an errno = ENOENT, or NoSuchFile
221
rename_func(new, tmp_name)
222
except (errors.NoSuchFile,), e:
225
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
226
# function raises an IOError with errno is None when a rename fails.
227
# This then gets caught here.
228
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
231
if (getattr(e, 'errno', None) is None
232
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
241
# This may throw an exception, in which case success will
243
rename_func(old, new)
245
except (IOError, OSError), e:
246
# source and target may be aliases of each other (e.g. on a
247
# case-insensitive filesystem), so we may have accidentally renamed
248
# source by when we tried to rename target
249
failure_exc = sys.exc_info()
250
if (file_existed and e.errno in (None, errno.ENOENT)
251
and old.lower() == new.lower()):
252
# source and target are the same file on a case-insensitive
253
# filesystem, so we don't generate an exception
257
# If the file used to exist, rename it back into place
258
# otherwise just delete it from the tmp location
260
unlink_func(tmp_name)
262
rename_func(tmp_name, new)
263
if failure_exc is not None:
264
raise failure_exc[0], failure_exc[1], failure_exc[2]
267
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
268
# choke on a Unicode string containing a relative path if
269
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
271
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
272
def _posix_abspath(path):
273
# jam 20060426 rather than encoding to fsencoding
274
# copy posixpath.abspath, but use os.getcwdu instead
275
if not posixpath.isabs(path):
276
path = posixpath.join(getcwd(), path)
277
return posixpath.normpath(path)
280
def _posix_realpath(path):
281
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
284
def _win32_fixdrive(path):
285
"""Force drive letters to be consistent.
287
win32 is inconsistent whether it returns lower or upper case
288
and even if it was consistent the user might type the other
289
so we force it to uppercase
290
running python.exe under cmd.exe return capital C:\\
291
running win32 python inside a cygwin shell returns lowercase c:\\
293
drive, path = _nt_splitdrive(path)
294
return drive.upper() + path
297
def _win32_abspath(path):
298
# Real _nt_abspath doesn't have a problem with a unicode cwd
299
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
302
def _win98_abspath(path):
303
"""Return the absolute version of a path.
304
Windows 98 safe implementation (python reimplementation
305
of Win32 API function GetFullPathNameW)
310
# \\HOST\path => //HOST/path
311
# //HOST/path => //HOST/path
312
# path => C:/cwd/path
315
# check for absolute path
316
drive = _nt_splitdrive(path)[0]
317
if drive == '' and path[:2] not in('//','\\\\'):
319
# we cannot simply os.path.join cwd and path
320
# because os.path.join('C:','/path') produce '/path'
321
# and this is incorrect
322
if path[:1] in ('/','\\'):
323
cwd = _nt_splitdrive(cwd)[0]
325
path = cwd + '\\' + path
326
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
329
def _win32_realpath(path):
330
# Real _nt_realpath doesn't have a problem with a unicode cwd
331
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
334
def _win32_pathjoin(*args):
335
return _nt_join(*args).replace('\\', '/')
338
def _win32_normpath(path):
339
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
343
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
346
def _win32_mkdtemp(*args, **kwargs):
347
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
350
def _win32_rename(old, new):
351
"""We expect to be able to atomically replace 'new' with old.
353
On win32, if new exists, it must be moved out of the way first,
357
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
359
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
360
# If we try to rename a non-existant file onto cwd, we get
361
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
362
# if the old path doesn't exist, sometimes we get EACCES
363
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
369
return unicodedata.normalize('NFC', os.getcwdu())
372
# Default is to just use the python builtins, but these can be rebound on
373
# particular platforms.
374
abspath = _posix_abspath
375
realpath = _posix_realpath
376
pathjoin = os.path.join
377
normpath = os.path.normpath
380
dirname = os.path.dirname
381
basename = os.path.basename
382
split = os.path.split
383
splitext = os.path.splitext
384
# These were already imported into local scope
385
# mkdtemp = tempfile.mkdtemp
386
# rmtree = shutil.rmtree
388
MIN_ABS_PATHLENGTH = 1
391
if sys.platform == 'win32':
392
if win32utils.winver == 'Windows 98':
393
abspath = _win98_abspath
395
abspath = _win32_abspath
396
realpath = _win32_realpath
397
pathjoin = _win32_pathjoin
398
normpath = _win32_normpath
399
getcwd = _win32_getcwd
400
mkdtemp = _win32_mkdtemp
401
rename = _win32_rename
403
MIN_ABS_PATHLENGTH = 3
405
def _win32_delete_readonly(function, path, excinfo):
406
"""Error handler for shutil.rmtree function [for win32]
407
Helps to remove files and dirs marked as read-only.
409
exception = excinfo[1]
410
if function in (os.remove, os.rmdir) \
411
and isinstance(exception, OSError) \
412
and exception.errno == errno.EACCES:
418
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
419
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
420
return shutil.rmtree(path, ignore_errors, onerror)
422
f = win32utils.get_unicode_argv # special function or None
426
elif sys.platform == 'darwin':
430
def get_terminal_encoding():
431
"""Find the best encoding for printing to the screen.
433
This attempts to check both sys.stdout and sys.stdin to see
434
what encoding they are in, and if that fails it falls back to
435
osutils.get_user_encoding().
436
The problem is that on Windows, locale.getpreferredencoding()
437
is not the same encoding as that used by the console:
438
http://mail.python.org/pipermail/python-list/2003-May/162357.html
440
On my standard US Windows XP, the preferred encoding is
441
cp1252, but the console is cp437
443
from bzrlib.trace import mutter
444
output_encoding = getattr(sys.stdout, 'encoding', None)
445
if not output_encoding:
446
input_encoding = getattr(sys.stdin, 'encoding', None)
447
if not input_encoding:
448
output_encoding = get_user_encoding()
449
mutter('encoding stdout as osutils.get_user_encoding() %r',
452
output_encoding = input_encoding
453
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
455
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
456
if output_encoding == 'cp0':
457
# invalid encoding (cp0 means 'no codepage' on Windows)
458
output_encoding = get_user_encoding()
459
mutter('cp0 is invalid encoding.'
460
' encoding stdout as osutils.get_user_encoding() %r',
464
codecs.lookup(output_encoding)
466
sys.stderr.write('bzr: warning:'
467
' unknown terminal encoding %s.\n'
468
' Using encoding %s instead.\n'
469
% (output_encoding, get_user_encoding())
471
output_encoding = get_user_encoding()
473
return output_encoding
476
def normalizepath(f):
477
if getattr(os.path, 'realpath', None) is not None:
481
[p,e] = os.path.split(f)
482
if e == "" or e == "." or e == "..":
485
return pathjoin(F(p), e)
241
700
def local_time_offset(t=None):
242
701
"""Return offset of local zone from GMT, either at present or at time t."""
243
# python2.3 localtime() can't take None
247
if time.localtime(t).tm_isdst and time.daylight:
250
return -time.timezone
253
def format_date(t, offset=0, timezone='original'):
254
## TODO: Perhaps a global option to use either universal or local time?
255
## Or perhaps just let people set $TZ?
256
assert isinstance(t, float)
704
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
705
return offset.days * 86400 + offset.seconds
707
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
708
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
711
def format_date(t, offset=0, timezone='original', date_fmt=None,
713
"""Return a formatted date string.
715
:param t: Seconds since the epoch.
716
:param offset: Timezone offset in seconds east of utc.
717
:param timezone: How to display the time: 'utc', 'original' for the
718
timezone specified by offset, or 'local' for the process's current
720
:param date_fmt: strftime format.
721
:param show_offset: Whether to append the timezone.
723
(date_fmt, tt, offset_str) = \
724
_format_date(t, offset, timezone, date_fmt, show_offset)
725
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
726
date_str = time.strftime(date_fmt, tt)
727
return date_str + offset_str
730
# Cache of formatted offset strings
734
def format_date_with_offset_in_original_timezone(t, offset=0,
735
_cache=_offset_cache):
736
"""Return a formatted date string in the original timezone.
738
This routine may be faster then format_date.
740
:param t: Seconds since the epoch.
741
:param offset: Timezone offset in seconds east of utc.
745
tt = time.gmtime(t + offset)
746
date_fmt = _default_format_by_weekday_num[tt[6]]
747
date_str = time.strftime(date_fmt, tt)
748
offset_str = _cache.get(offset, None)
749
if offset_str is None:
750
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
751
_cache[offset] = offset_str
752
return date_str + offset_str
755
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
757
"""Return an unicode date string formatted according to the current locale.
759
:param t: Seconds since the epoch.
760
:param offset: Timezone offset in seconds east of utc.
761
:param timezone: How to display the time: 'utc', 'original' for the
762
timezone specified by offset, or 'local' for the process's current
764
:param date_fmt: strftime format.
765
:param show_offset: Whether to append the timezone.
767
(date_fmt, tt, offset_str) = \
768
_format_date(t, offset, timezone, date_fmt, show_offset)
769
date_str = time.strftime(date_fmt, tt)
770
if not isinstance(date_str, unicode):
771
date_str = date_str.decode(get_user_encoding(), 'replace')
772
return date_str + offset_str
775
def _format_date(t, offset, timezone, date_fmt, show_offset):
258
776
if timezone == 'utc':
259
777
tt = time.gmtime(t)
261
779
elif timezone == 'original':
264
782
tt = time.gmtime(t + offset)
265
783
elif timezone == 'local':
266
784
tt = time.localtime(t)
267
785
offset = local_time_offset(t)
269
bailout("unsupported timezone format %r",
270
['options are "utc", "original", "local"'])
272
return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
273
+ ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
787
raise errors.UnsupportedTimezoneFormat(timezone)
789
date_fmt = "%a %Y-%m-%d %H:%M:%S"
791
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
794
return (date_fmt, tt, offset_str)
276
797
def compact_date(when):
277
798
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
801
def format_delta(delta):
802
"""Get a nice looking string for a time delta.
804
:param delta: The time difference in seconds, can be positive or negative.
805
positive indicates time in the past, negative indicates time in the
806
future. (usually time.time() - stored_time)
807
:return: String formatted to show approximate resolution
813
direction = 'in the future'
817
if seconds < 90: # print seconds up to 90 seconds
819
return '%d second %s' % (seconds, direction,)
821
return '%d seconds %s' % (seconds, direction)
823
minutes = int(seconds / 60)
824
seconds -= 60 * minutes
829
if minutes < 90: # print minutes, seconds up to 90 minutes
831
return '%d minute, %d second%s %s' % (
832
minutes, seconds, plural_seconds, direction)
834
return '%d minutes, %d second%s %s' % (
835
minutes, seconds, plural_seconds, direction)
837
hours = int(minutes / 60)
838
minutes -= 60 * hours
845
return '%d hour, %d minute%s %s' % (hours, minutes,
846
plural_minutes, direction)
847
return '%d hours, %d minute%s %s' % (hours, minutes,
848
plural_minutes, direction)
282
851
"""Return size of given open file."""
283
852
return os.fstat(f.fileno())[ST_SIZE]
286
if hasattr(os, 'urandom'): # python 2.4 and later
855
# Define rand_bytes based on platform.
857
# Python 2.4 and later have os.urandom,
858
# but it doesn't work on some arches
287
860
rand_bytes = os.urandom
288
elif sys.platform == 'linux2':
289
rand_bytes = file('/dev/urandom', 'rb').read
291
# not well seeded, but better than nothing
296
s += chr(random.randint(0, 255))
861
except (NotImplementedError, AttributeError):
862
# If python doesn't have os.urandom, or it doesn't work,
863
# then try to first pull random data from /dev/urandom
865
rand_bytes = file('/dev/urandom', 'rb').read
866
# Otherwise, use this hack as a last resort
867
except (IOError, OSError):
868
# not well seeded, but better than nothing
873
s += chr(random.randint(0, 255))
878
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
880
"""Return a random string of num alphanumeric characters
882
The result only contains lowercase chars because it may be used on
883
case-insensitive filesystems.
886
for raw_byte in rand_bytes(num):
887
s += ALNUM[ord(raw_byte) % 36]
301
891
## TODO: We could later have path objects that remember their list
302
892
## decomposition (might be too tricksy though.)
304
894
def splitpath(p):
305
"""Turn string into list of parts.
311
>>> splitpath('a/./b')
313
>>> splitpath('a/.b')
315
>>> splitpath('a/../b')
316
Traceback (most recent call last):
318
BzrError: ("sorry, '..' not allowed in path", [])
320
assert isinstance(p, types.StringTypes)
895
"""Turn string into list of parts."""
322
896
# split on either delimiter because people might use either on
324
898
ps = re.split(r'[\\/]', p)
329
bailout("sorry, %r not allowed in path" % f)
903
raise errors.BzrError("sorry, %r not allowed in path" % f)
330
904
elif (f == '.') or (f == ''):
337
assert isinstance(p, list)
339
if (f == '..') or (f == None) or (f == ''):
340
bailout("sorry, %r not allowed in path" % f)
341
return os.path.join(*p)
344
def appendpath(p1, p2):
348
return os.path.join(p1, p2)
351
def extern_command(cmd, ignore_errors = False):
352
mutter('external command: %s' % `cmd`)
354
if not ignore_errors:
355
bailout('command failed')
913
if (f == '..') or (f is None) or (f == ''):
914
raise errors.BzrError("sorry, %r not allowed in path" % f)
918
def parent_directories(filename):
919
"""Return the list of parent directories, deepest first.
921
For example, parent_directories("a/b/c") -> ["a/b", "a"].
924
parts = splitpath(dirname(filename))
926
parents.append(joinpath(parts))
931
_extension_load_failures = []
934
def failed_to_load_extension(exception):
935
"""Handle failing to load a binary extension.
937
This should be called from the ImportError block guarding the attempt to
938
import the native extension. If this function returns, the pure-Python
939
implementation should be loaded instead::
942
>>> import bzrlib._fictional_extension_pyx
943
>>> except ImportError, e:
944
>>> bzrlib.osutils.failed_to_load_extension(e)
945
>>> import bzrlib._fictional_extension_py
947
# NB: This docstring is just an example, not a doctest, because doctest
948
# currently can't cope with the use of lazy imports in this namespace --
951
# This currently doesn't report the failure at the time it occurs, because
952
# they tend to happen very early in startup when we can't check config
953
# files etc, and also we want to report all failures but not spam the user
955
from bzrlib import trace
956
exception_str = str(exception)
957
if exception_str not in _extension_load_failures:
958
trace.mutter("failed to load compiled extension: %s" % exception_str)
959
_extension_load_failures.append(exception_str)
962
def report_extension_load_failures():
963
if not _extension_load_failures:
965
from bzrlib.config import GlobalConfig
966
if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
968
# the warnings framework should by default show this only once
969
from bzrlib.trace import warning
971
"bzr: warning: some compiled extensions could not be loaded; "
972
"see <https://answers.launchpad.net/bzr/+faq/703>")
973
# we no longer show the specific missing extensions here, because it makes
974
# the message too long and scary - see
975
# https://bugs.launchpad.net/bzr/+bug/430529
979
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
980
except ImportError, e:
981
failed_to_load_extension(e)
982
from bzrlib._chunks_to_lines_py import chunks_to_lines
986
"""Split s into lines, but without removing the newline characters."""
987
# Trivially convert a fulltext into a 'chunked' representation, and let
988
# chunks_to_lines do the heavy lifting.
989
if isinstance(s, str):
990
# chunks_to_lines only supports 8-bit strings
991
return chunks_to_lines([s])
993
return _split_lines(s)
997
"""Split s into lines, but without removing the newline characters.
999
This supports Unicode or plain string objects.
1001
lines = s.split('\n')
1002
result = [line + '\n' for line in lines[:-1]]
1004
result.append(lines[-1])
1008
def hardlinks_good():
1009
return sys.platform not in ('win32', 'cygwin', 'darwin')
1012
def link_or_copy(src, dest):
1013
"""Hardlink a file, or copy it if it can't be hardlinked."""
1014
if not hardlinks_good():
1015
shutil.copyfile(src, dest)
1019
except (OSError, IOError), e:
1020
if e.errno != errno.EXDEV:
1022
shutil.copyfile(src, dest)
1025
def delete_any(path):
1026
"""Delete a file, symlink or directory.
1028
Will delete even if readonly.
1031
_delete_file_or_dir(path)
1032
except (OSError, IOError), e:
1033
if e.errno in (errno.EPERM, errno.EACCES):
1034
# make writable and try again
1037
except (OSError, IOError):
1039
_delete_file_or_dir(path)
1044
def _delete_file_or_dir(path):
1045
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1046
# Forgiveness than Permission (EAFP) because:
1047
# - root can damage a solaris file system by using unlink,
1048
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1049
# EACCES, OSX: EPERM) when invoked on a directory.
1050
if isdir(path): # Takes care of symlinks
1057
if getattr(os, 'symlink', None) is not None:
1063
def has_hardlinks():
1064
if getattr(os, 'link', None) is not None:
1070
def host_os_dereferences_symlinks():
1071
return (has_symlinks()
1072
and sys.platform not in ('cygwin', 'win32'))
1075
def readlink(abspath):
1076
"""Return a string representing the path to which the symbolic link points.
1078
:param abspath: The link absolute unicode path.
1080
This his guaranteed to return the symbolic link in unicode in all python
1083
link = abspath.encode(_fs_enc)
1084
target = os.readlink(link)
1085
target = target.decode(_fs_enc)
1089
def contains_whitespace(s):
1090
"""True if there are any whitespace characters in s."""
1091
# string.whitespace can include '\xa0' in certain locales, because it is
1092
# considered "non-breaking-space" as part of ISO-8859-1. But it
1093
# 1) Isn't a breaking whitespace
1094
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1096
# 3) '\xa0' isn't unicode safe since it is >128.
1098
# This should *not* be a unicode set of characters in case the source
1099
# string is not a Unicode string. We can auto-up-cast the characters since
1100
# they are ascii, but we don't want to auto-up-cast the string in case it
1102
for ch in ' \t\n\r\v\f':
1109
def contains_linebreaks(s):
1110
"""True if there is any vertical whitespace in s."""
1118
def relpath(base, path):
1119
"""Return path relative to base, or raise exception.
1121
The path may be either an absolute path or a path relative to the
1122
current working directory.
1124
os.path.commonprefix (python2.4) has a bad bug that it works just
1125
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1126
avoids that problem.
1129
if len(base) < MIN_ABS_PATHLENGTH:
1130
# must have space for e.g. a drive letter
1131
raise ValueError('%r is too short to calculate a relative path'
1139
if len(head) <= len(base) and head != base:
1140
raise errors.PathNotChild(rp, base)
1143
head, tail = split(head)
1148
return pathjoin(*reversed(s))
1153
def _cicp_canonical_relpath(base, path):
1154
"""Return the canonical path relative to base.
1156
Like relpath, but on case-insensitive-case-preserving file-systems, this
1157
will return the relpath as stored on the file-system rather than in the
1158
case specified in the input string, for all existing portions of the path.
1160
This will cause O(N) behaviour if called for every path in a tree; if you
1161
have a number of paths to convert, you should use canonical_relpaths().
1163
# TODO: it should be possible to optimize this for Windows by using the
1164
# win32 API FindFiles function to look for the specified name - but using
1165
# os.listdir() still gives us the correct, platform agnostic semantics in
1168
rel = relpath(base, path)
1169
# '.' will have been turned into ''
1173
abs_base = abspath(base)
1175
_listdir = os.listdir
1177
# use an explicit iterator so we can easily consume the rest on early exit.
1178
bit_iter = iter(rel.split('/'))
1179
for bit in bit_iter:
1182
next_entries = _listdir(current)
1183
except OSError: # enoent, eperm, etc
1184
# We can't find this in the filesystem, so just append the
1186
current = pathjoin(current, bit, *list(bit_iter))
1188
for look in next_entries:
1189
if lbit == look.lower():
1190
current = pathjoin(current, look)
1193
# got to the end, nothing matched, so we just return the
1194
# non-existing bits as they were specified (the filename may be
1195
# the target of a move, for example).
1196
current = pathjoin(current, bit, *list(bit_iter))
1198
return current[len(abs_base):].lstrip('/')
1200
# XXX - TODO - we need better detection/integration of case-insensitive
1201
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1202
# filesystems), for example, so could probably benefit from the same basic
1203
# support there. For now though, only Windows and OSX get that support, and
1204
# they get it for *all* file-systems!
1205
if sys.platform in ('win32', 'darwin'):
1206
canonical_relpath = _cicp_canonical_relpath
1208
canonical_relpath = relpath
1210
def canonical_relpaths(base, paths):
1211
"""Create an iterable to canonicalize a sequence of relative paths.
1213
The intent is for this implementation to use a cache, vastly speeding
1214
up multiple transformations in the same directory.
1216
# but for now, we haven't optimized...
1217
return [canonical_relpath(base, p) for p in paths]
1219
def safe_unicode(unicode_or_utf8_string):
1220
"""Coerce unicode_or_utf8_string into unicode.
1222
If it is unicode, it is returned.
1223
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1224
wrapped in a BzrBadParameterNotUnicode exception.
1226
if isinstance(unicode_or_utf8_string, unicode):
1227
return unicode_or_utf8_string
1229
return unicode_or_utf8_string.decode('utf8')
1230
except UnicodeDecodeError:
1231
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1234
def safe_utf8(unicode_or_utf8_string):
1235
"""Coerce unicode_or_utf8_string to a utf8 string.
1237
If it is a str, it is returned.
1238
If it is Unicode, it is encoded into a utf-8 string.
1240
if isinstance(unicode_or_utf8_string, str):
1241
# TODO: jam 20070209 This is overkill, and probably has an impact on
1242
# performance if we are dealing with lots of apis that want a
1245
# Make sure it is a valid utf-8 string
1246
unicode_or_utf8_string.decode('utf-8')
1247
except UnicodeDecodeError:
1248
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1249
return unicode_or_utf8_string
1250
return unicode_or_utf8_string.encode('utf-8')
1253
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1254
' Revision id generators should be creating utf8'
1258
def safe_revision_id(unicode_or_utf8_string, warn=True):
1259
"""Revision ids should now be utf8, but at one point they were unicode.
1261
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1263
:param warn: Functions that are sanitizing user data can set warn=False
1264
:return: None or a utf8 revision id.
1266
if (unicode_or_utf8_string is None
1267
or unicode_or_utf8_string.__class__ == str):
1268
return unicode_or_utf8_string
1270
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1272
return cache_utf8.encode(unicode_or_utf8_string)
1275
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1276
' generators should be creating utf8 file ids.')
1279
def safe_file_id(unicode_or_utf8_string, warn=True):
1280
"""File ids should now be utf8, but at one point they were unicode.
1282
This is the same as safe_utf8, except it uses the cached encode functions
1283
to save a little bit of performance.
1285
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1287
:param warn: Functions that are sanitizing user data can set warn=False
1288
:return: None or a utf8 file id.
1290
if (unicode_or_utf8_string is None
1291
or unicode_or_utf8_string.__class__ == str):
1292
return unicode_or_utf8_string
1294
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1296
return cache_utf8.encode(unicode_or_utf8_string)
1299
_platform_normalizes_filenames = False
1300
if sys.platform == 'darwin':
1301
_platform_normalizes_filenames = True
1304
def normalizes_filenames():
1305
"""Return True if this platform normalizes unicode filenames.
1307
Mac OSX does, Windows/Linux do not.
1309
return _platform_normalizes_filenames
1312
def _accessible_normalized_filename(path):
1313
"""Get the unicode normalized path, and if you can access the file.
1315
On platforms where the system normalizes filenames (Mac OSX),
1316
you can access a file by any path which will normalize correctly.
1317
On platforms where the system does not normalize filenames
1318
(Windows, Linux), you have to access a file by its exact path.
1320
Internally, bzr only supports NFC normalization, since that is
1321
the standard for XML documents.
1323
So return the normalized path, and a flag indicating if the file
1324
can be accessed by that path.
1327
return unicodedata.normalize('NFC', unicode(path)), True
1330
def _inaccessible_normalized_filename(path):
1331
__doc__ = _accessible_normalized_filename.__doc__
1333
normalized = unicodedata.normalize('NFC', unicode(path))
1334
return normalized, normalized == path
1337
if _platform_normalizes_filenames:
1338
normalized_filename = _accessible_normalized_filename
1340
normalized_filename = _inaccessible_normalized_filename
1343
default_terminal_width = 80
1344
"""The default terminal width for ttys.
1346
This is defined so that higher levels can share a common fallback value when
1347
terminal_width() returns None.
1351
def terminal_width():
1352
"""Return terminal width.
1354
None is returned if the width can't established precisely.
1357
- if BZR_COLUMNS is set, returns its value
1358
- if there is no controlling terminal, returns None
1359
- if COLUMNS is set, returns its value,
1361
From there, we need to query the OS to get the size of the controlling
1365
- get termios.TIOCGWINSZ
1366
- if an error occurs or a negative value is obtained, returns None
1370
- win32utils.get_console_size() decides,
1371
- returns None on error (provided default value)
1374
# If BZR_COLUMNS is set, take it, user is always right
1376
return int(os.environ['BZR_COLUMNS'])
1377
except (KeyError, ValueError):
1380
isatty = getattr(sys.stdout, 'isatty', None)
1381
if isatty is None or not isatty():
1382
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1385
# If COLUMNS is set, take it, the terminal knows better (even inside a
1386
# given terminal, the application can decide to set COLUMNS to a lower
1387
# value (splitted screen) or a bigger value (scroll bars))
1389
return int(os.environ['COLUMNS'])
1390
except (KeyError, ValueError):
1393
width, height = _terminal_size(None, None)
1395
# Consider invalid values as meaning no width
1401
def _win32_terminal_size(width, height):
1402
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1403
return width, height
1406
def _ioctl_terminal_size(width, height):
1408
import struct, fcntl, termios
1409
s = struct.pack('HHHH', 0, 0, 0, 0)
1410
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1411
height, width = struct.unpack('HHHH', x)[0:2]
1412
except (IOError, AttributeError):
1414
return width, height
1416
_terminal_size = None
1417
"""Returns the terminal size as (width, height).
1419
:param width: Default value for width.
1420
:param height: Default value for height.
1422
This is defined specifically for each OS and query the size of the controlling
1423
terminal. If any error occurs, the provided default values should be returned.
1425
if sys.platform == 'win32':
1426
_terminal_size = _win32_terminal_size
1428
_terminal_size = _ioctl_terminal_size
1431
def _terminal_size_changed(signum, frame):
1432
"""Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1433
width, height = _terminal_size(None, None)
1434
if width is not None:
1435
os.environ['COLUMNS'] = str(width)
1437
if sys.platform == 'win32':
1438
# Martin (gz) mentioned WINDOW_BUFFER_SIZE_RECORD from ReadConsoleInput but
1439
# I've no idea how to plug that in the current design -- vila 20091216
1442
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1445
def supports_executable():
1446
return sys.platform != "win32"
1449
def supports_posix_readonly():
1450
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1452
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1453
directory controls creation/deletion, etc.
1455
And under win32, readonly means that the directory itself cannot be
1456
deleted. The contents of a readonly directory can be changed, unlike POSIX
1457
where files in readonly directories cannot be added, deleted or renamed.
1459
return sys.platform != "win32"
1462
def set_or_unset_env(env_variable, value):
1463
"""Modify the environment, setting or removing the env_variable.
1465
:param env_variable: The environment variable in question
1466
:param value: The value to set the environment to. If None, then
1467
the variable will be removed.
1468
:return: The original value of the environment variable.
1470
orig_val = os.environ.get(env_variable)
1472
if orig_val is not None:
1473
del os.environ[env_variable]
1475
if isinstance(value, unicode):
1476
value = value.encode(get_user_encoding())
1477
os.environ[env_variable] = value
1481
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1484
def check_legal_path(path):
1485
"""Check whether the supplied path is legal.
1486
This is only required on Windows, so we don't test on other platforms
1489
if sys.platform != "win32":
1491
if _validWin32PathRE.match(path) is None:
1492
raise errors.IllegalPath(path)
1495
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1497
def _is_error_enotdir(e):
1498
"""Check if this exception represents ENOTDIR.
1500
Unfortunately, python is very inconsistent about the exception
1501
here. The cases are:
1502
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1503
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1504
which is the windows error code.
1505
3) Windows, Python2.5 uses errno == EINVAL and
1506
winerror == ERROR_DIRECTORY
1508
:param e: An Exception object (expected to be OSError with an errno
1509
attribute, but we should be able to cope with anything)
1510
:return: True if this represents an ENOTDIR error. False otherwise.
1512
en = getattr(e, 'errno', None)
1513
if (en == errno.ENOTDIR
1514
or (sys.platform == 'win32'
1515
and (en == _WIN32_ERROR_DIRECTORY
1516
or (en == errno.EINVAL
1517
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1523
def walkdirs(top, prefix=""):
1524
"""Yield data about all the directories in a tree.
1526
This yields all the data about the contents of a directory at a time.
1527
After each directory has been yielded, if the caller has mutated the list
1528
to exclude some directories, they are then not descended into.
1530
The data yielded is of the form:
1531
((directory-relpath, directory-path-from-top),
1532
[(relpath, basename, kind, lstat, path-from-top), ...]),
1533
- directory-relpath is the relative path of the directory being returned
1534
with respect to top. prefix is prepended to this.
1535
- directory-path-from-root is the path including top for this directory.
1536
It is suitable for use with os functions.
1537
- relpath is the relative path within the subtree being walked.
1538
- basename is the basename of the path
1539
- kind is the kind of the file now. If unknown then the file is not
1540
present within the tree - but it may be recorded as versioned. See
1542
- lstat is the stat data *if* the file was statted.
1543
- planned, not implemented:
1544
path_from_tree_root is the path from the root of the tree.
1546
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1547
allows one to walk a subtree but get paths that are relative to a tree
1549
:return: an iterator over the dirs.
1551
#TODO there is a bit of a smell where the results of the directory-
1552
# summary in this, and the path from the root, may not agree
1553
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1554
# potentially confusing output. We should make this more robust - but
1555
# not at a speed cost. RBC 20060731
1557
_directory = _directory_kind
1558
_listdir = os.listdir
1559
_kind_from_mode = file_kind_from_stat_mode
1560
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1562
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1563
relroot, _, _, _, top = pending.pop()
1565
relprefix = relroot + u'/'
1568
top_slash = top + u'/'
1571
append = dirblock.append
1573
names = sorted(_listdir(top))
1575
if not _is_error_enotdir(e):
1579
abspath = top_slash + name
1580
statvalue = _lstat(abspath)
1581
kind = _kind_from_mode(statvalue.st_mode)
1582
append((relprefix + name, name, kind, statvalue, abspath))
1583
yield (relroot, top), dirblock
1585
# push the user specified dirs from dirblock
1586
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1589
class DirReader(object):
1590
"""An interface for reading directories."""
1592
def top_prefix_to_starting_dir(self, top, prefix=""):
1593
"""Converts top and prefix to a starting dir entry
1595
:param top: A utf8 path
1596
:param prefix: An optional utf8 path to prefix output relative paths
1598
:return: A tuple starting with prefix, and ending with the native
1601
raise NotImplementedError(self.top_prefix_to_starting_dir)
1603
def read_dir(self, prefix, top):
1604
"""Read a specific dir.
1606
:param prefix: A utf8 prefix to be preprended to the path basenames.
1607
:param top: A natively encoded path to read.
1608
:return: A list of the directories contents. Each item contains:
1609
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1611
raise NotImplementedError(self.read_dir)
1614
_selected_dir_reader = None
1617
def _walkdirs_utf8(top, prefix=""):
1618
"""Yield data about all the directories in a tree.
1620
This yields the same information as walkdirs() only each entry is yielded
1621
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1622
are returned as exact byte-strings.
1624
:return: yields a tuple of (dir_info, [file_info])
1625
dir_info is (utf8_relpath, path-from-top)
1626
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1627
if top is an absolute path, path-from-top is also an absolute path.
1628
path-from-top might be unicode or utf8, but it is the correct path to
1629
pass to os functions to affect the file in question. (such as os.lstat)
1631
global _selected_dir_reader
1632
if _selected_dir_reader is None:
1633
fs_encoding = _fs_enc.upper()
1634
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1635
# Win98 doesn't have unicode apis like FindFirstFileW
1636
# TODO: We possibly could support Win98 by falling back to the
1637
# original FindFirstFile, and using TCHAR instead of WCHAR,
1638
# but that gets a bit tricky, and requires custom compiling
1641
from bzrlib._walkdirs_win32 import Win32ReadDir
1642
_selected_dir_reader = Win32ReadDir()
1645
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1646
# ANSI_X3.4-1968 is a form of ASCII
1648
from bzrlib._readdir_pyx import UTF8DirReader
1649
_selected_dir_reader = UTF8DirReader()
1650
except ImportError, e:
1651
failed_to_load_extension(e)
1654
if _selected_dir_reader is None:
1655
# Fallback to the python version
1656
_selected_dir_reader = UnicodeDirReader()
1658
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1659
# But we don't actually uses 1-3 in pending, so set them to None
1660
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1661
read_dir = _selected_dir_reader.read_dir
1662
_directory = _directory_kind
1664
relroot, _, _, _, top = pending[-1].pop()
1667
dirblock = sorted(read_dir(relroot, top))
1668
yield (relroot, top), dirblock
1669
# push the user specified dirs from dirblock
1670
next = [d for d in reversed(dirblock) if d[2] == _directory]
1672
pending.append(next)
1675
class UnicodeDirReader(DirReader):
1676
"""A dir reader for non-utf8 file systems, which transcodes."""
1678
__slots__ = ['_utf8_encode']
1681
self._utf8_encode = codecs.getencoder('utf8')
1683
def top_prefix_to_starting_dir(self, top, prefix=""):
1684
"""See DirReader.top_prefix_to_starting_dir."""
1685
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1687
def read_dir(self, prefix, top):
1688
"""Read a single directory from a non-utf8 file system.
1690
top, and the abspath element in the output are unicode, all other paths
1691
are utf8. Local disk IO is done via unicode calls to listdir etc.
1693
This is currently the fallback code path when the filesystem encoding is
1694
not UTF-8. It may be better to implement an alternative so that we can
1695
safely handle paths that are not properly decodable in the current
1698
See DirReader.read_dir for details.
1700
_utf8_encode = self._utf8_encode
1702
_listdir = os.listdir
1703
_kind_from_mode = file_kind_from_stat_mode
1706
relprefix = prefix + '/'
1709
top_slash = top + u'/'
1712
append = dirblock.append
1713
for name in sorted(_listdir(top)):
1715
name_utf8 = _utf8_encode(name)[0]
1716
except UnicodeDecodeError:
1717
raise errors.BadFilenameEncoding(
1718
_utf8_encode(relprefix)[0] + name, _fs_enc)
1719
abspath = top_slash + name
1720
statvalue = _lstat(abspath)
1721
kind = _kind_from_mode(statvalue.st_mode)
1722
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1726
def copy_tree(from_path, to_path, handlers={}):
1727
"""Copy all of the entries in from_path into to_path.
1729
:param from_path: The base directory to copy.
1730
:param to_path: The target directory. If it does not exist, it will
1732
:param handlers: A dictionary of functions, which takes a source and
1733
destinations for files, directories, etc.
1734
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1735
'file', 'directory', and 'symlink' should always exist.
1736
If they are missing, they will be replaced with 'os.mkdir()',
1737
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1739
# Now, just copy the existing cached tree to the new location
1740
# We use a cheap trick here.
1741
# Absolute paths are prefixed with the first parameter
1742
# relative paths are prefixed with the second.
1743
# So we can get both the source and target returned
1744
# without any extra work.
1746
def copy_dir(source, dest):
1749
def copy_link(source, dest):
1750
"""Copy the contents of a symlink"""
1751
link_to = os.readlink(source)
1752
os.symlink(link_to, dest)
1754
real_handlers = {'file':shutil.copy2,
1755
'symlink':copy_link,
1756
'directory':copy_dir,
1758
real_handlers.update(handlers)
1760
if not os.path.exists(to_path):
1761
real_handlers['directory'](from_path, to_path)
1763
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1764
for relpath, name, kind, st, abspath in entries:
1765
real_handlers[kind](abspath, relpath)
1768
def path_prefix_key(path):
1769
"""Generate a prefix-order path key for path.
1771
This can be used to sort paths in the same way that walkdirs does.
1773
return (dirname(path) , path)
1776
def compare_paths_prefix_order(path_a, path_b):
1777
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1778
key_a = path_prefix_key(path_a)
1779
key_b = path_prefix_key(path_b)
1780
return cmp(key_a, key_b)
1783
_cached_user_encoding = None
1786
def get_user_encoding(use_cache=True):
1787
"""Find out what the preferred user encoding is.
1789
This is generally the encoding that is used for command line parameters
1790
and file contents. This may be different from the terminal encoding
1791
or the filesystem encoding.
1793
:param use_cache: Enable cache for detected encoding.
1794
(This parameter is turned on by default,
1795
and required only for selftesting)
1797
:return: A string defining the preferred user encoding
1799
global _cached_user_encoding
1800
if _cached_user_encoding is not None and use_cache:
1801
return _cached_user_encoding
1803
if sys.platform == 'darwin':
1804
# python locale.getpreferredencoding() always return
1805
# 'mac-roman' on darwin. That's a lie.
1806
sys.platform = 'posix'
1808
if os.environ.get('LANG', None) is None:
1809
# If LANG is not set, we end up with 'ascii', which is bad
1810
# ('mac-roman' is more than ascii), so we set a default which
1811
# will give us UTF-8 (which appears to work in all cases on
1812
# OSX). Users are still free to override LANG of course, as
1813
# long as it give us something meaningful. This work-around
1814
# *may* not be needed with python 3k and/or OSX 10.5, but will
1815
# work with them too -- vila 20080908
1816
os.environ['LANG'] = 'en_US.UTF-8'
1819
sys.platform = 'darwin'
1824
user_encoding = locale.getpreferredencoding()
1825
except locale.Error, e:
1826
sys.stderr.write('bzr: warning: %s\n'
1827
' Could not determine what text encoding to use.\n'
1828
' This error usually means your Python interpreter\n'
1829
' doesn\'t support the locale set by $LANG (%s)\n'
1830
" Continuing with ascii encoding.\n"
1831
% (e, os.environ.get('LANG')))
1832
user_encoding = 'ascii'
1834
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1835
# treat that as ASCII, and not support printing unicode characters to the
1838
# For python scripts run under vim, we get '', so also treat that as ASCII
1839
if user_encoding in (None, 'cp0', ''):
1840
user_encoding = 'ascii'
1844
codecs.lookup(user_encoding)
1846
sys.stderr.write('bzr: warning:'
1847
' unknown encoding %s.'
1848
' Continuing with ascii encoding.\n'
1851
user_encoding = 'ascii'
1854
_cached_user_encoding = user_encoding
1856
return user_encoding
1859
def get_host_name():
1860
"""Return the current unicode host name.
1862
This is meant to be used in place of socket.gethostname() because that
1863
behaves inconsistently on different platforms.
1865
if sys.platform == "win32":
1867
return win32utils.get_host_name()
1870
return socket.gethostname().decode(get_user_encoding())
1873
def recv_all(socket, bytes):
1874
"""Receive an exact number of bytes.
1876
Regular Socket.recv() may return less than the requested number of bytes,
1877
dependning on what's in the OS buffer. MSG_WAITALL is not available
1878
on all platforms, but this should work everywhere. This will return
1879
less than the requested amount if the remote end closes.
1881
This isn't optimized and is intended mostly for use in testing.
1884
while len(b) < bytes:
1885
new = until_no_eintr(socket.recv, bytes - len(b))
1892
def send_all(socket, bytes, report_activity=None):
1893
"""Send all bytes on a socket.
1895
Regular socket.sendall() can give socket error 10053 on Windows. This
1896
implementation sends no more than 64k at a time, which avoids this problem.
1898
:param report_activity: Call this as bytes are read, see
1899
Transport._report_activity
1902
for pos in xrange(0, len(bytes), chunk_size):
1903
block = bytes[pos:pos+chunk_size]
1904
if report_activity is not None:
1905
report_activity(len(block), 'write')
1906
until_no_eintr(socket.sendall, block)
1909
def dereference_path(path):
1910
"""Determine the real path to a file.
1912
All parent elements are dereferenced. But the file itself is not
1914
:param path: The original path. May be absolute or relative.
1915
:return: the real path *to* the file
1917
parent, base = os.path.split(path)
1918
# The pathjoin for '.' is a workaround for Python bug #1213894.
1919
# (initial path components aren't dereferenced)
1920
return pathjoin(realpath(pathjoin('.', parent)), base)
1923
def supports_mapi():
1924
"""Return True if we can use MAPI to launch a mail client."""
1925
return sys.platform == "win32"
1928
def resource_string(package, resource_name):
1929
"""Load a resource from a package and return it as a string.
1931
Note: Only packages that start with bzrlib are currently supported.
1933
This is designed to be a lightweight implementation of resource
1934
loading in a way which is API compatible with the same API from
1936
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1937
If and when pkg_resources becomes a standard library, this routine
1940
# Check package name is within bzrlib
1941
if package == "bzrlib":
1942
resource_relpath = resource_name
1943
elif package.startswith("bzrlib."):
1944
package = package[len("bzrlib."):].replace('.', os.sep)
1945
resource_relpath = pathjoin(package, resource_name)
1947
raise errors.BzrError('resource package %s not in bzrlib' % package)
1949
# Map the resource to a file and read its contents
1950
base = dirname(bzrlib.__file__)
1951
if getattr(sys, 'frozen', None): # bzr.exe
1952
base = abspath(pathjoin(base, '..', '..'))
1953
filename = pathjoin(base, resource_relpath)
1954
return open(filename, 'rU').read()
1957
def file_kind_from_stat_mode_thunk(mode):
1958
global file_kind_from_stat_mode
1959
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1961
from bzrlib._readdir_pyx import UTF8DirReader
1962
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1963
except ImportError, e:
1964
# This is one time where we won't warn that an extension failed to
1965
# load. The extension is never available on Windows anyway.
1966
from bzrlib._readdir_py import (
1967
_kind_from_mode as file_kind_from_stat_mode
1969
return file_kind_from_stat_mode(mode)
1970
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1973
def file_kind(f, _lstat=os.lstat):
1975
return file_kind_from_stat_mode(_lstat(f).st_mode)
1977
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1978
raise errors.NoSuchFile(f)
1982
def until_no_eintr(f, *a, **kw):
1983
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1984
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1988
except (IOError, OSError), e:
1989
if e.errno == errno.EINTR:
1993
def re_compile_checked(re_string, flags=0, where=""):
1994
"""Return a compiled re, or raise a sensible error.
1996
This should only be used when compiling user-supplied REs.
1998
:param re_string: Text form of regular expression.
1999
:param flags: eg re.IGNORECASE
2000
:param where: Message explaining to the user the context where
2001
it occurred, eg 'log search filter'.
2003
# from https://bugs.launchpad.net/bzr/+bug/251352
2005
re_obj = re.compile(re_string, flags)
2010
where = ' in ' + where
2011
# despite the name 'error' is a type
2012
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2013
% (where, re_string, e))
2016
if sys.platform == "win32":
2019
return msvcrt.getch()
2024
fd = sys.stdin.fileno()
2025
settings = termios.tcgetattr(fd)
2028
ch = sys.stdin.read(1)
2030
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2034
if sys.platform == 'linux2':
2035
def _local_concurrency():
2037
prefix = 'processor'
2038
for line in file('/proc/cpuinfo', 'rb'):
2039
if line.startswith(prefix):
2040
concurrency = int(line[line.find(':')+1:]) + 1
2042
elif sys.platform == 'darwin':
2043
def _local_concurrency():
2044
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2045
stdout=subprocess.PIPE).communicate()[0]
2046
elif sys.platform[0:7] == 'freebsd':
2047
def _local_concurrency():
2048
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2049
stdout=subprocess.PIPE).communicate()[0]
2050
elif sys.platform == 'sunos5':
2051
def _local_concurrency():
2052
return subprocess.Popen(['psrinfo', '-p',],
2053
stdout=subprocess.PIPE).communicate()[0]
2054
elif sys.platform == "win32":
2055
def _local_concurrency():
2056
# This appears to return the number of cores.
2057
return os.environ.get('NUMBER_OF_PROCESSORS')
2059
def _local_concurrency():
2064
_cached_local_concurrency = None
2066
def local_concurrency(use_cache=True):
2067
"""Return how many processes can be run concurrently.
2069
Rely on platform specific implementations and default to 1 (one) if
2070
anything goes wrong.
2072
global _cached_local_concurrency
2074
if _cached_local_concurrency is not None and use_cache:
2075
return _cached_local_concurrency
2077
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2078
if concurrency is None:
2080
concurrency = _local_concurrency()
2081
except (OSError, IOError):
2084
concurrency = int(concurrency)
2085
except (TypeError, ValueError):
2088
_cached_concurrency = concurrency
2092
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2093
"""A stream writer that doesn't decode str arguments."""
2095
def __init__(self, encode, stream, errors='strict'):
2096
codecs.StreamWriter.__init__(self, stream, errors)
2097
self.encode = encode
2099
def write(self, object):
2100
if type(object) is str:
2101
self.stream.write(object)
2103
data, _ = self.encode(object, self.errors)
2104
self.stream.write(data)