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,
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
# On win32, O_BINARY is used to indicate the file should
75
# be opened in binary mode, rather than text mode.
76
# On other platforms, O_BINARY doesn't exist, because
77
# they always open in binary mode, so it is okay to
78
# OR with 0 on those platforms
79
O_BINARY = getattr(os, 'O_BINARY', 0)
82
def get_unicode_argv():
84
user_encoding = get_user_encoding()
85
return [a.decode(user_encoding) for a in sys.argv[1:]]
86
except UnicodeDecodeError:
87
raise errors.BzrError(("Parameter '%r' is unsupported by the current "
26
91
def make_readonly(filename):
27
92
"""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)
93
mod = os.lstat(filename).st_mode
94
if not stat.S_ISLNK(mod):
96
os.chmod(filename, mod)
34
99
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.,:/_~-])')
100
mod = os.lstat(filename).st_mode
101
if not stat.S_ISLNK(mod):
103
os.chmod(filename, mod)
106
def minimum_path_selection(paths):
107
"""Return the smallset subset of paths which are outside paths.
109
:param paths: A container (and hence not None) of paths.
110
:return: A set of paths sufficient to include everything in paths via
111
is_inside, drawn from the paths parameter.
117
return path.split('/')
118
sorted_paths = sorted(list(paths), key=sort_key)
120
search_paths = [sorted_paths[0]]
121
for path in sorted_paths[1:]:
122
if not is_inside(search_paths[-1], path):
123
# This path is unique, add it
124
search_paths.append(path)
126
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))
133
"""Return a quoted filename filename
135
This previously used backslash quoting, but that works poorly on
137
# TODO: I'm not really sure this is the best format either.x
139
if _QUOTE_RE is None:
140
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
142
if _QUOTE_RE.search(f):
148
_directory_kind = 'directory'
151
"""Return the current umask"""
152
# Assume that people aren't messing with the umask while running
153
# XXX: This is not thread safe, but there is no way to get the
154
# umask without setting it
162
_directory_kind: "/",
164
'tree-reference': '+',
168
def kind_marker(kind):
170
return _kind_marker_map[kind]
172
raise errors.BzrError('invalid file kind %r' % kind)
175
lexists = getattr(os.path, 'lexists', None)
179
stat = getattr(os, 'lstat', os.stat)
183
if e.errno == errno.ENOENT:
186
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
189
def fancy_rename(old, new, rename_func, unlink_func):
190
"""A fancy rename, when you don't have atomic rename.
192
:param old: The old path, to rename from
193
:param new: The new path, to rename to
194
:param rename_func: The potentially non-atomic rename function
195
:param unlink_func: A way to delete the target file if the full rename succeeds
198
# sftp rename doesn't allow overwriting, so play tricks:
199
base = os.path.basename(new)
200
dirname = os.path.dirname(new)
201
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
202
tmp_name = pathjoin(dirname, tmp_name)
204
# Rename the file out of the way, but keep track if it didn't exist
205
# We don't want to grab just any exception
206
# something like EACCES should prevent us from continuing
207
# The downside is that the rename_func has to throw an exception
208
# with an errno = ENOENT, or NoSuchFile
211
rename_func(new, tmp_name)
212
except (errors.NoSuchFile,), e:
215
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
216
# function raises an IOError with errno is None when a rename fails.
217
# This then gets caught here.
218
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
221
if (getattr(e, 'errno', None) is None
222
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
231
# This may throw an exception, in which case success will
233
rename_func(old, new)
235
except (IOError, OSError), e:
236
# source and target may be aliases of each other (e.g. on a
237
# case-insensitive filesystem), so we may have accidentally renamed
238
# source by when we tried to rename target
239
failure_exc = sys.exc_info()
240
if (file_existed and e.errno in (None, errno.ENOENT)
241
and old.lower() == new.lower()):
242
# source and target are the same file on a case-insensitive
243
# filesystem, so we don't generate an exception
247
# If the file used to exist, rename it back into place
248
# otherwise just delete it from the tmp location
250
unlink_func(tmp_name)
252
rename_func(tmp_name, new)
253
if failure_exc is not None:
254
raise failure_exc[0], failure_exc[1], failure_exc[2]
257
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
258
# choke on a Unicode string containing a relative path if
259
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
261
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
262
def _posix_abspath(path):
263
# jam 20060426 rather than encoding to fsencoding
264
# copy posixpath.abspath, but use os.getcwdu instead
265
if not posixpath.isabs(path):
266
path = posixpath.join(getcwd(), path)
267
return posixpath.normpath(path)
270
def _posix_realpath(path):
271
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
274
def _win32_fixdrive(path):
275
"""Force drive letters to be consistent.
277
win32 is inconsistent whether it returns lower or upper case
278
and even if it was consistent the user might type the other
279
so we force it to uppercase
280
running python.exe under cmd.exe return capital C:\\
281
running win32 python inside a cygwin shell returns lowercase c:\\
283
drive, path = _nt_splitdrive(path)
284
return drive.upper() + path
287
def _win32_abspath(path):
288
# Real _nt_abspath doesn't have a problem with a unicode cwd
289
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
292
def _win98_abspath(path):
293
"""Return the absolute version of a path.
294
Windows 98 safe implementation (python reimplementation
295
of Win32 API function GetFullPathNameW)
300
# \\HOST\path => //HOST/path
301
# //HOST/path => //HOST/path
302
# path => C:/cwd/path
305
# check for absolute path
306
drive = _nt_splitdrive(path)[0]
307
if drive == '' and path[:2] not in('//','\\\\'):
309
# we cannot simply os.path.join cwd and path
310
# because os.path.join('C:','/path') produce '/path'
311
# and this is incorrect
312
if path[:1] in ('/','\\'):
313
cwd = _nt_splitdrive(cwd)[0]
315
path = cwd + '\\' + path
316
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
319
def _win32_realpath(path):
320
# Real _nt_realpath doesn't have a problem with a unicode cwd
321
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
324
def _win32_pathjoin(*args):
325
return _nt_join(*args).replace('\\', '/')
328
def _win32_normpath(path):
329
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
333
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
336
def _win32_mkdtemp(*args, **kwargs):
337
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
340
def _win32_rename(old, new):
341
"""We expect to be able to atomically replace 'new' with old.
343
On win32, if new exists, it must be moved out of the way first,
347
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
349
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
350
# If we try to rename a non-existant file onto cwd, we get
351
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
352
# if the old path doesn't exist, sometimes we get EACCES
353
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
359
return unicodedata.normalize('NFC', os.getcwdu())
362
# Default is to just use the python builtins, but these can be rebound on
363
# particular platforms.
364
abspath = _posix_abspath
365
realpath = _posix_realpath
366
pathjoin = os.path.join
367
normpath = os.path.normpath
370
dirname = os.path.dirname
371
basename = os.path.basename
372
split = os.path.split
373
splitext = os.path.splitext
374
# These were already imported into local scope
375
# mkdtemp = tempfile.mkdtemp
376
# rmtree = shutil.rmtree
378
MIN_ABS_PATHLENGTH = 1
381
if sys.platform == 'win32':
382
if win32utils.winver == 'Windows 98':
383
abspath = _win98_abspath
385
abspath = _win32_abspath
386
realpath = _win32_realpath
387
pathjoin = _win32_pathjoin
388
normpath = _win32_normpath
389
getcwd = _win32_getcwd
390
mkdtemp = _win32_mkdtemp
391
rename = _win32_rename
393
MIN_ABS_PATHLENGTH = 3
395
def _win32_delete_readonly(function, path, excinfo):
396
"""Error handler for shutil.rmtree function [for win32]
397
Helps to remove files and dirs marked as read-only.
399
exception = excinfo[1]
400
if function in (os.remove, os.rmdir) \
401
and isinstance(exception, OSError) \
402
and exception.errno == errno.EACCES:
408
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
409
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
410
return shutil.rmtree(path, ignore_errors, onerror)
412
f = win32utils.get_unicode_argv # special function or None
416
elif sys.platform == 'darwin':
420
def get_terminal_encoding():
421
"""Find the best encoding for printing to the screen.
423
This attempts to check both sys.stdout and sys.stdin to see
424
what encoding they are in, and if that fails it falls back to
425
osutils.get_user_encoding().
426
The problem is that on Windows, locale.getpreferredencoding()
427
is not the same encoding as that used by the console:
428
http://mail.python.org/pipermail/python-list/2003-May/162357.html
430
On my standard US Windows XP, the preferred encoding is
431
cp1252, but the console is cp437
433
from bzrlib.trace import mutter
434
output_encoding = getattr(sys.stdout, 'encoding', None)
435
if not output_encoding:
436
input_encoding = getattr(sys.stdin, 'encoding', None)
437
if not input_encoding:
438
output_encoding = get_user_encoding()
439
mutter('encoding stdout as osutils.get_user_encoding() %r',
442
output_encoding = input_encoding
443
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
445
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
446
if output_encoding == 'cp0':
447
# invalid encoding (cp0 means 'no codepage' on Windows)
448
output_encoding = get_user_encoding()
449
mutter('cp0 is invalid encoding.'
450
' encoding stdout as osutils.get_user_encoding() %r',
454
codecs.lookup(output_encoding)
456
sys.stderr.write('bzr: warning:'
457
' unknown terminal encoding %s.\n'
458
' Using encoding %s instead.\n'
459
% (output_encoding, get_user_encoding())
461
output_encoding = get_user_encoding()
463
return output_encoding
466
def normalizepath(f):
467
if getattr(os.path, 'realpath', None) is not None:
471
[p,e] = os.path.split(f)
472
if e == "" or e == "." or e == "..":
475
return pathjoin(F(p), e)
241
690
def local_time_offset(t=None):
242
691
"""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)
694
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
695
return offset.days * 86400 + offset.seconds
697
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
698
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
701
def format_date(t, offset=0, timezone='original', date_fmt=None,
703
"""Return a formatted date string.
705
:param t: Seconds since the epoch.
706
:param offset: Timezone offset in seconds east of utc.
707
:param timezone: How to display the time: 'utc', 'original' for the
708
timezone specified by offset, or 'local' for the process's current
710
:param date_fmt: strftime format.
711
:param show_offset: Whether to append the timezone.
713
(date_fmt, tt, offset_str) = \
714
_format_date(t, offset, timezone, date_fmt, show_offset)
715
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
716
date_str = time.strftime(date_fmt, tt)
717
return date_str + offset_str
720
# Cache of formatted offset strings
724
def format_date_with_offset_in_original_timezone(t, offset=0,
725
_cache=_offset_cache):
726
"""Return a formatted date string in the original timezone.
728
This routine may be faster then format_date.
730
:param t: Seconds since the epoch.
731
:param offset: Timezone offset in seconds east of utc.
735
tt = time.gmtime(t + offset)
736
date_fmt = _default_format_by_weekday_num[tt[6]]
737
date_str = time.strftime(date_fmt, tt)
738
offset_str = _cache.get(offset, None)
739
if offset_str is None:
740
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
741
_cache[offset] = offset_str
742
return date_str + offset_str
745
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
747
"""Return an unicode date string formatted according to the current locale.
749
:param t: Seconds since the epoch.
750
:param offset: Timezone offset in seconds east of utc.
751
:param timezone: How to display the time: 'utc', 'original' for the
752
timezone specified by offset, or 'local' for the process's current
754
:param date_fmt: strftime format.
755
:param show_offset: Whether to append the timezone.
757
(date_fmt, tt, offset_str) = \
758
_format_date(t, offset, timezone, date_fmt, show_offset)
759
date_str = time.strftime(date_fmt, tt)
760
if not isinstance(date_str, unicode):
761
date_str = date_str.decode(get_user_encoding(), 'replace')
762
return date_str + offset_str
765
def _format_date(t, offset, timezone, date_fmt, show_offset):
258
766
if timezone == 'utc':
259
767
tt = time.gmtime(t)
261
769
elif timezone == 'original':
264
772
tt = time.gmtime(t + offset)
265
773
elif timezone == 'local':
266
774
tt = time.localtime(t)
267
775
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))
777
raise errors.UnsupportedTimezoneFormat(timezone)
779
date_fmt = "%a %Y-%m-%d %H:%M:%S"
781
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
784
return (date_fmt, tt, offset_str)
276
787
def compact_date(when):
277
788
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
791
def format_delta(delta):
792
"""Get a nice looking string for a time delta.
794
:param delta: The time difference in seconds, can be positive or negative.
795
positive indicates time in the past, negative indicates time in the
796
future. (usually time.time() - stored_time)
797
:return: String formatted to show approximate resolution
803
direction = 'in the future'
807
if seconds < 90: # print seconds up to 90 seconds
809
return '%d second %s' % (seconds, direction,)
811
return '%d seconds %s' % (seconds, direction)
813
minutes = int(seconds / 60)
814
seconds -= 60 * minutes
819
if minutes < 90: # print minutes, seconds up to 90 minutes
821
return '%d minute, %d second%s %s' % (
822
minutes, seconds, plural_seconds, direction)
824
return '%d minutes, %d second%s %s' % (
825
minutes, seconds, plural_seconds, direction)
827
hours = int(minutes / 60)
828
minutes -= 60 * hours
835
return '%d hour, %d minute%s %s' % (hours, minutes,
836
plural_minutes, direction)
837
return '%d hours, %d minute%s %s' % (hours, minutes,
838
plural_minutes, direction)
282
841
"""Return size of given open file."""
283
842
return os.fstat(f.fileno())[ST_SIZE]
286
if hasattr(os, 'urandom'): # python 2.4 and later
845
# Define rand_bytes based on platform.
847
# Python 2.4 and later have os.urandom,
848
# but it doesn't work on some arches
287
850
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))
851
except (NotImplementedError, AttributeError):
852
# If python doesn't have os.urandom, or it doesn't work,
853
# then try to first pull random data from /dev/urandom
855
rand_bytes = file('/dev/urandom', 'rb').read
856
# Otherwise, use this hack as a last resort
857
except (IOError, OSError):
858
# not well seeded, but better than nothing
863
s += chr(random.randint(0, 255))
868
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
870
"""Return a random string of num alphanumeric characters
872
The result only contains lowercase chars because it may be used on
873
case-insensitive filesystems.
876
for raw_byte in rand_bytes(num):
877
s += ALNUM[ord(raw_byte) % 36]
301
881
## TODO: We could later have path objects that remember their list
302
882
## decomposition (might be too tricksy though.)
304
884
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)
885
"""Turn string into list of parts."""
322
886
# split on either delimiter because people might use either on
324
888
ps = re.split(r'[\\/]', p)
329
bailout("sorry, %r not allowed in path" % f)
893
raise errors.BzrError("sorry, %r not allowed in path" % f)
330
894
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')
903
if (f == '..') or (f is None) or (f == ''):
904
raise errors.BzrError("sorry, %r not allowed in path" % f)
908
def parent_directories(filename):
909
"""Return the list of parent directories, deepest first.
911
For example, parent_directories("a/b/c") -> ["a/b", "a"].
914
parts = splitpath(dirname(filename))
916
parents.append(joinpath(parts))
921
_extension_load_failures = []
924
def failed_to_load_extension(exception):
925
"""Handle failing to load a binary extension.
927
This should be called from the ImportError block guarding the attempt to
928
import the native extension. If this function returns, the pure-Python
929
implementation should be loaded instead::
932
>>> import bzrlib._fictional_extension_pyx
933
>>> except ImportError, e:
934
>>> bzrlib.osutils.failed_to_load_extension(e)
935
>>> import bzrlib._fictional_extension_py
937
# NB: This docstring is just an example, not a doctest, because doctest
938
# currently can't cope with the use of lazy imports in this namespace --
941
# This currently doesn't report the failure at the time it occurs, because
942
# they tend to happen very early in startup when we can't check config
943
# files etc, and also we want to report all failures but not spam the user
945
from bzrlib import trace
946
exception_str = str(exception)
947
if exception_str not in _extension_load_failures:
948
trace.mutter("failed to load compiled extension: %s" % exception_str)
949
_extension_load_failures.append(exception_str)
952
def report_extension_load_failures():
953
if not _extension_load_failures:
955
from bzrlib.config import GlobalConfig
956
if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
958
# the warnings framework should by default show this only once
959
from bzrlib.trace import warning
961
"bzr: warning: some compiled extensions could not be loaded; "
962
"see <https://answers.launchpad.net/bzr/+faq/703>")
963
# we no longer show the specific missing extensions here, because it makes
964
# the message too long and scary - see
965
# https://bugs.launchpad.net/bzr/+bug/430529
969
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
970
except ImportError, e:
971
failed_to_load_extension(e)
972
from bzrlib._chunks_to_lines_py import chunks_to_lines
976
"""Split s into lines, but without removing the newline characters."""
977
# Trivially convert a fulltext into a 'chunked' representation, and let
978
# chunks_to_lines do the heavy lifting.
979
if isinstance(s, str):
980
# chunks_to_lines only supports 8-bit strings
981
return chunks_to_lines([s])
983
return _split_lines(s)
987
"""Split s into lines, but without removing the newline characters.
989
This supports Unicode or plain string objects.
991
lines = s.split('\n')
992
result = [line + '\n' for line in lines[:-1]]
994
result.append(lines[-1])
998
def hardlinks_good():
999
return sys.platform not in ('win32', 'cygwin', 'darwin')
1002
def link_or_copy(src, dest):
1003
"""Hardlink a file, or copy it if it can't be hardlinked."""
1004
if not hardlinks_good():
1005
shutil.copyfile(src, dest)
1009
except (OSError, IOError), e:
1010
if e.errno != errno.EXDEV:
1012
shutil.copyfile(src, dest)
1015
def delete_any(path):
1016
"""Delete a file, symlink or directory.
1018
Will delete even if readonly.
1021
_delete_file_or_dir(path)
1022
except (OSError, IOError), e:
1023
if e.errno in (errno.EPERM, errno.EACCES):
1024
# make writable and try again
1027
except (OSError, IOError):
1029
_delete_file_or_dir(path)
1034
def _delete_file_or_dir(path):
1035
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1036
# Forgiveness than Permission (EAFP) because:
1037
# - root can damage a solaris file system by using unlink,
1038
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1039
# EACCES, OSX: EPERM) when invoked on a directory.
1040
if isdir(path): # Takes care of symlinks
1047
if getattr(os, 'symlink', None) is not None:
1053
def has_hardlinks():
1054
if getattr(os, 'link', None) is not None:
1060
def host_os_dereferences_symlinks():
1061
return (has_symlinks()
1062
and sys.platform not in ('cygwin', 'win32'))
1065
def readlink(abspath):
1066
"""Return a string representing the path to which the symbolic link points.
1068
:param abspath: The link absolute unicode path.
1070
This his guaranteed to return the symbolic link in unicode in all python
1073
link = abspath.encode(_fs_enc)
1074
target = os.readlink(link)
1075
target = target.decode(_fs_enc)
1079
def contains_whitespace(s):
1080
"""True if there are any whitespace characters in s."""
1081
# string.whitespace can include '\xa0' in certain locales, because it is
1082
# considered "non-breaking-space" as part of ISO-8859-1. But it
1083
# 1) Isn't a breaking whitespace
1084
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1086
# 3) '\xa0' isn't unicode safe since it is >128.
1088
# This should *not* be a unicode set of characters in case the source
1089
# string is not a Unicode string. We can auto-up-cast the characters since
1090
# they are ascii, but we don't want to auto-up-cast the string in case it
1092
for ch in ' \t\n\r\v\f':
1099
def contains_linebreaks(s):
1100
"""True if there is any vertical whitespace in s."""
1108
def relpath(base, path):
1109
"""Return path relative to base, or raise exception.
1111
The path may be either an absolute path or a path relative to the
1112
current working directory.
1114
os.path.commonprefix (python2.4) has a bad bug that it works just
1115
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1116
avoids that problem.
1119
if len(base) < MIN_ABS_PATHLENGTH:
1120
# must have space for e.g. a drive letter
1121
raise ValueError('%r is too short to calculate a relative path'
1129
if len(head) <= len(base) and head != base:
1130
raise errors.PathNotChild(rp, base)
1133
head, tail = split(head)
1138
return pathjoin(*reversed(s))
1143
def _cicp_canonical_relpath(base, path):
1144
"""Return the canonical path relative to base.
1146
Like relpath, but on case-insensitive-case-preserving file-systems, this
1147
will return the relpath as stored on the file-system rather than in the
1148
case specified in the input string, for all existing portions of the path.
1150
This will cause O(N) behaviour if called for every path in a tree; if you
1151
have a number of paths to convert, you should use canonical_relpaths().
1153
# TODO: it should be possible to optimize this for Windows by using the
1154
# win32 API FindFiles function to look for the specified name - but using
1155
# os.listdir() still gives us the correct, platform agnostic semantics in
1158
rel = relpath(base, path)
1159
# '.' will have been turned into ''
1163
abs_base = abspath(base)
1165
_listdir = os.listdir
1167
# use an explicit iterator so we can easily consume the rest on early exit.
1168
bit_iter = iter(rel.split('/'))
1169
for bit in bit_iter:
1172
next_entries = _listdir(current)
1173
except OSError: # enoent, eperm, etc
1174
# We can't find this in the filesystem, so just append the
1176
current = pathjoin(current, bit, *list(bit_iter))
1178
for look in next_entries:
1179
if lbit == look.lower():
1180
current = pathjoin(current, look)
1183
# got to the end, nothing matched, so we just return the
1184
# non-existing bits as they were specified (the filename may be
1185
# the target of a move, for example).
1186
current = pathjoin(current, bit, *list(bit_iter))
1188
return current[len(abs_base):].lstrip('/')
1190
# XXX - TODO - we need better detection/integration of case-insensitive
1191
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1192
# filesystems), for example, so could probably benefit from the same basic
1193
# support there. For now though, only Windows and OSX get that support, and
1194
# they get it for *all* file-systems!
1195
if sys.platform in ('win32', 'darwin'):
1196
canonical_relpath = _cicp_canonical_relpath
1198
canonical_relpath = relpath
1200
def canonical_relpaths(base, paths):
1201
"""Create an iterable to canonicalize a sequence of relative paths.
1203
The intent is for this implementation to use a cache, vastly speeding
1204
up multiple transformations in the same directory.
1206
# but for now, we haven't optimized...
1207
return [canonical_relpath(base, p) for p in paths]
1209
def safe_unicode(unicode_or_utf8_string):
1210
"""Coerce unicode_or_utf8_string into unicode.
1212
If it is unicode, it is returned.
1213
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1214
wrapped in a BzrBadParameterNotUnicode exception.
1216
if isinstance(unicode_or_utf8_string, unicode):
1217
return unicode_or_utf8_string
1219
return unicode_or_utf8_string.decode('utf8')
1220
except UnicodeDecodeError:
1221
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1224
def safe_utf8(unicode_or_utf8_string):
1225
"""Coerce unicode_or_utf8_string to a utf8 string.
1227
If it is a str, it is returned.
1228
If it is Unicode, it is encoded into a utf-8 string.
1230
if isinstance(unicode_or_utf8_string, str):
1231
# TODO: jam 20070209 This is overkill, and probably has an impact on
1232
# performance if we are dealing with lots of apis that want a
1235
# Make sure it is a valid utf-8 string
1236
unicode_or_utf8_string.decode('utf-8')
1237
except UnicodeDecodeError:
1238
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1239
return unicode_or_utf8_string
1240
return unicode_or_utf8_string.encode('utf-8')
1243
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1244
' Revision id generators should be creating utf8'
1248
def safe_revision_id(unicode_or_utf8_string, warn=True):
1249
"""Revision ids should now be utf8, but at one point they were unicode.
1251
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1253
:param warn: Functions that are sanitizing user data can set warn=False
1254
:return: None or a utf8 revision id.
1256
if (unicode_or_utf8_string is None
1257
or unicode_or_utf8_string.__class__ == str):
1258
return unicode_or_utf8_string
1260
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1262
return cache_utf8.encode(unicode_or_utf8_string)
1265
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1266
' generators should be creating utf8 file ids.')
1269
def safe_file_id(unicode_or_utf8_string, warn=True):
1270
"""File ids should now be utf8, but at one point they were unicode.
1272
This is the same as safe_utf8, except it uses the cached encode functions
1273
to save a little bit of performance.
1275
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1277
:param warn: Functions that are sanitizing user data can set warn=False
1278
:return: None or a utf8 file id.
1280
if (unicode_or_utf8_string is None
1281
or unicode_or_utf8_string.__class__ == str):
1282
return unicode_or_utf8_string
1284
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1286
return cache_utf8.encode(unicode_or_utf8_string)
1289
_platform_normalizes_filenames = False
1290
if sys.platform == 'darwin':
1291
_platform_normalizes_filenames = True
1294
def normalizes_filenames():
1295
"""Return True if this platform normalizes unicode filenames.
1297
Mac OSX does, Windows/Linux do not.
1299
return _platform_normalizes_filenames
1302
def _accessible_normalized_filename(path):
1303
"""Get the unicode normalized path, and if you can access the file.
1305
On platforms where the system normalizes filenames (Mac OSX),
1306
you can access a file by any path which will normalize correctly.
1307
On platforms where the system does not normalize filenames
1308
(Windows, Linux), you have to access a file by its exact path.
1310
Internally, bzr only supports NFC normalization, since that is
1311
the standard for XML documents.
1313
So return the normalized path, and a flag indicating if the file
1314
can be accessed by that path.
1317
return unicodedata.normalize('NFC', unicode(path)), True
1320
def _inaccessible_normalized_filename(path):
1321
__doc__ = _accessible_normalized_filename.__doc__
1323
normalized = unicodedata.normalize('NFC', unicode(path))
1324
return normalized, normalized == path
1327
if _platform_normalizes_filenames:
1328
normalized_filename = _accessible_normalized_filename
1330
normalized_filename = _inaccessible_normalized_filename
1333
default_terminal_width = 80
1334
"""The default terminal width for ttys.
1336
This is defined so that higher levels can share a common fallback value when
1337
terminal_width() returns None.
1341
def terminal_width():
1342
"""Return terminal width.
1344
None is returned if the width can't established precisely.
1347
- if BZR_COLUMNS is set, returns its value
1348
- if there is no controlling terminal, returns None
1349
- if COLUMNS is set, returns its value,
1351
From there, we need to query the OS to get the size of the controlling
1355
- get termios.TIOCGWINSZ
1356
- if an error occurs or a negative value is obtained, returns None
1360
- win32utils.get_console_size() decides,
1361
- returns None on error (provided default value)
1364
# If BZR_COLUMNS is set, take it, user is always right
1366
return int(os.environ['BZR_COLUMNS'])
1367
except (KeyError, ValueError):
1370
isatty = getattr(sys.stdout, 'isatty', None)
1371
if isatty is None or not isatty():
1372
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1375
# If COLUMNS is set, take it, the terminal knows better (even inside a
1376
# given terminal, the application can decide to set COLUMNS to a lower
1377
# value (splitted screen) or a bigger value (scroll bars))
1379
return int(os.environ['COLUMNS'])
1380
except (KeyError, ValueError):
1383
width, height = _terminal_size(None, None)
1385
# Consider invalid values as meaning no width
1391
def _win32_terminal_size(width, height):
1392
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1393
return width, height
1396
def _ioctl_terminal_size(width, height):
1398
import struct, fcntl, termios
1399
s = struct.pack('HHHH', 0, 0, 0, 0)
1400
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1401
height, width = struct.unpack('HHHH', x)[0:2]
1402
except (IOError, AttributeError):
1404
return width, height
1406
_terminal_size = None
1407
"""Returns the terminal size as (width, height).
1409
:param width: Default value for width.
1410
:param height: Default value for height.
1412
This is defined specifically for each OS and query the size of the controlling
1413
terminal. If any error occurs, the provided default values should be returned.
1415
if sys.platform == 'win32':
1416
_terminal_size = _win32_terminal_size
1418
_terminal_size = _ioctl_terminal_size
1421
def supports_executable():
1422
return sys.platform != "win32"
1425
def supports_posix_readonly():
1426
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1428
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1429
directory controls creation/deletion, etc.
1431
And under win32, readonly means that the directory itself cannot be
1432
deleted. The contents of a readonly directory can be changed, unlike POSIX
1433
where files in readonly directories cannot be added, deleted or renamed.
1435
return sys.platform != "win32"
1438
def set_or_unset_env(env_variable, value):
1439
"""Modify the environment, setting or removing the env_variable.
1441
:param env_variable: The environment variable in question
1442
:param value: The value to set the environment to. If None, then
1443
the variable will be removed.
1444
:return: The original value of the environment variable.
1446
orig_val = os.environ.get(env_variable)
1448
if orig_val is not None:
1449
del os.environ[env_variable]
1451
if isinstance(value, unicode):
1452
value = value.encode(get_user_encoding())
1453
os.environ[env_variable] = value
1457
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1460
def check_legal_path(path):
1461
"""Check whether the supplied path is legal.
1462
This is only required on Windows, so we don't test on other platforms
1465
if sys.platform != "win32":
1467
if _validWin32PathRE.match(path) is None:
1468
raise errors.IllegalPath(path)
1471
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1473
def _is_error_enotdir(e):
1474
"""Check if this exception represents ENOTDIR.
1476
Unfortunately, python is very inconsistent about the exception
1477
here. The cases are:
1478
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1479
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1480
which is the windows error code.
1481
3) Windows, Python2.5 uses errno == EINVAL and
1482
winerror == ERROR_DIRECTORY
1484
:param e: An Exception object (expected to be OSError with an errno
1485
attribute, but we should be able to cope with anything)
1486
:return: True if this represents an ENOTDIR error. False otherwise.
1488
en = getattr(e, 'errno', None)
1489
if (en == errno.ENOTDIR
1490
or (sys.platform == 'win32'
1491
and (en == _WIN32_ERROR_DIRECTORY
1492
or (en == errno.EINVAL
1493
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1499
def walkdirs(top, prefix=""):
1500
"""Yield data about all the directories in a tree.
1502
This yields all the data about the contents of a directory at a time.
1503
After each directory has been yielded, if the caller has mutated the list
1504
to exclude some directories, they are then not descended into.
1506
The data yielded is of the form:
1507
((directory-relpath, directory-path-from-top),
1508
[(relpath, basename, kind, lstat, path-from-top), ...]),
1509
- directory-relpath is the relative path of the directory being returned
1510
with respect to top. prefix is prepended to this.
1511
- directory-path-from-root is the path including top for this directory.
1512
It is suitable for use with os functions.
1513
- relpath is the relative path within the subtree being walked.
1514
- basename is the basename of the path
1515
- kind is the kind of the file now. If unknown then the file is not
1516
present within the tree - but it may be recorded as versioned. See
1518
- lstat is the stat data *if* the file was statted.
1519
- planned, not implemented:
1520
path_from_tree_root is the path from the root of the tree.
1522
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1523
allows one to walk a subtree but get paths that are relative to a tree
1525
:return: an iterator over the dirs.
1527
#TODO there is a bit of a smell where the results of the directory-
1528
# summary in this, and the path from the root, may not agree
1529
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1530
# potentially confusing output. We should make this more robust - but
1531
# not at a speed cost. RBC 20060731
1533
_directory = _directory_kind
1534
_listdir = os.listdir
1535
_kind_from_mode = file_kind_from_stat_mode
1536
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1538
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1539
relroot, _, _, _, top = pending.pop()
1541
relprefix = relroot + u'/'
1544
top_slash = top + u'/'
1547
append = dirblock.append
1549
names = sorted(_listdir(top))
1551
if not _is_error_enotdir(e):
1555
abspath = top_slash + name
1556
statvalue = _lstat(abspath)
1557
kind = _kind_from_mode(statvalue.st_mode)
1558
append((relprefix + name, name, kind, statvalue, abspath))
1559
yield (relroot, top), dirblock
1561
# push the user specified dirs from dirblock
1562
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1565
class DirReader(object):
1566
"""An interface for reading directories."""
1568
def top_prefix_to_starting_dir(self, top, prefix=""):
1569
"""Converts top and prefix to a starting dir entry
1571
:param top: A utf8 path
1572
:param prefix: An optional utf8 path to prefix output relative paths
1574
:return: A tuple starting with prefix, and ending with the native
1577
raise NotImplementedError(self.top_prefix_to_starting_dir)
1579
def read_dir(self, prefix, top):
1580
"""Read a specific dir.
1582
:param prefix: A utf8 prefix to be preprended to the path basenames.
1583
:param top: A natively encoded path to read.
1584
:return: A list of the directories contents. Each item contains:
1585
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1587
raise NotImplementedError(self.read_dir)
1590
_selected_dir_reader = None
1593
def _walkdirs_utf8(top, prefix=""):
1594
"""Yield data about all the directories in a tree.
1596
This yields the same information as walkdirs() only each entry is yielded
1597
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1598
are returned as exact byte-strings.
1600
:return: yields a tuple of (dir_info, [file_info])
1601
dir_info is (utf8_relpath, path-from-top)
1602
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1603
if top is an absolute path, path-from-top is also an absolute path.
1604
path-from-top might be unicode or utf8, but it is the correct path to
1605
pass to os functions to affect the file in question. (such as os.lstat)
1607
global _selected_dir_reader
1608
if _selected_dir_reader is None:
1609
fs_encoding = _fs_enc.upper()
1610
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1611
# Win98 doesn't have unicode apis like FindFirstFileW
1612
# TODO: We possibly could support Win98 by falling back to the
1613
# original FindFirstFile, and using TCHAR instead of WCHAR,
1614
# but that gets a bit tricky, and requires custom compiling
1617
from bzrlib._walkdirs_win32 import Win32ReadDir
1618
_selected_dir_reader = Win32ReadDir()
1621
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1622
# ANSI_X3.4-1968 is a form of ASCII
1624
from bzrlib._readdir_pyx import UTF8DirReader
1625
_selected_dir_reader = UTF8DirReader()
1626
except ImportError, e:
1627
failed_to_load_extension(e)
1630
if _selected_dir_reader is None:
1631
# Fallback to the python version
1632
_selected_dir_reader = UnicodeDirReader()
1634
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1635
# But we don't actually uses 1-3 in pending, so set them to None
1636
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1637
read_dir = _selected_dir_reader.read_dir
1638
_directory = _directory_kind
1640
relroot, _, _, _, top = pending[-1].pop()
1643
dirblock = sorted(read_dir(relroot, top))
1644
yield (relroot, top), dirblock
1645
# push the user specified dirs from dirblock
1646
next = [d for d in reversed(dirblock) if d[2] == _directory]
1648
pending.append(next)
1651
class UnicodeDirReader(DirReader):
1652
"""A dir reader for non-utf8 file systems, which transcodes."""
1654
__slots__ = ['_utf8_encode']
1657
self._utf8_encode = codecs.getencoder('utf8')
1659
def top_prefix_to_starting_dir(self, top, prefix=""):
1660
"""See DirReader.top_prefix_to_starting_dir."""
1661
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1663
def read_dir(self, prefix, top):
1664
"""Read a single directory from a non-utf8 file system.
1666
top, and the abspath element in the output are unicode, all other paths
1667
are utf8. Local disk IO is done via unicode calls to listdir etc.
1669
This is currently the fallback code path when the filesystem encoding is
1670
not UTF-8. It may be better to implement an alternative so that we can
1671
safely handle paths that are not properly decodable in the current
1674
See DirReader.read_dir for details.
1676
_utf8_encode = self._utf8_encode
1678
_listdir = os.listdir
1679
_kind_from_mode = file_kind_from_stat_mode
1682
relprefix = prefix + '/'
1685
top_slash = top + u'/'
1688
append = dirblock.append
1689
for name in sorted(_listdir(top)):
1691
name_utf8 = _utf8_encode(name)[0]
1692
except UnicodeDecodeError:
1693
raise errors.BadFilenameEncoding(
1694
_utf8_encode(relprefix)[0] + name, _fs_enc)
1695
abspath = top_slash + name
1696
statvalue = _lstat(abspath)
1697
kind = _kind_from_mode(statvalue.st_mode)
1698
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1702
def copy_tree(from_path, to_path, handlers={}):
1703
"""Copy all of the entries in from_path into to_path.
1705
:param from_path: The base directory to copy.
1706
:param to_path: The target directory. If it does not exist, it will
1708
:param handlers: A dictionary of functions, which takes a source and
1709
destinations for files, directories, etc.
1710
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1711
'file', 'directory', and 'symlink' should always exist.
1712
If they are missing, they will be replaced with 'os.mkdir()',
1713
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1715
# Now, just copy the existing cached tree to the new location
1716
# We use a cheap trick here.
1717
# Absolute paths are prefixed with the first parameter
1718
# relative paths are prefixed with the second.
1719
# So we can get both the source and target returned
1720
# without any extra work.
1722
def copy_dir(source, dest):
1725
def copy_link(source, dest):
1726
"""Copy the contents of a symlink"""
1727
link_to = os.readlink(source)
1728
os.symlink(link_to, dest)
1730
real_handlers = {'file':shutil.copy2,
1731
'symlink':copy_link,
1732
'directory':copy_dir,
1734
real_handlers.update(handlers)
1736
if not os.path.exists(to_path):
1737
real_handlers['directory'](from_path, to_path)
1739
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1740
for relpath, name, kind, st, abspath in entries:
1741
real_handlers[kind](abspath, relpath)
1744
def path_prefix_key(path):
1745
"""Generate a prefix-order path key for path.
1747
This can be used to sort paths in the same way that walkdirs does.
1749
return (dirname(path) , path)
1752
def compare_paths_prefix_order(path_a, path_b):
1753
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1754
key_a = path_prefix_key(path_a)
1755
key_b = path_prefix_key(path_b)
1756
return cmp(key_a, key_b)
1759
_cached_user_encoding = None
1762
def get_user_encoding(use_cache=True):
1763
"""Find out what the preferred user encoding is.
1765
This is generally the encoding that is used for command line parameters
1766
and file contents. This may be different from the terminal encoding
1767
or the filesystem encoding.
1769
:param use_cache: Enable cache for detected encoding.
1770
(This parameter is turned on by default,
1771
and required only for selftesting)
1773
:return: A string defining the preferred user encoding
1775
global _cached_user_encoding
1776
if _cached_user_encoding is not None and use_cache:
1777
return _cached_user_encoding
1779
if sys.platform == 'darwin':
1780
# python locale.getpreferredencoding() always return
1781
# 'mac-roman' on darwin. That's a lie.
1782
sys.platform = 'posix'
1784
if os.environ.get('LANG', None) is None:
1785
# If LANG is not set, we end up with 'ascii', which is bad
1786
# ('mac-roman' is more than ascii), so we set a default which
1787
# will give us UTF-8 (which appears to work in all cases on
1788
# OSX). Users are still free to override LANG of course, as
1789
# long as it give us something meaningful. This work-around
1790
# *may* not be needed with python 3k and/or OSX 10.5, but will
1791
# work with them too -- vila 20080908
1792
os.environ['LANG'] = 'en_US.UTF-8'
1795
sys.platform = 'darwin'
1800
user_encoding = locale.getpreferredencoding()
1801
except locale.Error, e:
1802
sys.stderr.write('bzr: warning: %s\n'
1803
' Could not determine what text encoding to use.\n'
1804
' This error usually means your Python interpreter\n'
1805
' doesn\'t support the locale set by $LANG (%s)\n'
1806
" Continuing with ascii encoding.\n"
1807
% (e, os.environ.get('LANG')))
1808
user_encoding = 'ascii'
1810
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1811
# treat that as ASCII, and not support printing unicode characters to the
1814
# For python scripts run under vim, we get '', so also treat that as ASCII
1815
if user_encoding in (None, 'cp0', ''):
1816
user_encoding = 'ascii'
1820
codecs.lookup(user_encoding)
1822
sys.stderr.write('bzr: warning:'
1823
' unknown encoding %s.'
1824
' Continuing with ascii encoding.\n'
1827
user_encoding = 'ascii'
1830
_cached_user_encoding = user_encoding
1832
return user_encoding
1835
def get_host_name():
1836
"""Return the current unicode host name.
1838
This is meant to be used in place of socket.gethostname() because that
1839
behaves inconsistently on different platforms.
1841
if sys.platform == "win32":
1843
return win32utils.get_host_name()
1846
return socket.gethostname().decode(get_user_encoding())
1849
def recv_all(socket, bytes):
1850
"""Receive an exact number of bytes.
1852
Regular Socket.recv() may return less than the requested number of bytes,
1853
dependning on what's in the OS buffer. MSG_WAITALL is not available
1854
on all platforms, but this should work everywhere. This will return
1855
less than the requested amount if the remote end closes.
1857
This isn't optimized and is intended mostly for use in testing.
1860
while len(b) < bytes:
1861
new = until_no_eintr(socket.recv, bytes - len(b))
1868
def send_all(socket, bytes, report_activity=None):
1869
"""Send all bytes on a socket.
1871
Regular socket.sendall() can give socket error 10053 on Windows. This
1872
implementation sends no more than 64k at a time, which avoids this problem.
1874
:param report_activity: Call this as bytes are read, see
1875
Transport._report_activity
1878
for pos in xrange(0, len(bytes), chunk_size):
1879
block = bytes[pos:pos+chunk_size]
1880
if report_activity is not None:
1881
report_activity(len(block), 'write')
1882
until_no_eintr(socket.sendall, block)
1885
def dereference_path(path):
1886
"""Determine the real path to a file.
1888
All parent elements are dereferenced. But the file itself is not
1890
:param path: The original path. May be absolute or relative.
1891
:return: the real path *to* the file
1893
parent, base = os.path.split(path)
1894
# The pathjoin for '.' is a workaround for Python bug #1213894.
1895
# (initial path components aren't dereferenced)
1896
return pathjoin(realpath(pathjoin('.', parent)), base)
1899
def supports_mapi():
1900
"""Return True if we can use MAPI to launch a mail client."""
1901
return sys.platform == "win32"
1904
def resource_string(package, resource_name):
1905
"""Load a resource from a package and return it as a string.
1907
Note: Only packages that start with bzrlib are currently supported.
1909
This is designed to be a lightweight implementation of resource
1910
loading in a way which is API compatible with the same API from
1912
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1913
If and when pkg_resources becomes a standard library, this routine
1916
# Check package name is within bzrlib
1917
if package == "bzrlib":
1918
resource_relpath = resource_name
1919
elif package.startswith("bzrlib."):
1920
package = package[len("bzrlib."):].replace('.', os.sep)
1921
resource_relpath = pathjoin(package, resource_name)
1923
raise errors.BzrError('resource package %s not in bzrlib' % package)
1925
# Map the resource to a file and read its contents
1926
base = dirname(bzrlib.__file__)
1927
if getattr(sys, 'frozen', None): # bzr.exe
1928
base = abspath(pathjoin(base, '..', '..'))
1929
filename = pathjoin(base, resource_relpath)
1930
return open(filename, 'rU').read()
1933
def file_kind_from_stat_mode_thunk(mode):
1934
global file_kind_from_stat_mode
1935
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1937
from bzrlib._readdir_pyx import UTF8DirReader
1938
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1939
except ImportError, e:
1940
# This is one time where we won't warn that an extension failed to
1941
# load. The extension is never available on Windows anyway.
1942
from bzrlib._readdir_py import (
1943
_kind_from_mode as file_kind_from_stat_mode
1945
return file_kind_from_stat_mode(mode)
1946
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1949
def file_kind(f, _lstat=os.lstat):
1951
return file_kind_from_stat_mode(_lstat(f).st_mode)
1953
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1954
raise errors.NoSuchFile(f)
1958
def until_no_eintr(f, *a, **kw):
1959
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
1960
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1964
except (IOError, OSError), e:
1965
if e.errno == errno.EINTR:
1969
def re_compile_checked(re_string, flags=0, where=""):
1970
"""Return a compiled re, or raise a sensible error.
1972
This should only be used when compiling user-supplied REs.
1974
:param re_string: Text form of regular expression.
1975
:param flags: eg re.IGNORECASE
1976
:param where: Message explaining to the user the context where
1977
it occurred, eg 'log search filter'.
1979
# from https://bugs.launchpad.net/bzr/+bug/251352
1981
re_obj = re.compile(re_string, flags)
1986
where = ' in ' + where
1987
# despite the name 'error' is a type
1988
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1989
% (where, re_string, e))
1992
if sys.platform == "win32":
1995
return msvcrt.getch()
2000
fd = sys.stdin.fileno()
2001
settings = termios.tcgetattr(fd)
2004
ch = sys.stdin.read(1)
2006
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2010
if sys.platform == 'linux2':
2011
def _local_concurrency():
2013
prefix = 'processor'
2014
for line in file('/proc/cpuinfo', 'rb'):
2015
if line.startswith(prefix):
2016
concurrency = int(line[line.find(':')+1:]) + 1
2018
elif sys.platform == 'darwin':
2019
def _local_concurrency():
2020
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2021
stdout=subprocess.PIPE).communicate()[0]
2022
elif sys.platform[0:7] == 'freebsd':
2023
def _local_concurrency():
2024
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2025
stdout=subprocess.PIPE).communicate()[0]
2026
elif sys.platform == 'sunos5':
2027
def _local_concurrency():
2028
return subprocess.Popen(['psrinfo', '-p',],
2029
stdout=subprocess.PIPE).communicate()[0]
2030
elif sys.platform == "win32":
2031
def _local_concurrency():
2032
# This appears to return the number of cores.
2033
return os.environ.get('NUMBER_OF_PROCESSORS')
2035
def _local_concurrency():
2040
_cached_local_concurrency = None
2042
def local_concurrency(use_cache=True):
2043
"""Return how many processes can be run concurrently.
2045
Rely on platform specific implementations and default to 1 (one) if
2046
anything goes wrong.
2048
global _cached_local_concurrency
2050
if _cached_local_concurrency is not None and use_cache:
2051
return _cached_local_concurrency
2053
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2054
if concurrency is None:
2056
concurrency = _local_concurrency()
2057
except (OSError, IOError):
2060
concurrency = int(concurrency)
2061
except (TypeError, ValueError):
2064
_cached_concurrency = concurrency