1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
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,
44
from tempfile import (
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
58
if sys.version_info < (2, 5):
59
import md5 as _mod_md5
61
import sha as _mod_sha
71
from bzrlib import symbol_versioning
74
# Cross platform wall-clock time functionality with decent resolution.
75
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
76
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
77
# synchronized with ``time.time()``, this is only meant to be used to find
78
# delta times by subtracting from another call to this function.
79
timer_func = time.time
80
if sys.platform == 'win32':
81
timer_func = time.clock
83
# On win32, O_BINARY is used to indicate the file should
84
# be opened in binary mode, rather than text mode.
85
# On other platforms, O_BINARY doesn't exist, because
86
# they always open in binary mode, so it is okay to
87
# OR with 0 on those platforms
88
O_BINARY = getattr(os, 'O_BINARY', 0)
91
def get_unicode_argv():
93
user_encoding = get_user_encoding()
94
return [a.decode(user_encoding) for a in sys.argv[1:]]
95
except UnicodeDecodeError:
96
raise errors.BzrError(("Parameter '%r' is unsupported by the current "
100
def make_readonly(filename):
101
"""Make a filename read-only."""
102
mod = os.lstat(filename).st_mode
103
if not stat.S_ISLNK(mod):
105
os.chmod(filename, mod)
108
def make_writable(filename):
109
mod = os.lstat(filename).st_mode
110
if not stat.S_ISLNK(mod):
112
os.chmod(filename, mod)
115
def minimum_path_selection(paths):
116
"""Return the smallset subset of paths which are outside paths.
118
:param paths: A container (and hence not None) of paths.
119
:return: A set of paths sufficient to include everything in paths via
120
is_inside, drawn from the paths parameter.
126
return path.split('/')
127
sorted_paths = sorted(list(paths), key=sort_key)
129
search_paths = [sorted_paths[0]]
130
for path in sorted_paths[1:]:
131
if not is_inside(search_paths[-1], path):
132
# This path is unique, add it
133
search_paths.append(path)
135
return set(search_paths)
142
"""Return a quoted filename filename
144
This previously used backslash quoting, but that works poorly on
146
# TODO: I'm not really sure this is the best format either.x
148
if _QUOTE_RE is None:
149
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
151
if _QUOTE_RE.search(f):
157
_directory_kind = 'directory'
160
"""Return the current umask"""
161
# Assume that people aren't messing with the umask while running
162
# XXX: This is not thread safe, but there is no way to get the
163
# umask without setting it
171
_directory_kind: "/",
173
'tree-reference': '+',
177
def kind_marker(kind):
179
return _kind_marker_map[kind]
181
raise errors.BzrError('invalid file kind %r' % kind)
184
lexists = getattr(os.path, 'lexists', None)
188
stat = getattr(os, 'lstat', os.stat)
192
if e.errno == errno.ENOENT:
195
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
198
def fancy_rename(old, new, rename_func, unlink_func):
199
"""A fancy rename, when you don't have atomic rename.
201
:param old: The old path, to rename from
202
:param new: The new path, to rename to
203
:param rename_func: The potentially non-atomic rename function
204
:param unlink_func: A way to delete the target file if the full rename succeeds
207
# sftp rename doesn't allow overwriting, so play tricks:
208
base = os.path.basename(new)
209
dirname = os.path.dirname(new)
210
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
211
tmp_name = pathjoin(dirname, tmp_name)
213
# Rename the file out of the way, but keep track if it didn't exist
214
# We don't want to grab just any exception
215
# something like EACCES should prevent us from continuing
216
# The downside is that the rename_func has to throw an exception
217
# with an errno = ENOENT, or NoSuchFile
220
rename_func(new, tmp_name)
221
except (errors.NoSuchFile,), e:
224
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
225
# function raises an IOError with errno is None when a rename fails.
226
# This then gets caught here.
227
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
230
if (getattr(e, 'errno', None) is None
231
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
240
# This may throw an exception, in which case success will
242
rename_func(old, new)
244
except (IOError, OSError), e:
245
# source and target may be aliases of each other (e.g. on a
246
# case-insensitive filesystem), so we may have accidentally renamed
247
# source by when we tried to rename target
248
failure_exc = sys.exc_info()
249
if (file_existed and e.errno in (None, errno.ENOENT)
250
and old.lower() == new.lower()):
251
# source and target are the same file on a case-insensitive
252
# filesystem, so we don't generate an exception
256
# If the file used to exist, rename it back into place
257
# otherwise just delete it from the tmp location
259
unlink_func(tmp_name)
261
rename_func(tmp_name, new)
262
if failure_exc is not None:
263
raise failure_exc[0], failure_exc[1], failure_exc[2]
266
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
267
# choke on a Unicode string containing a relative path if
268
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
270
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
271
def _posix_abspath(path):
272
# jam 20060426 rather than encoding to fsencoding
273
# copy posixpath.abspath, but use os.getcwdu instead
274
if not posixpath.isabs(path):
275
path = posixpath.join(getcwd(), path)
276
return posixpath.normpath(path)
279
def _posix_realpath(path):
280
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
283
def _win32_fixdrive(path):
284
"""Force drive letters to be consistent.
286
win32 is inconsistent whether it returns lower or upper case
287
and even if it was consistent the user might type the other
288
so we force it to uppercase
289
running python.exe under cmd.exe return capital C:\\
290
running win32 python inside a cygwin shell returns lowercase c:\\
292
drive, path = _nt_splitdrive(path)
293
return drive.upper() + path
296
def _win32_abspath(path):
297
# Real _nt_abspath doesn't have a problem with a unicode cwd
298
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
301
def _win98_abspath(path):
302
"""Return the absolute version of a path.
303
Windows 98 safe implementation (python reimplementation
304
of Win32 API function GetFullPathNameW)
309
# \\HOST\path => //HOST/path
310
# //HOST/path => //HOST/path
311
# path => C:/cwd/path
314
# check for absolute path
315
drive = _nt_splitdrive(path)[0]
316
if drive == '' and path[:2] not in('//','\\\\'):
318
# we cannot simply os.path.join cwd and path
319
# because os.path.join('C:','/path') produce '/path'
320
# and this is incorrect
321
if path[:1] in ('/','\\'):
322
cwd = _nt_splitdrive(cwd)[0]
324
path = cwd + '\\' + path
325
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
328
def _win32_realpath(path):
329
# Real _nt_realpath doesn't have a problem with a unicode cwd
330
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
333
def _win32_pathjoin(*args):
334
return _nt_join(*args).replace('\\', '/')
337
def _win32_normpath(path):
338
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
342
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
345
def _win32_mkdtemp(*args, **kwargs):
346
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
349
def _win32_rename(old, new):
350
"""We expect to be able to atomically replace 'new' with old.
352
On win32, if new exists, it must be moved out of the way first,
356
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
358
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
359
# If we try to rename a non-existant file onto cwd, we get
360
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
361
# if the old path doesn't exist, sometimes we get EACCES
362
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
368
return unicodedata.normalize('NFC', os.getcwdu())
371
# Default is to just use the python builtins, but these can be rebound on
372
# particular platforms.
373
abspath = _posix_abspath
374
realpath = _posix_realpath
375
pathjoin = os.path.join
376
normpath = os.path.normpath
379
dirname = os.path.dirname
380
basename = os.path.basename
381
split = os.path.split
382
splitext = os.path.splitext
383
# These were already imported into local scope
384
# mkdtemp = tempfile.mkdtemp
385
# rmtree = shutil.rmtree
387
MIN_ABS_PATHLENGTH = 1
390
if sys.platform == 'win32':
391
if win32utils.winver == 'Windows 98':
392
abspath = _win98_abspath
394
abspath = _win32_abspath
395
realpath = _win32_realpath
396
pathjoin = _win32_pathjoin
397
normpath = _win32_normpath
398
getcwd = _win32_getcwd
399
mkdtemp = _win32_mkdtemp
400
rename = _win32_rename
402
MIN_ABS_PATHLENGTH = 3
404
def _win32_delete_readonly(function, path, excinfo):
405
"""Error handler for shutil.rmtree function [for win32]
406
Helps to remove files and dirs marked as read-only.
408
exception = excinfo[1]
409
if function in (os.remove, os.rmdir) \
410
and isinstance(exception, OSError) \
411
and exception.errno == errno.EACCES:
417
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
418
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
419
return shutil.rmtree(path, ignore_errors, onerror)
421
f = win32utils.get_unicode_argv # special function or None
425
elif sys.platform == 'darwin':
429
def get_terminal_encoding():
430
"""Find the best encoding for printing to the screen.
432
This attempts to check both sys.stdout and sys.stdin to see
433
what encoding they are in, and if that fails it falls back to
434
osutils.get_user_encoding().
435
The problem is that on Windows, locale.getpreferredencoding()
436
is not the same encoding as that used by the console:
437
http://mail.python.org/pipermail/python-list/2003-May/162357.html
439
On my standard US Windows XP, the preferred encoding is
440
cp1252, but the console is cp437
442
from bzrlib.trace import mutter
443
output_encoding = getattr(sys.stdout, 'encoding', None)
444
if not output_encoding:
445
input_encoding = getattr(sys.stdin, 'encoding', None)
446
if not input_encoding:
447
output_encoding = get_user_encoding()
448
mutter('encoding stdout as osutils.get_user_encoding() %r',
451
output_encoding = input_encoding
452
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
454
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
455
if output_encoding == 'cp0':
456
# invalid encoding (cp0 means 'no codepage' on Windows)
457
output_encoding = get_user_encoding()
458
mutter('cp0 is invalid encoding.'
459
' encoding stdout as osutils.get_user_encoding() %r',
463
codecs.lookup(output_encoding)
465
sys.stderr.write('bzr: warning:'
466
' unknown terminal encoding %s.\n'
467
' Using encoding %s instead.\n'
468
% (output_encoding, get_user_encoding())
470
output_encoding = get_user_encoding()
472
return output_encoding
475
def normalizepath(f):
476
if getattr(os.path, 'realpath', None) is not None:
480
[p,e] = os.path.split(f)
481
if e == "" or e == "." or e == "..":
484
return pathjoin(F(p), e)
488
"""True if f is an accessible directory."""
490
return S_ISDIR(os.lstat(f)[ST_MODE])
496
"""True if f is a regular file."""
498
return S_ISREG(os.lstat(f)[ST_MODE])
503
"""True if f is a symlink."""
505
return S_ISLNK(os.lstat(f)[ST_MODE])
509
def is_inside(dir, fname):
510
"""True if fname is inside dir.
512
The parameters should typically be passed to osutils.normpath first, so
513
that . and .. and repeated slashes are eliminated, and the separators
514
are canonical for the platform.
516
The empty string as a dir name is taken as top-of-tree and matches
519
# XXX: Most callers of this can actually do something smarter by
520
# looking at the inventory
530
return fname.startswith(dir)
533
def is_inside_any(dir_list, fname):
534
"""True if fname is inside any of given dirs."""
535
for dirname in dir_list:
536
if is_inside(dirname, fname):
541
def is_inside_or_parent_of_any(dir_list, fname):
542
"""True if fname is a child or a parent of any of the given files."""
543
for dirname in dir_list:
544
if is_inside(dirname, fname) or is_inside(fname, dirname):
549
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
550
report_activity=None, direction='read'):
551
"""Copy contents of one file to another.
553
The read_length can either be -1 to read to end-of-file (EOF) or
554
it can specify the maximum number of bytes to read.
556
The buff_size represents the maximum size for each read operation
557
performed on from_file.
559
:param report_activity: Call this as bytes are read, see
560
Transport._report_activity
561
:param direction: Will be passed to report_activity
563
:return: The number of bytes copied.
567
# read specified number of bytes
569
while read_length > 0:
570
num_bytes_to_read = min(read_length, buff_size)
572
block = from_file.read(num_bytes_to_read)
576
if report_activity is not None:
577
report_activity(len(block), direction)
580
actual_bytes_read = len(block)
581
read_length -= actual_bytes_read
582
length += actual_bytes_read
586
block = from_file.read(buff_size)
590
if report_activity is not None:
591
report_activity(len(block), direction)
597
def pump_string_file(bytes, file_handle, segment_size=None):
598
"""Write bytes to file_handle in many smaller writes.
600
:param bytes: The string to write.
601
:param file_handle: The file to write to.
603
# Write data in chunks rather than all at once, because very large
604
# writes fail on some platforms (e.g. Windows with SMB mounted
607
segment_size = 5242880 # 5MB
608
segments = range(len(bytes) / segment_size + 1)
609
write = file_handle.write
610
for segment_index in segments:
611
segment = buffer(bytes, segment_index * segment_size, segment_size)
615
def file_iterator(input_file, readsize=32768):
617
b = input_file.read(readsize)
624
"""Calculate the hexdigest of an open file.
626
The file cursor should be already at the start.
638
def size_sha_file(f):
639
"""Calculate the size and hexdigest of an open file.
641
The file cursor should be already at the start and
642
the caller is responsible for closing the file afterwards.
653
return size, s.hexdigest()
656
def sha_file_by_name(fname):
657
"""Calculate the SHA1 of a file by reading the full text"""
659
f = os.open(fname, os.O_RDONLY | O_BINARY)
662
b = os.read(f, 1<<16)
670
def sha_strings(strings, _factory=sha):
671
"""Return the sha-1 of concatenation of strings"""
673
map(s.update, strings)
677
def sha_string(f, _factory=sha):
678
return _factory(f).hexdigest()
681
def fingerprint_file(f):
683
return {'size': len(b),
684
'sha1': sha(b).hexdigest()}
687
def compare_files(a, b):
688
"""Returns true if equal in contents"""
699
def local_time_offset(t=None):
700
"""Return offset of local zone from GMT, either at present or at time t."""
703
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
704
return offset.days * 86400 + offset.seconds
706
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
707
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
710
def format_date(t, offset=0, timezone='original', date_fmt=None,
712
"""Return a formatted date string.
714
:param t: Seconds since the epoch.
715
:param offset: Timezone offset in seconds east of utc.
716
:param timezone: How to display the time: 'utc', 'original' for the
717
timezone specified by offset, or 'local' for the process's current
719
:param date_fmt: strftime format.
720
:param show_offset: Whether to append the timezone.
722
(date_fmt, tt, offset_str) = \
723
_format_date(t, offset, timezone, date_fmt, show_offset)
724
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
725
date_str = time.strftime(date_fmt, tt)
726
return date_str + offset_str
729
# Cache of formatted offset strings
733
def format_date_with_offset_in_original_timezone(t, offset=0,
734
_cache=_offset_cache):
735
"""Return a formatted date string in the original timezone.
737
This routine may be faster then format_date.
739
:param t: Seconds since the epoch.
740
:param offset: Timezone offset in seconds east of utc.
744
tt = time.gmtime(t + offset)
745
date_fmt = _default_format_by_weekday_num[tt[6]]
746
date_str = time.strftime(date_fmt, tt)
747
offset_str = _cache.get(offset, None)
748
if offset_str is None:
749
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
750
_cache[offset] = offset_str
751
return date_str + offset_str
754
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
756
"""Return an unicode date string formatted according to the current locale.
758
:param t: Seconds since the epoch.
759
:param offset: Timezone offset in seconds east of utc.
760
:param timezone: How to display the time: 'utc', 'original' for the
761
timezone specified by offset, or 'local' for the process's current
763
:param date_fmt: strftime format.
764
:param show_offset: Whether to append the timezone.
766
(date_fmt, tt, offset_str) = \
767
_format_date(t, offset, timezone, date_fmt, show_offset)
768
date_str = time.strftime(date_fmt, tt)
769
if not isinstance(date_str, unicode):
770
date_str = date_str.decode(get_user_encoding(), 'replace')
771
return date_str + offset_str
774
def _format_date(t, offset, timezone, date_fmt, show_offset):
775
if timezone == 'utc':
778
elif timezone == 'original':
781
tt = time.gmtime(t + offset)
782
elif timezone == 'local':
783
tt = time.localtime(t)
784
offset = local_time_offset(t)
786
raise errors.UnsupportedTimezoneFormat(timezone)
788
date_fmt = "%a %Y-%m-%d %H:%M:%S"
790
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
793
return (date_fmt, tt, offset_str)
796
def compact_date(when):
797
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
800
def format_delta(delta):
801
"""Get a nice looking string for a time delta.
803
:param delta: The time difference in seconds, can be positive or negative.
804
positive indicates time in the past, negative indicates time in the
805
future. (usually time.time() - stored_time)
806
:return: String formatted to show approximate resolution
812
direction = 'in the future'
816
if seconds < 90: # print seconds up to 90 seconds
818
return '%d second %s' % (seconds, direction,)
820
return '%d seconds %s' % (seconds, direction)
822
minutes = int(seconds / 60)
823
seconds -= 60 * minutes
828
if minutes < 90: # print minutes, seconds up to 90 minutes
830
return '%d minute, %d second%s %s' % (
831
minutes, seconds, plural_seconds, direction)
833
return '%d minutes, %d second%s %s' % (
834
minutes, seconds, plural_seconds, direction)
836
hours = int(minutes / 60)
837
minutes -= 60 * hours
844
return '%d hour, %d minute%s %s' % (hours, minutes,
845
plural_minutes, direction)
846
return '%d hours, %d minute%s %s' % (hours, minutes,
847
plural_minutes, direction)
850
"""Return size of given open file."""
851
return os.fstat(f.fileno())[ST_SIZE]
854
# Define rand_bytes based on platform.
856
# Python 2.4 and later have os.urandom,
857
# but it doesn't work on some arches
859
rand_bytes = os.urandom
860
except (NotImplementedError, AttributeError):
861
# If python doesn't have os.urandom, or it doesn't work,
862
# then try to first pull random data from /dev/urandom
864
rand_bytes = file('/dev/urandom', 'rb').read
865
# Otherwise, use this hack as a last resort
866
except (IOError, OSError):
867
# not well seeded, but better than nothing
872
s += chr(random.randint(0, 255))
877
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
879
"""Return a random string of num alphanumeric characters
881
The result only contains lowercase chars because it may be used on
882
case-insensitive filesystems.
885
for raw_byte in rand_bytes(num):
886
s += ALNUM[ord(raw_byte) % 36]
890
## TODO: We could later have path objects that remember their list
891
## decomposition (might be too tricksy though.)
894
"""Turn string into list of parts."""
895
# split on either delimiter because people might use either on
897
ps = re.split(r'[\\/]', p)
902
raise errors.BzrError("sorry, %r not allowed in path" % f)
903
elif (f == '.') or (f == ''):
912
if (f == '..') or (f is None) or (f == ''):
913
raise errors.BzrError("sorry, %r not allowed in path" % f)
917
def parent_directories(filename):
918
"""Return the list of parent directories, deepest first.
920
For example, parent_directories("a/b/c") -> ["a/b", "a"].
923
parts = splitpath(dirname(filename))
925
parents.append(joinpath(parts))
930
_extension_load_failures = []
933
def failed_to_load_extension(exception):
934
"""Handle failing to load a binary extension.
936
This should be called from the ImportError block guarding the attempt to
937
import the native extension. If this function returns, the pure-Python
938
implementation should be loaded instead::
941
>>> import bzrlib._fictional_extension_pyx
942
>>> except ImportError, e:
943
>>> bzrlib.osutils.failed_to_load_extension(e)
944
>>> import bzrlib._fictional_extension_py
946
# NB: This docstring is just an example, not a doctest, because doctest
947
# currently can't cope with the use of lazy imports in this namespace --
950
# This currently doesn't report the failure at the time it occurs, because
951
# they tend to happen very early in startup when we can't check config
952
# files etc, and also we want to report all failures but not spam the user
954
from bzrlib import trace
955
exception_str = str(exception)
956
if exception_str not in _extension_load_failures:
957
trace.mutter("failed to load compiled extension: %s" % exception_str)
958
_extension_load_failures.append(exception_str)
961
def report_extension_load_failures():
962
if not _extension_load_failures:
964
from bzrlib.config import GlobalConfig
965
if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
967
# the warnings framework should by default show this only once
968
from bzrlib.trace import warning
970
"bzr: warning: some compiled extensions could not be loaded; "
971
"see <https://answers.launchpad.net/bzr/+faq/703>")
972
# we no longer show the specific missing extensions here, because it makes
973
# the message too long and scary - see
974
# https://bugs.launchpad.net/bzr/+bug/430529
978
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
979
except ImportError, e:
980
failed_to_load_extension(e)
981
from bzrlib._chunks_to_lines_py import chunks_to_lines
985
"""Split s into lines, but without removing the newline characters."""
986
# Trivially convert a fulltext into a 'chunked' representation, and let
987
# chunks_to_lines do the heavy lifting.
988
if isinstance(s, str):
989
# chunks_to_lines only supports 8-bit strings
990
return chunks_to_lines([s])
992
return _split_lines(s)
996
"""Split s into lines, but without removing the newline characters.
998
This supports Unicode or plain string objects.
1000
lines = s.split('\n')
1001
result = [line + '\n' for line in lines[:-1]]
1003
result.append(lines[-1])
1007
def hardlinks_good():
1008
return sys.platform not in ('win32', 'cygwin', 'darwin')
1011
def link_or_copy(src, dest):
1012
"""Hardlink a file, or copy it if it can't be hardlinked."""
1013
if not hardlinks_good():
1014
shutil.copyfile(src, dest)
1018
except (OSError, IOError), e:
1019
if e.errno != errno.EXDEV:
1021
shutil.copyfile(src, dest)
1024
def delete_any(path):
1025
"""Delete a file, symlink or directory.
1027
Will delete even if readonly.
1030
_delete_file_or_dir(path)
1031
except (OSError, IOError), e:
1032
if e.errno in (errno.EPERM, errno.EACCES):
1033
# make writable and try again
1036
except (OSError, IOError):
1038
_delete_file_or_dir(path)
1043
def _delete_file_or_dir(path):
1044
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1045
# Forgiveness than Permission (EAFP) because:
1046
# - root can damage a solaris file system by using unlink,
1047
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1048
# EACCES, OSX: EPERM) when invoked on a directory.
1049
if isdir(path): # Takes care of symlinks
1056
if getattr(os, 'symlink', None) is not None:
1062
def has_hardlinks():
1063
if getattr(os, 'link', None) is not None:
1069
def host_os_dereferences_symlinks():
1070
return (has_symlinks()
1071
and sys.platform not in ('cygwin', 'win32'))
1074
def readlink(abspath):
1075
"""Return a string representing the path to which the symbolic link points.
1077
:param abspath: The link absolute unicode path.
1079
This his guaranteed to return the symbolic link in unicode in all python
1082
link = abspath.encode(_fs_enc)
1083
target = os.readlink(link)
1084
target = target.decode(_fs_enc)
1088
def contains_whitespace(s):
1089
"""True if there are any whitespace characters in s."""
1090
# string.whitespace can include '\xa0' in certain locales, because it is
1091
# considered "non-breaking-space" as part of ISO-8859-1. But it
1092
# 1) Isn't a breaking whitespace
1093
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1095
# 3) '\xa0' isn't unicode safe since it is >128.
1097
# This should *not* be a unicode set of characters in case the source
1098
# string is not a Unicode string. We can auto-up-cast the characters since
1099
# they are ascii, but we don't want to auto-up-cast the string in case it
1101
for ch in ' \t\n\r\v\f':
1108
def contains_linebreaks(s):
1109
"""True if there is any vertical whitespace in s."""
1117
def relpath(base, path):
1118
"""Return path relative to base, or raise exception.
1120
The path may be either an absolute path or a path relative to the
1121
current working directory.
1123
os.path.commonprefix (python2.4) has a bad bug that it works just
1124
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1125
avoids that problem.
1128
if len(base) < MIN_ABS_PATHLENGTH:
1129
# must have space for e.g. a drive letter
1130
raise ValueError('%r is too short to calculate a relative path'
1138
if len(head) <= len(base) and head != base:
1139
raise errors.PathNotChild(rp, base)
1142
head, tail = split(head)
1147
return pathjoin(*reversed(s))
1152
def _cicp_canonical_relpath(base, path):
1153
"""Return the canonical path relative to base.
1155
Like relpath, but on case-insensitive-case-preserving file-systems, this
1156
will return the relpath as stored on the file-system rather than in the
1157
case specified in the input string, for all existing portions of the path.
1159
This will cause O(N) behaviour if called for every path in a tree; if you
1160
have a number of paths to convert, you should use canonical_relpaths().
1162
# TODO: it should be possible to optimize this for Windows by using the
1163
# win32 API FindFiles function to look for the specified name - but using
1164
# os.listdir() still gives us the correct, platform agnostic semantics in
1167
rel = relpath(base, path)
1168
# '.' will have been turned into ''
1172
abs_base = abspath(base)
1174
_listdir = os.listdir
1176
# use an explicit iterator so we can easily consume the rest on early exit.
1177
bit_iter = iter(rel.split('/'))
1178
for bit in bit_iter:
1181
next_entries = _listdir(current)
1182
except OSError: # enoent, eperm, etc
1183
# We can't find this in the filesystem, so just append the
1185
current = pathjoin(current, bit, *list(bit_iter))
1187
for look in next_entries:
1188
if lbit == look.lower():
1189
current = pathjoin(current, look)
1192
# got to the end, nothing matched, so we just return the
1193
# non-existing bits as they were specified (the filename may be
1194
# the target of a move, for example).
1195
current = pathjoin(current, bit, *list(bit_iter))
1197
return current[len(abs_base):].lstrip('/')
1199
# XXX - TODO - we need better detection/integration of case-insensitive
1200
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1201
# filesystems), for example, so could probably benefit from the same basic
1202
# support there. For now though, only Windows and OSX get that support, and
1203
# they get it for *all* file-systems!
1204
if sys.platform in ('win32', 'darwin'):
1205
canonical_relpath = _cicp_canonical_relpath
1207
canonical_relpath = relpath
1209
def canonical_relpaths(base, paths):
1210
"""Create an iterable to canonicalize a sequence of relative paths.
1212
The intent is for this implementation to use a cache, vastly speeding
1213
up multiple transformations in the same directory.
1215
# but for now, we haven't optimized...
1216
return [canonical_relpath(base, p) for p in paths]
1218
def safe_unicode(unicode_or_utf8_string):
1219
"""Coerce unicode_or_utf8_string into unicode.
1221
If it is unicode, it is returned.
1222
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1223
wrapped in a BzrBadParameterNotUnicode exception.
1225
if isinstance(unicode_or_utf8_string, unicode):
1226
return unicode_or_utf8_string
1228
return unicode_or_utf8_string.decode('utf8')
1229
except UnicodeDecodeError:
1230
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1233
def safe_utf8(unicode_or_utf8_string):
1234
"""Coerce unicode_or_utf8_string to a utf8 string.
1236
If it is a str, it is returned.
1237
If it is Unicode, it is encoded into a utf-8 string.
1239
if isinstance(unicode_or_utf8_string, str):
1240
# TODO: jam 20070209 This is overkill, and probably has an impact on
1241
# performance if we are dealing with lots of apis that want a
1244
# Make sure it is a valid utf-8 string
1245
unicode_or_utf8_string.decode('utf-8')
1246
except UnicodeDecodeError:
1247
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1248
return unicode_or_utf8_string
1249
return unicode_or_utf8_string.encode('utf-8')
1252
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1253
' Revision id generators should be creating utf8'
1257
def safe_revision_id(unicode_or_utf8_string, warn=True):
1258
"""Revision ids should now be utf8, but at one point they were unicode.
1260
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1262
:param warn: Functions that are sanitizing user data can set warn=False
1263
:return: None or a utf8 revision id.
1265
if (unicode_or_utf8_string is None
1266
or unicode_or_utf8_string.__class__ == str):
1267
return unicode_or_utf8_string
1269
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1271
return cache_utf8.encode(unicode_or_utf8_string)
1274
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1275
' generators should be creating utf8 file ids.')
1278
def safe_file_id(unicode_or_utf8_string, warn=True):
1279
"""File ids should now be utf8, but at one point they were unicode.
1281
This is the same as safe_utf8, except it uses the cached encode functions
1282
to save a little bit of performance.
1284
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1286
:param warn: Functions that are sanitizing user data can set warn=False
1287
:return: None or a utf8 file id.
1289
if (unicode_or_utf8_string is None
1290
or unicode_or_utf8_string.__class__ == str):
1291
return unicode_or_utf8_string
1293
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1295
return cache_utf8.encode(unicode_or_utf8_string)
1298
_platform_normalizes_filenames = False
1299
if sys.platform == 'darwin':
1300
_platform_normalizes_filenames = True
1303
def normalizes_filenames():
1304
"""Return True if this platform normalizes unicode filenames.
1306
Mac OSX does, Windows/Linux do not.
1308
return _platform_normalizes_filenames
1311
def _accessible_normalized_filename(path):
1312
"""Get the unicode normalized path, and if you can access the file.
1314
On platforms where the system normalizes filenames (Mac OSX),
1315
you can access a file by any path which will normalize correctly.
1316
On platforms where the system does not normalize filenames
1317
(Windows, Linux), you have to access a file by its exact path.
1319
Internally, bzr only supports NFC normalization, since that is
1320
the standard for XML documents.
1322
So return the normalized path, and a flag indicating if the file
1323
can be accessed by that path.
1326
return unicodedata.normalize('NFC', unicode(path)), True
1329
def _inaccessible_normalized_filename(path):
1330
__doc__ = _accessible_normalized_filename.__doc__
1332
normalized = unicodedata.normalize('NFC', unicode(path))
1333
return normalized, normalized == path
1336
if _platform_normalizes_filenames:
1337
normalized_filename = _accessible_normalized_filename
1339
normalized_filename = _inaccessible_normalized_filename
1342
default_terminal_width = 80
1343
"""The default terminal width for ttys.
1345
This is defined so that higher levels can share a common fallback value when
1346
terminal_width() returns None.
1350
def terminal_width():
1351
"""Return terminal width.
1353
None is returned if the width can't established precisely.
1356
- if BZR_COLUMNS is set, returns its value
1357
- if there is no controlling terminal, returns None
1358
- if COLUMNS is set, returns its value,
1360
From there, we need to query the OS to get the size of the controlling
1364
- get termios.TIOCGWINSZ
1365
- if an error occurs or a negative value is obtained, returns None
1369
- win32utils.get_console_size() decides,
1370
- returns None on error (provided default value)
1373
# If BZR_COLUMNS is set, take it, user is always right
1375
return int(os.environ['BZR_COLUMNS'])
1376
except (KeyError, ValueError):
1379
isatty = getattr(sys.stdout, 'isatty', None)
1380
if isatty is None or not isatty():
1381
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1384
# If COLUMNS is set, take it, the terminal knows better (even inside a
1385
# given terminal, the application can decide to set COLUMNS to a lower
1386
# value (splitted screen) or a bigger value (scroll bars))
1388
return int(os.environ['COLUMNS'])
1389
except (KeyError, ValueError):
1392
width, height = _terminal_size(None, None)
1394
# Consider invalid values as meaning no width
1400
def _win32_terminal_size(width, height):
1401
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1402
return width, height
1405
def _ioctl_terminal_size(width, height):
1407
import struct, fcntl, termios
1408
s = struct.pack('HHHH', 0, 0, 0, 0)
1409
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1410
height, width = struct.unpack('HHHH', x)[0:2]
1411
except (IOError, AttributeError):
1413
return width, height
1415
_terminal_size = None
1416
"""Returns the terminal size as (width, height).
1418
:param width: Default value for width.
1419
:param height: Default value for height.
1421
This is defined specifically for each OS and query the size of the controlling
1422
terminal. If any error occurs, the provided default values should be returned.
1424
if sys.platform == 'win32':
1425
_terminal_size = _win32_terminal_size
1427
_terminal_size = _ioctl_terminal_size
1430
def supports_executable():
1431
return sys.platform != "win32"
1434
def supports_posix_readonly():
1435
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1437
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1438
directory controls creation/deletion, etc.
1440
And under win32, readonly means that the directory itself cannot be
1441
deleted. The contents of a readonly directory can be changed, unlike POSIX
1442
where files in readonly directories cannot be added, deleted or renamed.
1444
return sys.platform != "win32"
1447
def set_or_unset_env(env_variable, value):
1448
"""Modify the environment, setting or removing the env_variable.
1450
:param env_variable: The environment variable in question
1451
:param value: The value to set the environment to. If None, then
1452
the variable will be removed.
1453
:return: The original value of the environment variable.
1455
orig_val = os.environ.get(env_variable)
1457
if orig_val is not None:
1458
del os.environ[env_variable]
1460
if isinstance(value, unicode):
1461
value = value.encode(get_user_encoding())
1462
os.environ[env_variable] = value
1466
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1469
def check_legal_path(path):
1470
"""Check whether the supplied path is legal.
1471
This is only required on Windows, so we don't test on other platforms
1474
if sys.platform != "win32":
1476
if _validWin32PathRE.match(path) is None:
1477
raise errors.IllegalPath(path)
1480
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1482
def _is_error_enotdir(e):
1483
"""Check if this exception represents ENOTDIR.
1485
Unfortunately, python is very inconsistent about the exception
1486
here. The cases are:
1487
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1488
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1489
which is the windows error code.
1490
3) Windows, Python2.5 uses errno == EINVAL and
1491
winerror == ERROR_DIRECTORY
1493
:param e: An Exception object (expected to be OSError with an errno
1494
attribute, but we should be able to cope with anything)
1495
:return: True if this represents an ENOTDIR error. False otherwise.
1497
en = getattr(e, 'errno', None)
1498
if (en == errno.ENOTDIR
1499
or (sys.platform == 'win32'
1500
and (en == _WIN32_ERROR_DIRECTORY
1501
or (en == errno.EINVAL
1502
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1508
def walkdirs(top, prefix=""):
1509
"""Yield data about all the directories in a tree.
1511
This yields all the data about the contents of a directory at a time.
1512
After each directory has been yielded, if the caller has mutated the list
1513
to exclude some directories, they are then not descended into.
1515
The data yielded is of the form:
1516
((directory-relpath, directory-path-from-top),
1517
[(relpath, basename, kind, lstat, path-from-top), ...]),
1518
- directory-relpath is the relative path of the directory being returned
1519
with respect to top. prefix is prepended to this.
1520
- directory-path-from-root is the path including top for this directory.
1521
It is suitable for use with os functions.
1522
- relpath is the relative path within the subtree being walked.
1523
- basename is the basename of the path
1524
- kind is the kind of the file now. If unknown then the file is not
1525
present within the tree - but it may be recorded as versioned. See
1527
- lstat is the stat data *if* the file was statted.
1528
- planned, not implemented:
1529
path_from_tree_root is the path from the root of the tree.
1531
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1532
allows one to walk a subtree but get paths that are relative to a tree
1534
:return: an iterator over the dirs.
1536
#TODO there is a bit of a smell where the results of the directory-
1537
# summary in this, and the path from the root, may not agree
1538
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1539
# potentially confusing output. We should make this more robust - but
1540
# not at a speed cost. RBC 20060731
1542
_directory = _directory_kind
1543
_listdir = os.listdir
1544
_kind_from_mode = file_kind_from_stat_mode
1545
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1547
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1548
relroot, _, _, _, top = pending.pop()
1550
relprefix = relroot + u'/'
1553
top_slash = top + u'/'
1556
append = dirblock.append
1558
names = sorted(_listdir(top))
1560
if not _is_error_enotdir(e):
1564
abspath = top_slash + name
1565
statvalue = _lstat(abspath)
1566
kind = _kind_from_mode(statvalue.st_mode)
1567
append((relprefix + name, name, kind, statvalue, abspath))
1568
yield (relroot, top), dirblock
1570
# push the user specified dirs from dirblock
1571
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1574
class DirReader(object):
1575
"""An interface for reading directories."""
1577
def top_prefix_to_starting_dir(self, top, prefix=""):
1578
"""Converts top and prefix to a starting dir entry
1580
:param top: A utf8 path
1581
:param prefix: An optional utf8 path to prefix output relative paths
1583
:return: A tuple starting with prefix, and ending with the native
1586
raise NotImplementedError(self.top_prefix_to_starting_dir)
1588
def read_dir(self, prefix, top):
1589
"""Read a specific dir.
1591
:param prefix: A utf8 prefix to be preprended to the path basenames.
1592
:param top: A natively encoded path to read.
1593
:return: A list of the directories contents. Each item contains:
1594
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1596
raise NotImplementedError(self.read_dir)
1599
_selected_dir_reader = None
1602
def _walkdirs_utf8(top, prefix=""):
1603
"""Yield data about all the directories in a tree.
1605
This yields the same information as walkdirs() only each entry is yielded
1606
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1607
are returned as exact byte-strings.
1609
:return: yields a tuple of (dir_info, [file_info])
1610
dir_info is (utf8_relpath, path-from-top)
1611
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1612
if top is an absolute path, path-from-top is also an absolute path.
1613
path-from-top might be unicode or utf8, but it is the correct path to
1614
pass to os functions to affect the file in question. (such as os.lstat)
1616
global _selected_dir_reader
1617
if _selected_dir_reader is None:
1618
fs_encoding = _fs_enc.upper()
1619
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1620
# Win98 doesn't have unicode apis like FindFirstFileW
1621
# TODO: We possibly could support Win98 by falling back to the
1622
# original FindFirstFile, and using TCHAR instead of WCHAR,
1623
# but that gets a bit tricky, and requires custom compiling
1626
from bzrlib._walkdirs_win32 import Win32ReadDir
1627
_selected_dir_reader = Win32ReadDir()
1630
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1631
# ANSI_X3.4-1968 is a form of ASCII
1633
from bzrlib._readdir_pyx import UTF8DirReader
1634
_selected_dir_reader = UTF8DirReader()
1635
except ImportError, e:
1636
failed_to_load_extension(e)
1639
if _selected_dir_reader is None:
1640
# Fallback to the python version
1641
_selected_dir_reader = UnicodeDirReader()
1643
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1644
# But we don't actually uses 1-3 in pending, so set them to None
1645
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1646
read_dir = _selected_dir_reader.read_dir
1647
_directory = _directory_kind
1649
relroot, _, _, _, top = pending[-1].pop()
1652
dirblock = sorted(read_dir(relroot, top))
1653
yield (relroot, top), dirblock
1654
# push the user specified dirs from dirblock
1655
next = [d for d in reversed(dirblock) if d[2] == _directory]
1657
pending.append(next)
1660
class UnicodeDirReader(DirReader):
1661
"""A dir reader for non-utf8 file systems, which transcodes."""
1663
__slots__ = ['_utf8_encode']
1666
self._utf8_encode = codecs.getencoder('utf8')
1668
def top_prefix_to_starting_dir(self, top, prefix=""):
1669
"""See DirReader.top_prefix_to_starting_dir."""
1670
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1672
def read_dir(self, prefix, top):
1673
"""Read a single directory from a non-utf8 file system.
1675
top, and the abspath element in the output are unicode, all other paths
1676
are utf8. Local disk IO is done via unicode calls to listdir etc.
1678
This is currently the fallback code path when the filesystem encoding is
1679
not UTF-8. It may be better to implement an alternative so that we can
1680
safely handle paths that are not properly decodable in the current
1683
See DirReader.read_dir for details.
1685
_utf8_encode = self._utf8_encode
1687
_listdir = os.listdir
1688
_kind_from_mode = file_kind_from_stat_mode
1691
relprefix = prefix + '/'
1694
top_slash = top + u'/'
1697
append = dirblock.append
1698
for name in sorted(_listdir(top)):
1700
name_utf8 = _utf8_encode(name)[0]
1701
except UnicodeDecodeError:
1702
raise errors.BadFilenameEncoding(
1703
_utf8_encode(relprefix)[0] + name, _fs_enc)
1704
abspath = top_slash + name
1705
statvalue = _lstat(abspath)
1706
kind = _kind_from_mode(statvalue.st_mode)
1707
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1711
def copy_tree(from_path, to_path, handlers={}):
1712
"""Copy all of the entries in from_path into to_path.
1714
:param from_path: The base directory to copy.
1715
:param to_path: The target directory. If it does not exist, it will
1717
:param handlers: A dictionary of functions, which takes a source and
1718
destinations for files, directories, etc.
1719
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1720
'file', 'directory', and 'symlink' should always exist.
1721
If they are missing, they will be replaced with 'os.mkdir()',
1722
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1724
# Now, just copy the existing cached tree to the new location
1725
# We use a cheap trick here.
1726
# Absolute paths are prefixed with the first parameter
1727
# relative paths are prefixed with the second.
1728
# So we can get both the source and target returned
1729
# without any extra work.
1731
def copy_dir(source, dest):
1734
def copy_link(source, dest):
1735
"""Copy the contents of a symlink"""
1736
link_to = os.readlink(source)
1737
os.symlink(link_to, dest)
1739
real_handlers = {'file':shutil.copy2,
1740
'symlink':copy_link,
1741
'directory':copy_dir,
1743
real_handlers.update(handlers)
1745
if not os.path.exists(to_path):
1746
real_handlers['directory'](from_path, to_path)
1748
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1749
for relpath, name, kind, st, abspath in entries:
1750
real_handlers[kind](abspath, relpath)
1753
def path_prefix_key(path):
1754
"""Generate a prefix-order path key for path.
1756
This can be used to sort paths in the same way that walkdirs does.
1758
return (dirname(path) , path)
1761
def compare_paths_prefix_order(path_a, path_b):
1762
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1763
key_a = path_prefix_key(path_a)
1764
key_b = path_prefix_key(path_b)
1765
return cmp(key_a, key_b)
1768
_cached_user_encoding = None
1771
def get_user_encoding(use_cache=True):
1772
"""Find out what the preferred user encoding is.
1774
This is generally the encoding that is used for command line parameters
1775
and file contents. This may be different from the terminal encoding
1776
or the filesystem encoding.
1778
:param use_cache: Enable cache for detected encoding.
1779
(This parameter is turned on by default,
1780
and required only for selftesting)
1782
:return: A string defining the preferred user encoding
1784
global _cached_user_encoding
1785
if _cached_user_encoding is not None and use_cache:
1786
return _cached_user_encoding
1788
if sys.platform == 'darwin':
1789
# python locale.getpreferredencoding() always return
1790
# 'mac-roman' on darwin. That's a lie.
1791
sys.platform = 'posix'
1793
if os.environ.get('LANG', None) is None:
1794
# If LANG is not set, we end up with 'ascii', which is bad
1795
# ('mac-roman' is more than ascii), so we set a default which
1796
# will give us UTF-8 (which appears to work in all cases on
1797
# OSX). Users are still free to override LANG of course, as
1798
# long as it give us something meaningful. This work-around
1799
# *may* not be needed with python 3k and/or OSX 10.5, but will
1800
# work with them too -- vila 20080908
1801
os.environ['LANG'] = 'en_US.UTF-8'
1804
sys.platform = 'darwin'
1809
user_encoding = locale.getpreferredencoding()
1810
except locale.Error, e:
1811
sys.stderr.write('bzr: warning: %s\n'
1812
' Could not determine what text encoding to use.\n'
1813
' This error usually means your Python interpreter\n'
1814
' doesn\'t support the locale set by $LANG (%s)\n'
1815
" Continuing with ascii encoding.\n"
1816
% (e, os.environ.get('LANG')))
1817
user_encoding = 'ascii'
1819
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1820
# treat that as ASCII, and not support printing unicode characters to the
1823
# For python scripts run under vim, we get '', so also treat that as ASCII
1824
if user_encoding in (None, 'cp0', ''):
1825
user_encoding = 'ascii'
1829
codecs.lookup(user_encoding)
1831
sys.stderr.write('bzr: warning:'
1832
' unknown encoding %s.'
1833
' Continuing with ascii encoding.\n'
1836
user_encoding = 'ascii'
1839
_cached_user_encoding = user_encoding
1841
return user_encoding
1844
def get_host_name():
1845
"""Return the current unicode host name.
1847
This is meant to be used in place of socket.gethostname() because that
1848
behaves inconsistently on different platforms.
1850
if sys.platform == "win32":
1852
return win32utils.get_host_name()
1855
return socket.gethostname().decode(get_user_encoding())
1858
def recv_all(socket, bytes):
1859
"""Receive an exact number of bytes.
1861
Regular Socket.recv() may return less than the requested number of bytes,
1862
dependning on what's in the OS buffer. MSG_WAITALL is not available
1863
on all platforms, but this should work everywhere. This will return
1864
less than the requested amount if the remote end closes.
1866
This isn't optimized and is intended mostly for use in testing.
1869
while len(b) < bytes:
1870
new = until_no_eintr(socket.recv, bytes - len(b))
1877
def send_all(socket, bytes, report_activity=None):
1878
"""Send all bytes on a socket.
1880
Regular socket.sendall() can give socket error 10053 on Windows. This
1881
implementation sends no more than 64k at a time, which avoids this problem.
1883
:param report_activity: Call this as bytes are read, see
1884
Transport._report_activity
1887
for pos in xrange(0, len(bytes), chunk_size):
1888
block = bytes[pos:pos+chunk_size]
1889
if report_activity is not None:
1890
report_activity(len(block), 'write')
1891
until_no_eintr(socket.sendall, block)
1894
def dereference_path(path):
1895
"""Determine the real path to a file.
1897
All parent elements are dereferenced. But the file itself is not
1899
:param path: The original path. May be absolute or relative.
1900
:return: the real path *to* the file
1902
parent, base = os.path.split(path)
1903
# The pathjoin for '.' is a workaround for Python bug #1213894.
1904
# (initial path components aren't dereferenced)
1905
return pathjoin(realpath(pathjoin('.', parent)), base)
1908
def supports_mapi():
1909
"""Return True if we can use MAPI to launch a mail client."""
1910
return sys.platform == "win32"
1913
def resource_string(package, resource_name):
1914
"""Load a resource from a package and return it as a string.
1916
Note: Only packages that start with bzrlib are currently supported.
1918
This is designed to be a lightweight implementation of resource
1919
loading in a way which is API compatible with the same API from
1921
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1922
If and when pkg_resources becomes a standard library, this routine
1925
# Check package name is within bzrlib
1926
if package == "bzrlib":
1927
resource_relpath = resource_name
1928
elif package.startswith("bzrlib."):
1929
package = package[len("bzrlib."):].replace('.', os.sep)
1930
resource_relpath = pathjoin(package, resource_name)
1932
raise errors.BzrError('resource package %s not in bzrlib' % package)
1934
# Map the resource to a file and read its contents
1935
base = dirname(bzrlib.__file__)
1936
if getattr(sys, 'frozen', None): # bzr.exe
1937
base = abspath(pathjoin(base, '..', '..'))
1938
filename = pathjoin(base, resource_relpath)
1939
return open(filename, 'rU').read()
1942
def file_kind_from_stat_mode_thunk(mode):
1943
global file_kind_from_stat_mode
1944
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1946
from bzrlib._readdir_pyx import UTF8DirReader
1947
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1948
except ImportError, e:
1949
# This is one time where we won't warn that an extension failed to
1950
# load. The extension is never available on Windows anyway.
1951
from bzrlib._readdir_py import (
1952
_kind_from_mode as file_kind_from_stat_mode
1954
return file_kind_from_stat_mode(mode)
1955
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1958
def file_kind(f, _lstat=os.lstat):
1960
return file_kind_from_stat_mode(_lstat(f).st_mode)
1962
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1963
raise errors.NoSuchFile(f)
1967
def until_no_eintr(f, *a, **kw):
1968
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1969
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1973
except (IOError, OSError), e:
1974
if e.errno == errno.EINTR:
1978
def re_compile_checked(re_string, flags=0, where=""):
1979
"""Return a compiled re, or raise a sensible error.
1981
This should only be used when compiling user-supplied REs.
1983
:param re_string: Text form of regular expression.
1984
:param flags: eg re.IGNORECASE
1985
:param where: Message explaining to the user the context where
1986
it occurred, eg 'log search filter'.
1988
# from https://bugs.launchpad.net/bzr/+bug/251352
1990
re_obj = re.compile(re_string, flags)
1995
where = ' in ' + where
1996
# despite the name 'error' is a type
1997
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1998
% (where, re_string, e))
2001
if sys.platform == "win32":
2004
return msvcrt.getch()
2009
fd = sys.stdin.fileno()
2010
settings = termios.tcgetattr(fd)
2013
ch = sys.stdin.read(1)
2015
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2019
if sys.platform == 'linux2':
2020
def _local_concurrency():
2022
prefix = 'processor'
2023
for line in file('/proc/cpuinfo', 'rb'):
2024
if line.startswith(prefix):
2025
concurrency = int(line[line.find(':')+1:]) + 1
2027
elif sys.platform == 'darwin':
2028
def _local_concurrency():
2029
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2030
stdout=subprocess.PIPE).communicate()[0]
2031
elif sys.platform[0:7] == 'freebsd':
2032
def _local_concurrency():
2033
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2034
stdout=subprocess.PIPE).communicate()[0]
2035
elif sys.platform == 'sunos5':
2036
def _local_concurrency():
2037
return subprocess.Popen(['psrinfo', '-p',],
2038
stdout=subprocess.PIPE).communicate()[0]
2039
elif sys.platform == "win32":
2040
def _local_concurrency():
2041
# This appears to return the number of cores.
2042
return os.environ.get('NUMBER_OF_PROCESSORS')
2044
def _local_concurrency():
2049
_cached_local_concurrency = None
2051
def local_concurrency(use_cache=True):
2052
"""Return how many processes can be run concurrently.
2054
Rely on platform specific implementations and default to 1 (one) if
2055
anything goes wrong.
2057
global _cached_local_concurrency
2059
if _cached_local_concurrency is not None and use_cache:
2060
return _cached_local_concurrency
2062
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2063
if concurrency is None:
2065
concurrency = _local_concurrency()
2066
except (OSError, IOError):
2069
concurrency = int(concurrency)
2070
except (TypeError, ValueError):
2073
_cached_concurrency = concurrency