1
# Copyright (C) 2005-2011 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
25
from .lazy_import import lazy_import
26
lazy_import(globals(), """
27
from datetime import datetime
33
# We need to import both shutil and rmtree as we export the later on posix
34
# and need the former on windows
36
from shutil import rmtree
39
# We need to import both tempfile and mkdtemp as we export the later on posix
40
# and need the former on windows
42
from tempfile import mkdtemp
50
from breezy.i18n import gettext
66
# On win32, O_BINARY is used to indicate the file should
67
# be opened in binary mode, rather than text mode.
68
# On other platforms, O_BINARY doesn't exist, because
69
# they always open in binary mode, so it is okay to
70
# OR with 0 on those platforms.
71
# O_NOINHERIT and O_TEXT exists only on win32 too.
72
O_BINARY = getattr(os, 'O_BINARY', 0)
73
O_TEXT = getattr(os, 'O_TEXT', 0)
74
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
77
class UnsupportedTimezoneFormat(errors.BzrError):
79
_fmt = ('Unsupported timezone format "%(timezone)s", '
80
'options are "utc", "original", "local".')
82
def __init__(self, timezone):
83
self.timezone = timezone
86
def get_unicode_argv():
90
def make_readonly(filename):
91
"""Make a filename read-only."""
92
mod = os.lstat(filename).st_mode
93
if not stat.S_ISLNK(mod):
95
chmod_if_possible(filename, mod)
98
def make_writable(filename):
99
mod = os.lstat(filename).st_mode
100
if not stat.S_ISLNK(mod):
102
chmod_if_possible(filename, mod)
105
def chmod_if_possible(filename, mode):
106
# Set file mode if that can be safely done.
107
# Sometimes even on unix the filesystem won't allow it - see
108
# https://bugs.launchpad.net/bzr/+bug/606537
110
# It is probably faster to just do the chmod, rather than
111
# doing a stat, and then trying to compare
112
os.chmod(filename, mode)
113
except (IOError, OSError) as e:
114
# Permission/access denied seems to commonly happen on smbfs; there's
115
# probably no point warning about it.
116
# <https://bugs.launchpad.net/bzr/+bug/606537>
117
if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
118
trace.mutter("ignore error on chmod of %r: %r" % (
124
def minimum_path_selection(paths):
125
"""Return the smallset subset of paths which are outside paths.
127
:param paths: A container (and hence not None) of paths.
128
:return: A set of paths sufficient to include everything in paths via
129
is_inside, drawn from the paths parameter.
135
if isinstance(path, bytes):
136
return path.split(b'/')
138
return path.split('/')
139
sorted_paths = sorted(list(paths), key=sort_key)
141
search_paths = [sorted_paths[0]]
142
for path in sorted_paths[1:]:
143
if not is_inside(search_paths[-1], path):
144
# This path is unique, add it
145
search_paths.append(path)
147
return set(search_paths)
154
"""Return a quoted filename filename
156
This previously used backslash quoting, but that works poorly on
158
# TODO: I'm not really sure this is the best format either.x
160
if _QUOTE_RE is None:
161
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
163
if _QUOTE_RE.search(f):
169
_directory_kind = 'directory'
173
"""Return the current umask"""
174
# Assume that people aren't messing with the umask while running
175
# XXX: This is not thread safe, but there is no way to get the
176
# umask without setting it
184
_directory_kind: "/",
186
'tree-reference': '+',
190
def kind_marker(kind):
192
return _kind_marker_map[kind]
194
# Slightly faster than using .get(, '') when the common case is that
199
lexists = getattr(os.path, 'lexists', None)
203
stat = getattr(os, 'lstat', os.stat)
207
if e.errno == errno.ENOENT:
210
raise errors.BzrError(
211
gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
214
def fancy_rename(old, new, rename_func, unlink_func):
215
"""A fancy rename, when you don't have atomic rename.
217
:param old: The old path, to rename from
218
:param new: The new path, to rename to
219
:param rename_func: The potentially non-atomic rename function
220
:param unlink_func: A way to delete the target file if the full rename
223
# sftp rename doesn't allow overwriting, so play tricks:
224
base = os.path.basename(new)
225
dirname = os.path.dirname(new)
226
# callers use different encodings for the paths so the following MUST
227
# respect that. We rely on python upcasting to unicode if new is unicode
228
# and keeping a str if not.
229
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
230
os.getpid(), rand_chars(10))
231
tmp_name = pathjoin(dirname, tmp_name)
233
# Rename the file out of the way, but keep track if it didn't exist
234
# We don't want to grab just any exception
235
# something like EACCES should prevent us from continuing
236
# The downside is that the rename_func has to throw an exception
237
# with an errno = ENOENT, or NoSuchFile
240
rename_func(new, tmp_name)
241
except (errors.NoSuchFile,):
244
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
245
# function raises an IOError with errno is None when a rename fails.
246
# This then gets caught here.
247
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
249
except Exception as e:
250
if (getattr(e, 'errno', None) is None
251
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
258
# This may throw an exception, in which case success will
260
rename_func(old, new)
262
except (IOError, OSError) as e:
263
# source and target may be aliases of each other (e.g. on a
264
# case-insensitive filesystem), so we may have accidentally renamed
265
# source by when we tried to rename target
266
if (file_existed and e.errno in (None, errno.ENOENT)
267
and old.lower() == new.lower()):
268
# source and target are the same file on a case-insensitive
269
# filesystem, so we don't generate an exception
275
# If the file used to exist, rename it back into place
276
# otherwise just delete it from the tmp location
278
unlink_func(tmp_name)
280
rename_func(tmp_name, new)
283
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
284
# choke on a Unicode string containing a relative path if
285
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
287
def _posix_abspath(path):
288
# jam 20060426 rather than encoding to fsencoding
289
# copy posixpath.abspath, but use os.getcwdu instead
290
if not posixpath.isabs(path):
291
path = posixpath.join(getcwd(), path)
292
return _posix_normpath(path)
295
def _posix_realpath(path):
296
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
299
def _posix_normpath(path):
300
path = posixpath.normpath(path)
301
# Bug 861008: posixpath.normpath() returns a path normalized according to
302
# the POSIX standard, which stipulates (for compatibility reasons) that two
303
# leading slashes must not be simplified to one, and only if there are 3 or
304
# more should they be simplified as one. So we treat the leading 2 slashes
305
# as a special case here by simply removing the first slash, as we consider
306
# that breaking POSIX compatibility for this obscure feature is acceptable.
307
# This is not a paranoid precaution, as we notably get paths like this when
308
# the repo is hosted at the root of the filesystem, i.e. in "/".
309
if path.startswith('//'):
314
def _posix_path_from_environ(key):
315
"""Get unicode path from `key` in environment or None if not present
317
Note that posix systems use arbitrary byte strings for filesystem objects,
318
so a path that raises BadFilenameEncoding here may still be accessible.
320
return os.environ.get(key, None)
323
def _posix_get_home_dir():
324
"""Get the home directory of the current user as a unicode path"""
325
path = posixpath.expanduser("~")
327
return path.decode(_fs_enc)
328
except AttributeError:
330
except UnicodeDecodeError:
331
raise errors.BadFilenameEncoding(path, _fs_enc)
334
def _posix_getuser_unicode():
335
"""Get username from environment or password database as unicode"""
336
return getpass.getuser()
339
def _win32_fixdrive(path):
340
"""Force drive letters to be consistent.
342
win32 is inconsistent whether it returns lower or upper case
343
and even if it was consistent the user might type the other
344
so we force it to uppercase
345
running python.exe under cmd.exe return capital C:\\
346
running win32 python inside a cygwin shell returns lowercase c:\\
348
drive, path = ntpath.splitdrive(path)
349
return drive.upper() + path
352
def _win32_abspath(path):
353
# Real ntpath.abspath doesn't have a problem with a unicode cwd
354
return _win32_fixdrive(ntpath.abspath(path).replace('\\', '/'))
357
def _win32_realpath(path):
358
# Real ntpath.realpath doesn't have a problem with a unicode cwd
359
return _win32_fixdrive(ntpath.realpath(path).replace('\\', '/'))
362
def _win32_pathjoin(*args):
363
return ntpath.join(*args).replace('\\', '/')
366
def _win32_normpath(path):
367
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
371
return _win32_fixdrive(_getcwd().replace('\\', '/'))
374
def _win32_mkdtemp(*args, **kwargs):
375
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
378
def _win32_rename(old, new):
379
"""We expect to be able to atomically replace 'new' with old.
381
On win32, if new exists, it must be moved out of the way first,
385
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
387
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
388
# If we try to rename a non-existant file onto cwd, we get
389
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
390
# if the old path doesn't exist, sometimes we get EACCES
391
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
397
return unicodedata.normalize('NFC', _getcwd())
400
def _rename_wrap_exception(rename_func):
401
"""Adds extra information to any exceptions that come from rename().
403
The exception has an updated message and 'old_filename' and 'new_filename'
407
def _rename_wrapper(old, new):
409
rename_func(old, new)
411
detailed_error = OSError(e.errno, e.strerror +
412
" [occurred when renaming '%s' to '%s']" %
414
detailed_error.old_filename = old
415
detailed_error.new_filename = new
418
return _rename_wrapper
424
# Default rename wraps os.rename()
425
rename = _rename_wrap_exception(os.rename)
427
# Default is to just use the python builtins, but these can be rebound on
428
# particular platforms.
429
abspath = _posix_abspath
430
realpath = _posix_realpath
431
pathjoin = os.path.join
432
normpath = _posix_normpath
433
path_from_environ = _posix_path_from_environ
434
_get_home_dir = _posix_get_home_dir
435
getuser_unicode = _posix_getuser_unicode
437
dirname = os.path.dirname
438
basename = os.path.basename
439
split = os.path.split
440
splitext = os.path.splitext
441
# These were already lazily imported into local scope
442
# mkdtemp = tempfile.mkdtemp
443
# rmtree = shutil.rmtree
452
MIN_ABS_PATHLENGTH = 1
455
if sys.platform == 'win32':
456
abspath = _win32_abspath
457
realpath = _win32_realpath
458
pathjoin = _win32_pathjoin
459
normpath = _win32_normpath
460
getcwd = _win32_getcwd
461
mkdtemp = _win32_mkdtemp
462
rename = _rename_wrap_exception(_win32_rename)
464
from . import _walkdirs_win32
468
lstat = _walkdirs_win32.lstat
469
fstat = _walkdirs_win32.fstat
470
wrap_stat = _walkdirs_win32.wrap_stat
472
MIN_ABS_PATHLENGTH = 3
474
def _win32_delete_readonly(function, path, excinfo):
475
"""Error handler for shutil.rmtree function [for win32]
476
Helps to remove files and dirs marked as read-only.
478
exception = excinfo[1]
479
if function in (os.remove, os.rmdir) \
480
and isinstance(exception, OSError) \
481
and exception.errno == errno.EACCES:
487
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
488
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
489
return shutil.rmtree(path, ignore_errors, onerror)
491
get_unicode_argv = getattr(win32utils, 'get_unicode_argv', get_unicode_argv)
492
path_from_environ = win32utils.get_environ_unicode
493
_get_home_dir = win32utils.get_home_location
494
getuser_unicode = win32utils.get_user_name
496
elif sys.platform == 'darwin':
500
def get_terminal_encoding(trace=False):
501
"""Find the best encoding for printing to the screen.
503
This attempts to check both sys.stdout and sys.stdin to see
504
what encoding they are in, and if that fails it falls back to
505
osutils.get_user_encoding().
506
The problem is that on Windows, locale.getpreferredencoding()
507
is not the same encoding as that used by the console:
508
http://mail.python.org/pipermail/python-list/2003-May/162357.html
510
On my standard US Windows XP, the preferred encoding is
511
cp1252, but the console is cp437
513
:param trace: If True trace the selected encoding via mutter().
515
from .trace import mutter
516
output_encoding = getattr(sys.stdout, 'encoding', None)
517
if not output_encoding:
518
input_encoding = getattr(sys.stdin, 'encoding', None)
519
if not input_encoding:
520
output_encoding = get_user_encoding()
522
mutter('encoding stdout as osutils.get_user_encoding() %r',
525
output_encoding = input_encoding
527
mutter('encoding stdout as sys.stdin encoding %r',
531
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
532
if output_encoding == 'cp0':
533
# invalid encoding (cp0 means 'no codepage' on Windows)
534
output_encoding = get_user_encoding()
536
mutter('cp0 is invalid encoding.'
537
' encoding stdout as osutils.get_user_encoding() %r',
541
codecs.lookup(output_encoding)
543
sys.stderr.write('brz: warning:'
544
' unknown terminal encoding %s.\n'
545
' Using encoding %s instead.\n'
546
% (output_encoding, get_user_encoding())
548
output_encoding = get_user_encoding()
550
return output_encoding
553
def normalizepath(f):
554
if getattr(os.path, 'realpath', None) is not None:
558
[p, e] = os.path.split(f)
559
if e == "" or e == "." or e == "..":
562
return pathjoin(F(p), e)
566
"""True if f is an accessible directory."""
568
return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
574
"""True if f is a regular file."""
576
return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
582
"""True if f is a symlink."""
584
return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
589
def is_inside(dir, fname):
590
"""True if fname is inside dir.
592
The parameters should typically be passed to osutils.normpath first, so
593
that . and .. and repeated slashes are eliminated, and the separators
594
are canonical for the platform.
596
The empty string as a dir name is taken as top-of-tree and matches
599
# XXX: Most callers of this can actually do something smarter by
600
# looking at the inventory
607
if isinstance(dir, bytes):
608
if not dir.endswith(b'/'):
611
if not dir.endswith('/'):
614
return fname.startswith(dir)
617
def is_inside_any(dir_list, fname):
618
"""True if fname is inside any of given dirs."""
619
for dirname in dir_list:
620
if is_inside(dirname, fname):
625
def is_inside_or_parent_of_any(dir_list, fname):
626
"""True if fname is a child or a parent of any of the given files."""
627
for dirname in dir_list:
628
if is_inside(dirname, fname) or is_inside(fname, dirname):
633
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
634
report_activity=None, direction='read'):
635
"""Copy contents of one file to another.
637
The read_length can either be -1 to read to end-of-file (EOF) or
638
it can specify the maximum number of bytes to read.
640
The buff_size represents the maximum size for each read operation
641
performed on from_file.
643
:param report_activity: Call this as bytes are read, see
644
Transport._report_activity
645
:param direction: Will be passed to report_activity
647
:return: The number of bytes copied.
651
# read specified number of bytes
653
while read_length > 0:
654
num_bytes_to_read = min(read_length, buff_size)
656
block = from_file.read(num_bytes_to_read)
660
if report_activity is not None:
661
report_activity(len(block), direction)
664
actual_bytes_read = len(block)
665
read_length -= actual_bytes_read
666
length += actual_bytes_read
670
block = from_file.read(buff_size)
674
if report_activity is not None:
675
report_activity(len(block), direction)
681
def pump_string_file(bytes, file_handle, segment_size=None):
682
"""Write bytes to file_handle in many smaller writes.
684
:param bytes: The string to write.
685
:param file_handle: The file to write to.
687
# Write data in chunks rather than all at once, because very large
688
# writes fail on some platforms (e.g. Windows with SMB mounted
691
segment_size = 5242880 # 5MB
692
offsets = range(0, len(bytes), segment_size)
693
view = memoryview(bytes)
694
write = file_handle.write
695
for offset in offsets:
696
write(view[offset:offset + segment_size])
699
def file_iterator(input_file, readsize=32768):
701
b = input_file.read(readsize)
707
# GZ 2017-09-16: Makes sense in general for hexdigest() result to be text, but
708
# used as bytes through most interfaces so encode with this wrapper.
709
def _hexdigest(hashobj):
710
return hashobj.hexdigest().encode()
714
"""Calculate the hexdigest of an open file.
716
The file cursor should be already at the start.
728
def size_sha_file(f):
729
"""Calculate the size and hexdigest of an open file.
731
The file cursor should be already at the start and
732
the caller is responsible for closing the file afterwards.
743
return size, _hexdigest(s)
746
def sha_file_by_name(fname):
747
"""Calculate the SHA1 of a file by reading the full text"""
749
f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
752
b = os.read(f, 1 << 16)
760
def sha_strings(strings, _factory=sha):
761
"""Return the sha-1 of concatenation of strings"""
763
for string in strings:
768
def sha_string(f, _factory=sha):
769
# GZ 2017-09-16: Dodgy if factory is ever not sha, probably shouldn't be.
770
return _hexdigest(_factory(f))
773
def fingerprint_file(f):
775
return {'size': len(b),
776
'sha1': _hexdigest(sha(b))}
779
def compare_files(a, b):
780
"""Returns true if equal in contents"""
791
def local_time_offset(t=None):
792
"""Return offset of local zone from GMT, either at present or at time t."""
795
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
796
return offset.days * 86400 + offset.seconds
799
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
800
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
803
def format_date(t, offset=0, timezone='original', date_fmt=None,
805
"""Return a formatted date string.
807
:param t: Seconds since the epoch.
808
:param offset: Timezone offset in seconds east of utc.
809
:param timezone: How to display the time: 'utc', 'original' for the
810
timezone specified by offset, or 'local' for the process's current
812
:param date_fmt: strftime format.
813
:param show_offset: Whether to append the timezone.
815
(date_fmt, tt, offset_str) = \
816
_format_date(t, offset, timezone, date_fmt, show_offset)
817
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
818
date_str = time.strftime(date_fmt, tt)
819
return date_str + offset_str
822
# Cache of formatted offset strings
826
def format_date_with_offset_in_original_timezone(t, offset=0,
827
_cache=_offset_cache):
828
"""Return a formatted date string in the original timezone.
830
This routine may be faster then format_date.
832
:param t: Seconds since the epoch.
833
:param offset: Timezone offset in seconds east of utc.
837
tt = time.gmtime(t + offset)
838
date_fmt = _default_format_by_weekday_num[tt[6]]
839
date_str = time.strftime(date_fmt, tt)
840
offset_str = _cache.get(offset, None)
841
if offset_str is None:
842
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
843
_cache[offset] = offset_str
844
return date_str + offset_str
847
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
849
"""Return an unicode date string formatted according to the current locale.
851
:param t: Seconds since the epoch.
852
:param offset: Timezone offset in seconds east of utc.
853
:param timezone: How to display the time: 'utc', 'original' for the
854
timezone specified by offset, or 'local' for the process's current
856
:param date_fmt: strftime format.
857
:param show_offset: Whether to append the timezone.
859
(date_fmt, tt, offset_str) = \
860
_format_date(t, offset, timezone, date_fmt, show_offset)
861
date_str = time.strftime(date_fmt, tt)
862
if not isinstance(date_str, str):
863
date_str = date_str.decode(get_user_encoding(), 'replace')
864
return date_str + offset_str
867
def _format_date(t, offset, timezone, date_fmt, show_offset):
868
if timezone == 'utc':
871
elif timezone == 'original':
874
tt = time.gmtime(t + offset)
875
elif timezone == 'local':
876
tt = time.localtime(t)
877
offset = local_time_offset(t)
879
raise UnsupportedTimezoneFormat(timezone)
881
date_fmt = "%a %Y-%m-%d %H:%M:%S"
883
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
886
return (date_fmt, tt, offset_str)
889
def compact_date(when):
890
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
893
def format_delta(delta):
894
"""Get a nice looking string for a time delta.
896
:param delta: The time difference in seconds, can be positive or negative.
897
positive indicates time in the past, negative indicates time in the
898
future. (usually time.time() - stored_time)
899
:return: String formatted to show approximate resolution
905
direction = 'in the future'
909
if seconds < 90: # print seconds up to 90 seconds
911
return '%d second %s' % (seconds, direction,)
913
return '%d seconds %s' % (seconds, direction)
915
minutes = int(seconds / 60)
916
seconds -= 60 * minutes
921
if minutes < 90: # print minutes, seconds up to 90 minutes
923
return '%d minute, %d second%s %s' % (
924
minutes, seconds, plural_seconds, direction)
926
return '%d minutes, %d second%s %s' % (
927
minutes, seconds, plural_seconds, direction)
929
hours = int(minutes / 60)
930
minutes -= 60 * hours
937
return '%d hour, %d minute%s %s' % (hours, minutes,
938
plural_minutes, direction)
939
return '%d hours, %d minute%s %s' % (hours, minutes,
940
plural_minutes, direction)
944
"""Return size of given open file."""
945
return os.fstat(f.fileno())[stat.ST_SIZE]
948
# Alias os.urandom to support platforms (which?) without /dev/urandom and
949
# override if it doesn't work. Avoid checking on windows where there is
950
# significant initialisation cost that can be avoided for some bzr calls.
952
rand_bytes = os.urandom
954
if rand_bytes.__module__ != "nt":
957
except NotImplementedError:
958
# not well seeded, but better than nothing
963
s += chr(random.randint(0, 255))
968
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
972
"""Return a random string of num alphanumeric characters
974
The result only contains lowercase chars because it may be used on
975
case-insensitive filesystems.
978
for raw_byte in rand_bytes(num):
979
s += ALNUM[raw_byte % 36]
983
# TODO: We could later have path objects that remember their list
984
# decomposition (might be too tricksy though.)
987
"""Turn string into list of parts."""
988
use_bytes = isinstance(p, bytes)
989
if os.path.sep == '\\':
990
# split on either delimiter because people might use either on
993
ps = re.split(b'[\\\\/]', p)
995
ps = re.split(r'[\\/]', p)
1004
current_empty_dir = (b'.', b'')
1007
current_empty_dir = ('.', '')
1012
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
1013
elif f in current_empty_dir:
1022
if (f == '..') or (f is None) or (f == ''):
1023
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
1027
def parent_directories(filename):
1028
"""Return the list of parent directories, deepest first.
1030
For example, parent_directories("a/b/c") -> ["a/b", "a"].
1033
parts = splitpath(dirname(filename))
1035
parents.append(joinpath(parts))
1040
_extension_load_failures = []
1043
def failed_to_load_extension(exception):
1044
"""Handle failing to load a binary extension.
1046
This should be called from the ImportError block guarding the attempt to
1047
import the native extension. If this function returns, the pure-Python
1048
implementation should be loaded instead::
1051
>>> import breezy._fictional_extension_pyx
1052
>>> except ImportError, e:
1053
>>> breezy.osutils.failed_to_load_extension(e)
1054
>>> import breezy._fictional_extension_py
1056
# NB: This docstring is just an example, not a doctest, because doctest
1057
# currently can't cope with the use of lazy imports in this namespace --
1060
# This currently doesn't report the failure at the time it occurs, because
1061
# they tend to happen very early in startup when we can't check config
1062
# files etc, and also we want to report all failures but not spam the user
1064
exception_str = str(exception)
1065
if exception_str not in _extension_load_failures:
1066
trace.mutter("failed to load compiled extension: %s" % exception_str)
1067
_extension_load_failures.append(exception_str)
1070
def report_extension_load_failures():
1071
if not _extension_load_failures:
1073
if config.GlobalConfig().suppress_warning('missing_extensions'):
1075
# the warnings framework should by default show this only once
1076
from .trace import warning
1078
"brz: warning: some compiled extensions could not be loaded; "
1079
"see ``brz help missing-extensions``")
1080
# we no longer show the specific missing extensions here, because it makes
1081
# the message too long and scary - see
1082
# https://bugs.launchpad.net/bzr/+bug/430529
1086
from ._chunks_to_lines_pyx import chunks_to_lines
1087
except ImportError as e:
1088
failed_to_load_extension(e)
1089
from ._chunks_to_lines_py import chunks_to_lines
1093
"""Split s into lines, but without removing the newline characters."""
1094
# Trivially convert a fulltext into a 'chunked' representation, and let
1095
# chunks_to_lines do the heavy lifting.
1096
if isinstance(s, bytes):
1097
# chunks_to_lines only supports 8-bit strings
1098
return chunks_to_lines([s])
1100
return _split_lines(s)
1103
def _split_lines(s):
1104
"""Split s into lines, but without removing the newline characters.
1106
This supports Unicode or plain string objects.
1108
nl = b'\n' if isinstance(s, bytes) else u'\n'
1110
result = [line + nl for line in lines[:-1]]
1112
result.append(lines[-1])
1116
def hardlinks_good():
1117
return sys.platform not in ('win32', 'cygwin', 'darwin')
1120
def link_or_copy(src, dest):
1121
"""Hardlink a file, or copy it if it can't be hardlinked."""
1122
if not hardlinks_good():
1123
shutil.copyfile(src, dest)
1127
except (OSError, IOError) as e:
1128
if e.errno != errno.EXDEV:
1130
shutil.copyfile(src, dest)
1133
def delete_any(path):
1134
"""Delete a file, symlink or directory.
1136
Will delete even if readonly.
1139
_delete_file_or_dir(path)
1140
except (OSError, IOError) as e:
1141
if e.errno in (errno.EPERM, errno.EACCES):
1142
# make writable and try again
1145
except (OSError, IOError):
1147
_delete_file_or_dir(path)
1152
def _delete_file_or_dir(path):
1153
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1154
# Forgiveness than Permission (EAFP) because:
1155
# - root can damage a solaris file system by using unlink,
1156
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1157
# EACCES, OSX: EPERM) when invoked on a directory.
1158
if isdir(path): # Takes care of symlinks
1165
if getattr(os, 'symlink', None) is not None:
1171
def has_hardlinks():
1172
if getattr(os, 'link', None) is not None:
1178
def host_os_dereferences_symlinks():
1179
return (has_symlinks()
1180
and sys.platform not in ('cygwin', 'win32'))
1183
def readlink(abspath):
1184
"""Return a string representing the path to which the symbolic link points.
1186
:param abspath: The link absolute unicode path.
1188
This his guaranteed to return the symbolic link in unicode in all python
1191
link = abspath.encode(_fs_enc)
1192
target = os.readlink(link)
1193
target = target.decode(_fs_enc)
1197
def contains_whitespace(s):
1198
"""True if there are any whitespace characters in s."""
1199
# string.whitespace can include '\xa0' in certain locales, because it is
1200
# considered "non-breaking-space" as part of ISO-8859-1. But it
1201
# 1) Isn't a breaking whitespace
1202
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1204
# 3) '\xa0' isn't unicode safe since it is >128.
1206
if isinstance(s, str):
1209
ws = (b' ', b'\t', b'\n', b'\r', b'\v', b'\f')
1217
def contains_linebreaks(s):
1218
"""True if there is any vertical whitespace in s."""
1226
def relpath(base, path):
1227
"""Return path relative to base, or raise PathNotChild exception.
1229
The path may be either an absolute path or a path relative to the
1230
current working directory.
1232
os.path.commonprefix (python2.4) has a bad bug that it works just
1233
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
1234
avoids that problem.
1236
NOTE: `base` should not have a trailing slash otherwise you'll get
1237
PathNotChild exceptions regardless of `path`.
1240
if len(base) < MIN_ABS_PATHLENGTH:
1241
# must have space for e.g. a drive letter
1242
raise ValueError(gettext('%r is too short to calculate a relative path')
1250
if len(head) <= len(base) and head != base:
1251
raise errors.PathNotChild(rp, base)
1254
head, tail = split(head)
1259
return pathjoin(*reversed(s))
1264
def _cicp_canonical_relpath(base, path):
1265
"""Return the canonical path relative to base.
1267
Like relpath, but on case-insensitive-case-preserving file-systems, this
1268
will return the relpath as stored on the file-system rather than in the
1269
case specified in the input string, for all existing portions of the path.
1271
This will cause O(N) behaviour if called for every path in a tree; if you
1272
have a number of paths to convert, you should use canonical_relpaths().
1274
# TODO: it should be possible to optimize this for Windows by using the
1275
# win32 API FindFiles function to look for the specified name - but using
1276
# os.listdir() still gives us the correct, platform agnostic semantics in
1279
rel = relpath(base, path)
1280
# '.' will have been turned into ''
1284
abs_base = abspath(base)
1287
# use an explicit iterator so we can easily consume the rest on early exit.
1288
bit_iter = iter(rel.split('/'))
1289
for bit in bit_iter:
1292
next_entries = scandir(current)
1293
except OSError: # enoent, eperm, etc
1294
# We can't find this in the filesystem, so just append the
1296
current = pathjoin(current, bit, *list(bit_iter))
1298
for entry in next_entries:
1299
if lbit == entry.name.lower():
1300
current = entry.path
1303
# got to the end, nothing matched, so we just return the
1304
# non-existing bits as they were specified (the filename may be
1305
# the target of a move, for example).
1306
current = pathjoin(current, bit, *list(bit_iter))
1308
return current[len(abs_base):].lstrip('/')
1311
# XXX - TODO - we need better detection/integration of case-insensitive
1312
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1313
# filesystems), for example, so could probably benefit from the same basic
1314
# support there. For now though, only Windows and OSX get that support, and
1315
# they get it for *all* file-systems!
1316
if sys.platform in ('win32', 'darwin'):
1317
canonical_relpath = _cicp_canonical_relpath
1319
canonical_relpath = relpath
1322
def canonical_relpaths(base, paths):
1323
"""Create an iterable to canonicalize a sequence of relative paths.
1325
The intent is for this implementation to use a cache, vastly speeding
1326
up multiple transformations in the same directory.
1328
# but for now, we haven't optimized...
1329
return [canonical_relpath(base, p) for p in paths]
1332
def decode_filename(filename):
1333
"""Decode the filename using the filesystem encoding
1335
If it is unicode, it is returned.
1336
Otherwise it is decoded from the the filesystem's encoding. If decoding
1337
fails, a errors.BadFilenameEncoding exception is raised.
1339
if isinstance(filename, str):
1342
return filename.decode(_fs_enc)
1343
except UnicodeDecodeError:
1344
raise errors.BadFilenameEncoding(filename, _fs_enc)
1347
def safe_unicode(unicode_or_utf8_string):
1348
"""Coerce unicode_or_utf8_string into unicode.
1350
If it is unicode, it is returned.
1351
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1352
wrapped in a BzrBadParameterNotUnicode exception.
1354
if isinstance(unicode_or_utf8_string, str):
1355
return unicode_or_utf8_string
1357
return unicode_or_utf8_string.decode('utf8')
1358
except UnicodeDecodeError:
1359
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1362
def safe_utf8(unicode_or_utf8_string):
1363
"""Coerce unicode_or_utf8_string to a utf8 string.
1365
If it is a str, it is returned.
1366
If it is Unicode, it is encoded into a utf-8 string.
1368
if isinstance(unicode_or_utf8_string, bytes):
1369
# TODO: jam 20070209 This is overkill, and probably has an impact on
1370
# performance if we are dealing with lots of apis that want a
1373
# Make sure it is a valid utf-8 string
1374
unicode_or_utf8_string.decode('utf-8')
1375
except UnicodeDecodeError:
1376
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1377
return unicode_or_utf8_string
1378
return unicode_or_utf8_string.encode('utf-8')
1381
def safe_revision_id(unicode_or_utf8_string):
1382
"""Revision ids should now be utf8, but at one point they were unicode.
1384
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1386
:return: None or a utf8 revision id.
1388
if (unicode_or_utf8_string is None
1389
or unicode_or_utf8_string.__class__ == bytes):
1390
return unicode_or_utf8_string
1391
raise TypeError('Unicode revision ids are no longer supported. '
1392
'Revision id generators should be creating utf8 revision '
1396
def safe_file_id(unicode_or_utf8_string):
1397
"""File ids should now be utf8, but at one point they were unicode.
1399
This is the same as safe_utf8, except it uses the cached encode functions
1400
to save a little bit of performance.
1402
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1404
:return: None or a utf8 file id.
1406
if (unicode_or_utf8_string is None
1407
or unicode_or_utf8_string.__class__ == bytes):
1408
return unicode_or_utf8_string
1409
raise TypeError('Unicode file ids are no longer supported. '
1410
'File id generators should be creating utf8 file ids.')
1413
_platform_normalizes_filenames = False
1414
if sys.platform == 'darwin':
1415
_platform_normalizes_filenames = True
1418
def normalizes_filenames():
1419
"""Return True if this platform normalizes unicode filenames.
1423
return _platform_normalizes_filenames
1426
def _accessible_normalized_filename(path):
1427
"""Get the unicode normalized path, and if you can access the file.
1429
On platforms where the system normalizes filenames (Mac OSX),
1430
you can access a file by any path which will normalize correctly.
1431
On platforms where the system does not normalize filenames
1432
(everything else), you have to access a file by its exact path.
1434
Internally, bzr only supports NFC normalization, since that is
1435
the standard for XML documents.
1437
So return the normalized path, and a flag indicating if the file
1438
can be accessed by that path.
1441
if isinstance(path, bytes):
1442
path = path.decode(sys.getfilesystemencoding())
1443
return unicodedata.normalize('NFC', path), True
1446
def _inaccessible_normalized_filename(path):
1447
__doc__ = _accessible_normalized_filename.__doc__
1449
if isinstance(path, bytes):
1450
path = path.decode(sys.getfilesystemencoding())
1451
normalized = unicodedata.normalize('NFC', path)
1452
return normalized, normalized == path
1455
if _platform_normalizes_filenames:
1456
normalized_filename = _accessible_normalized_filename
1458
normalized_filename = _inaccessible_normalized_filename
1461
def set_signal_handler(signum, handler, restart_syscall=True):
1462
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1463
on platforms that support that.
1465
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1466
automatically restart (by calling `signal.siginterrupt(signum,
1467
False)`). May be ignored if the feature is not available on this
1468
platform or Python version.
1472
siginterrupt = signal.siginterrupt
1474
# This python implementation doesn't provide signal support, hence no
1477
except AttributeError:
1478
# siginterrupt doesn't exist on this platform, or for this version
1480
def siginterrupt(signum, flag): return None
1482
def sig_handler(*args):
1483
# Python resets the siginterrupt flag when a signal is
1484
# received. <http://bugs.python.org/issue8354>
1485
# As a workaround for some cases, set it back the way we want it.
1486
siginterrupt(signum, False)
1487
# Now run the handler function passed to set_signal_handler.
1490
sig_handler = handler
1491
old_handler = signal.signal(signum, sig_handler)
1493
siginterrupt(signum, False)
1497
default_terminal_width = 80
1498
"""The default terminal width for ttys.
1500
This is defined so that higher levels can share a common fallback value when
1501
terminal_width() returns None.
1504
# Keep some state so that terminal_width can detect if _terminal_size has
1505
# returned a different size since the process started. See docstring and
1506
# comments of terminal_width for details.
1507
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1508
_terminal_size_state = 'no_data'
1509
_first_terminal_size = None
1512
def terminal_width():
1513
"""Return terminal width.
1515
None is returned if the width can't established precisely.
1518
- if BRZ_COLUMNS is set, returns its value
1519
- if there is no controlling terminal, returns None
1520
- query the OS, if the queried size has changed since the last query,
1522
- if COLUMNS is set, returns its value,
1523
- if the OS has a value (even though it's never changed), return its value.
1525
From there, we need to query the OS to get the size of the controlling
1528
On Unices we query the OS by:
1529
- get termios.TIOCGWINSZ
1530
- if an error occurs or a negative value is obtained, returns None
1532
On Windows we query the OS by:
1533
- win32utils.get_console_size() decides,
1534
- returns None on error (provided default value)
1536
# Note to implementors: if changing the rules for determining the width,
1537
# make sure you've considered the behaviour in these cases:
1538
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1539
# - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1541
# - (add more interesting cases here, if you find any)
1542
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1543
# but we don't want to register a signal handler because it is impossible
1544
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1545
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1546
# time so we can notice if the reported size has changed, which should have
1549
# If BRZ_COLUMNS is set, take it, user is always right
1550
# Except if they specified 0 in which case, impose no limit here
1552
width = int(os.environ['BRZ_COLUMNS'])
1553
except (KeyError, ValueError):
1555
if width is not None:
1561
isatty = getattr(sys.stdout, 'isatty', None)
1562
if isatty is None or not isatty():
1563
# Don't guess, setting BRZ_COLUMNS is the recommended way to override.
1567
width, height = os_size = _terminal_size(None, None)
1568
global _first_terminal_size, _terminal_size_state
1569
if _terminal_size_state == 'no_data':
1570
_first_terminal_size = os_size
1571
_terminal_size_state = 'unchanged'
1572
elif (_terminal_size_state == 'unchanged' and
1573
_first_terminal_size != os_size):
1574
_terminal_size_state = 'changed'
1576
# If the OS claims to know how wide the terminal is, and this value has
1577
# ever changed, use that.
1578
if _terminal_size_state == 'changed':
1579
if width is not None and width > 0:
1582
# If COLUMNS is set, use it.
1584
return int(os.environ['COLUMNS'])
1585
except (KeyError, ValueError):
1588
# Finally, use an unchanged size from the OS, if we have one.
1589
if _terminal_size_state == 'unchanged':
1590
if width is not None and width > 0:
1593
# The width could not be determined.
1597
def _win32_terminal_size(width, height):
1598
width, height = win32utils.get_console_size(
1599
defaultx=width, defaulty=height)
1600
return width, height
1603
def _ioctl_terminal_size(width, height):
1608
s = struct.pack('HHHH', 0, 0, 0, 0)
1609
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1610
height, width = struct.unpack('HHHH', x)[0:2]
1611
except (IOError, AttributeError):
1613
return width, height
1616
_terminal_size = None
1617
"""Returns the terminal size as (width, height).
1619
:param width: Default value for width.
1620
:param height: Default value for height.
1622
This is defined specifically for each OS and query the size of the controlling
1623
terminal. If any error occurs, the provided default values should be returned.
1625
if sys.platform == 'win32':
1626
_terminal_size = _win32_terminal_size
1628
_terminal_size = _ioctl_terminal_size
1631
def supports_executable(path):
1632
"""Return if filesystem at path supports executable bit.
1634
:param path: Path for which to check the file system
1635
:return: boolean indicating whether executable bit can be stored/relied upon
1637
if sys.platform == 'win32':
1640
fs_type = get_fs_type(path)
1641
except errors.DependencyNotPresent as e:
1642
trace.mutter('Unable to get fs type for %r: %s', path, e)
1644
if fs_type in ('vfat', 'ntfs'):
1645
# filesystems known to not support executable bit
1650
def supports_symlinks(path):
1651
"""Return if the filesystem at path supports the creation of symbolic links.
1654
if not has_symlinks():
1657
fs_type = get_fs_type(path)
1658
except errors.DependencyNotPresent as e:
1659
trace.mutter('Unable to get fs type for %r: %s', path, e)
1661
if fs_type in ('vfat', 'ntfs'):
1662
# filesystems known to not support symlinks
1667
def supports_posix_readonly():
1668
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1670
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1671
directory controls creation/deletion, etc.
1673
And under win32, readonly means that the directory itself cannot be
1674
deleted. The contents of a readonly directory can be changed, unlike POSIX
1675
where files in readonly directories cannot be added, deleted or renamed.
1677
return sys.platform != "win32"
1680
def set_or_unset_env(env_variable, value):
1681
"""Modify the environment, setting or removing the env_variable.
1683
:param env_variable: The environment variable in question
1684
:param value: The value to set the environment to. If None, then
1685
the variable will be removed.
1686
:return: The original value of the environment variable.
1688
orig_val = os.environ.get(env_variable)
1690
if orig_val is not None:
1691
del os.environ[env_variable]
1693
os.environ[env_variable] = value
1697
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1700
def check_legal_path(path):
1701
"""Check whether the supplied path is legal.
1702
This is only required on Windows, so we don't test on other platforms
1705
if sys.platform != "win32":
1707
if _validWin32PathRE.match(path) is None:
1708
raise errors.IllegalPath(path)
1711
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1715
scandir = os.scandir
1716
except AttributeError: # Python < 3
1717
lazy_import(globals(), """\
1718
from scandir import scandir
1722
def _is_error_enotdir(e):
1723
"""Check if this exception represents ENOTDIR.
1725
Unfortunately, python is very inconsistent about the exception
1726
here. The cases are:
1727
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1728
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1729
which is the windows error code.
1730
3) Windows, Python2.5 uses errno == EINVAL and
1731
winerror == ERROR_DIRECTORY
1733
:param e: An Exception object (expected to be OSError with an errno
1734
attribute, but we should be able to cope with anything)
1735
:return: True if this represents an ENOTDIR error. False otherwise.
1737
en = getattr(e, 'errno', None)
1738
if (en == errno.ENOTDIR or
1739
(sys.platform == 'win32' and
1740
(en == _WIN32_ERROR_DIRECTORY or
1742
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1748
def walkdirs(top, prefix=""):
1749
"""Yield data about all the directories in a tree.
1751
This yields all the data about the contents of a directory at a time.
1752
After each directory has been yielded, if the caller has mutated the list
1753
to exclude some directories, they are then not descended into.
1755
The data yielded is of the form:
1756
((directory-relpath, directory-path-from-top),
1757
[(relpath, basename, kind, lstat, path-from-top), ...]),
1758
- directory-relpath is the relative path of the directory being returned
1759
with respect to top. prefix is prepended to this.
1760
- directory-path-from-root is the path including top for this directory.
1761
It is suitable for use with os functions.
1762
- relpath is the relative path within the subtree being walked.
1763
- basename is the basename of the path
1764
- kind is the kind of the file now. If unknown then the file is not
1765
present within the tree - but it may be recorded as versioned. See
1767
- lstat is the stat data *if* the file was statted.
1768
- planned, not implemented:
1769
path_from_tree_root is the path from the root of the tree.
1771
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1772
allows one to walk a subtree but get paths that are relative to a tree
1774
:return: an iterator over the dirs.
1776
# TODO there is a bit of a smell where the results of the directory-
1777
# summary in this, and the path from the root, may not agree
1778
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1779
# potentially confusing output. We should make this more robust - but
1780
# not at a speed cost. RBC 20060731
1781
_directory = _directory_kind
1782
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1784
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1785
relroot, _, _, _, top = pending.pop()
1787
relprefix = relroot + u'/'
1790
top_slash = top + u'/'
1794
for entry in scandir(top):
1795
name = decode_filename(entry.name)
1796
statvalue = entry.stat(follow_symlinks=False)
1797
kind = file_kind_from_stat_mode(statvalue.st_mode)
1798
dirblock.append((relprefix + name, name, kind, statvalue, entry.path))
1799
except OSError as e:
1800
if not _is_error_enotdir(e):
1802
except UnicodeDecodeError as e:
1803
raise errors.BadFilenameEncoding(e.object, _fs_enc)
1805
yield (relroot, top), dirblock
1807
# push the user specified dirs from dirblock
1808
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1811
class DirReader(object):
1812
"""An interface for reading directories."""
1814
def top_prefix_to_starting_dir(self, top, prefix=""):
1815
"""Converts top and prefix to a starting dir entry
1817
:param top: A utf8 path
1818
:param prefix: An optional utf8 path to prefix output relative paths
1820
:return: A tuple starting with prefix, and ending with the native
1823
raise NotImplementedError(self.top_prefix_to_starting_dir)
1825
def read_dir(self, prefix, top):
1826
"""Read a specific dir.
1828
:param prefix: A utf8 prefix to be preprended to the path basenames.
1829
:param top: A natively encoded path to read.
1830
:return: A list of the directories contents. Each item contains:
1831
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1833
raise NotImplementedError(self.read_dir)
1836
_selected_dir_reader = None
1839
def _walkdirs_utf8(top, prefix=""):
1840
"""Yield data about all the directories in a tree.
1842
This yields the same information as walkdirs() only each entry is yielded
1843
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1844
are returned as exact byte-strings.
1846
:return: yields a tuple of (dir_info, [file_info])
1847
dir_info is (utf8_relpath, path-from-top)
1848
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1849
if top is an absolute path, path-from-top is also an absolute path.
1850
path-from-top might be unicode or utf8, but it is the correct path to
1851
pass to os functions to affect the file in question. (such as os.lstat)
1853
global _selected_dir_reader
1854
if _selected_dir_reader is None:
1855
if sys.platform == "win32":
1857
from ._walkdirs_win32 import Win32ReadDir
1858
_selected_dir_reader = Win32ReadDir()
1861
elif _fs_enc in ('utf-8', 'ascii'):
1863
from ._readdir_pyx import UTF8DirReader
1864
_selected_dir_reader = UTF8DirReader()
1865
except ImportError as e:
1866
failed_to_load_extension(e)
1869
if _selected_dir_reader is None:
1870
# Fallback to the python version
1871
_selected_dir_reader = UnicodeDirReader()
1873
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1874
# But we don't actually uses 1-3 in pending, so set them to None
1875
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1876
read_dir = _selected_dir_reader.read_dir
1877
_directory = _directory_kind
1879
relroot, _, _, _, top = pending[-1].pop()
1882
dirblock = sorted(read_dir(relroot, top))
1883
yield (relroot, top), dirblock
1884
# push the user specified dirs from dirblock
1885
next = [d for d in reversed(dirblock) if d[2] == _directory]
1887
pending.append(next)
1890
class UnicodeDirReader(DirReader):
1891
"""A dir reader for non-utf8 file systems, which transcodes."""
1893
__slots__ = ['_utf8_encode']
1896
self._utf8_encode = codecs.getencoder('utf8')
1898
def top_prefix_to_starting_dir(self, top, prefix=""):
1899
"""See DirReader.top_prefix_to_starting_dir."""
1900
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1902
def read_dir(self, prefix, top):
1903
"""Read a single directory from a non-utf8 file system.
1905
top, and the abspath element in the output are unicode, all other paths
1906
are utf8. Local disk IO is done via unicode calls to listdir etc.
1908
This is currently the fallback code path when the filesystem encoding is
1909
not UTF-8. It may be better to implement an alternative so that we can
1910
safely handle paths that are not properly decodable in the current
1913
See DirReader.read_dir for details.
1915
_utf8_encode = self._utf8_encode
1917
def _fs_decode(s): return s.decode(_fs_enc)
1919
def _fs_encode(s): return s.encode(_fs_enc)
1922
relprefix = prefix + b'/'
1925
top_slash = top + '/'
1928
append = dirblock.append
1929
for entry in scandir(safe_utf8(top)):
1931
name = _fs_decode(entry.name)
1932
except UnicodeDecodeError:
1933
raise errors.BadFilenameEncoding(
1934
relprefix + entry.name, _fs_enc)
1935
abspath = top_slash + name
1936
name_utf8 = _utf8_encode(name)[0]
1937
statvalue = entry.stat(follow_symlinks=False)
1938
kind = file_kind_from_stat_mode(statvalue.st_mode)
1939
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1940
return sorted(dirblock)
1943
def copy_tree(from_path, to_path, handlers={}):
1944
"""Copy all of the entries in from_path into to_path.
1946
:param from_path: The base directory to copy.
1947
:param to_path: The target directory. If it does not exist, it will
1949
:param handlers: A dictionary of functions, which takes a source and
1950
destinations for files, directories, etc.
1951
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1952
'file', 'directory', and 'symlink' should always exist.
1953
If they are missing, they will be replaced with 'os.mkdir()',
1954
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1956
# Now, just copy the existing cached tree to the new location
1957
# We use a cheap trick here.
1958
# Absolute paths are prefixed with the first parameter
1959
# relative paths are prefixed with the second.
1960
# So we can get both the source and target returned
1961
# without any extra work.
1963
def copy_dir(source, dest):
1966
def copy_link(source, dest):
1967
"""Copy the contents of a symlink"""
1968
link_to = os.readlink(source)
1969
os.symlink(link_to, dest)
1971
real_handlers = {'file': shutil.copy2,
1972
'symlink': copy_link,
1973
'directory': copy_dir,
1975
real_handlers.update(handlers)
1977
if not os.path.exists(to_path):
1978
real_handlers['directory'](from_path, to_path)
1980
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1981
for relpath, name, kind, st, abspath in entries:
1982
real_handlers[kind](abspath, relpath)
1985
def copy_ownership_from_path(dst, src=None):
1986
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1988
If src is None, the containing directory is used as source. If chown
1989
fails, the error is ignored and a warning is printed.
1991
chown = getattr(os, 'chown', None)
1996
src = os.path.dirname(dst)
2002
chown(dst, s.st_uid, s.st_gid)
2005
'Unable to copy ownership from "%s" to "%s". '
2006
'You may want to set it manually.', src, dst)
2007
trace.log_exception_quietly()
2010
def path_prefix_key(path):
2011
"""Generate a prefix-order path key for path.
2013
This can be used to sort paths in the same way that walkdirs does.
2015
return (dirname(path), path)
2018
def compare_paths_prefix_order(path_a, path_b):
2019
"""Compare path_a and path_b to generate the same order walkdirs uses."""
2020
key_a = path_prefix_key(path_a)
2021
key_b = path_prefix_key(path_b)
2022
return (key_a > key_b) - (key_a < key_b)
2025
_cached_user_encoding = None
2028
def get_user_encoding():
2029
"""Find out what the preferred user encoding is.
2031
This is generally the encoding that is used for command line parameters
2032
and file contents. This may be different from the terminal encoding
2033
or the filesystem encoding.
2035
:return: A string defining the preferred user encoding
2037
global _cached_user_encoding
2038
if _cached_user_encoding is not None:
2039
return _cached_user_encoding
2041
if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2042
# Use the existing locale settings and call nl_langinfo directly
2043
# rather than going through getpreferredencoding. This avoids
2044
# <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2045
# possibility of the setlocale call throwing an error.
2046
user_encoding = locale.nl_langinfo(locale.CODESET)
2048
# GZ 2011-12-19: On windows could call GetACP directly instead.
2049
user_encoding = locale.getpreferredencoding(False)
2052
user_encoding = codecs.lookup(user_encoding).name
2054
if user_encoding not in ("", "cp0"):
2055
sys.stderr.write('brz: warning:'
2056
' unknown encoding %s.'
2057
' Continuing with ascii encoding.\n'
2060
user_encoding = 'ascii'
2062
# Get 'ascii' when setlocale has not been called or LANG=C or unset.
2063
if user_encoding == 'ascii':
2064
if sys.platform == 'darwin':
2065
# OSX is special-cased in Python to have a UTF-8 filesystem
2066
# encoding and previously had LANG set here if not present.
2067
user_encoding = 'utf-8'
2068
# GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2069
# for some other posix platforms as well.
2071
_cached_user_encoding = user_encoding
2072
return user_encoding
2075
def get_diff_header_encoding():
2076
return get_terminal_encoding()
2079
def get_host_name():
2080
"""Return the current unicode host name.
2082
This is meant to be used in place of socket.gethostname() because that
2083
behaves inconsistently on different platforms.
2085
if sys.platform == "win32":
2086
return win32utils.get_host_name()
2089
return socket.gethostname()
2092
# We must not read/write any more than 64k at a time from/to a socket so we
2093
# don't risk "no buffer space available" errors on some platforms. Windows in
2094
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2096
MAX_SOCKET_CHUNK = 64 * 1024
2098
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
2099
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2100
_eno = getattr(errno, _eno, None)
2101
if _eno is not None:
2102
_end_of_stream_errors.append(_eno)
2106
def read_bytes_from_socket(sock, report_activity=None,
2107
max_read_size=MAX_SOCKET_CHUNK):
2108
"""Read up to max_read_size of bytes from sock and notify of progress.
2110
Translates "Connection reset by peer" into file-like EOF (return an
2111
empty string rather than raise an error), and repeats the recv if
2112
interrupted by a signal.
2116
data = sock.recv(max_read_size)
2117
except socket.error as e:
2119
if eno in _end_of_stream_errors:
2120
# The connection was closed by the other side. Callers expect
2121
# an empty string to signal end-of-stream.
2123
elif eno == errno.EINTR:
2124
# Retry the interrupted recv.
2128
if report_activity is not None:
2129
report_activity(len(data), 'read')
2133
def recv_all(socket, count):
2134
"""Receive an exact number of bytes.
2136
Regular Socket.recv() may return less than the requested number of bytes,
2137
depending on what's in the OS buffer. MSG_WAITALL is not available
2138
on all platforms, but this should work everywhere. This will return
2139
less than the requested amount if the remote end closes.
2141
This isn't optimized and is intended mostly for use in testing.
2144
while len(b) < count:
2145
new = read_bytes_from_socket(socket, None, count - len(b))
2152
def send_all(sock, bytes, report_activity=None):
2153
"""Send all bytes on a socket.
2155
Breaks large blocks in smaller chunks to avoid buffering limitations on
2156
some platforms, and catches EINTR which may be thrown if the send is
2157
interrupted by a signal.
2159
This is preferred to socket.sendall(), because it avoids portability bugs
2160
and provides activity reporting.
2162
:param report_activity: Call this as bytes are read, see
2163
Transport._report_activity
2166
byte_count = len(bytes)
2167
view = memoryview(bytes)
2168
while sent_total < byte_count:
2170
sent = sock.send(view[sent_total:sent_total + MAX_SOCKET_CHUNK])
2171
except (socket.error, IOError) as e:
2172
if e.args[0] in _end_of_stream_errors:
2173
raise errors.ConnectionReset(
2174
"Error trying to write to socket", e)
2175
if e.args[0] != errno.EINTR:
2179
raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2182
if report_activity is not None:
2183
report_activity(sent, 'write')
2186
def connect_socket(address):
2187
# Slight variation of the socket.create_connection() function (provided by
2188
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2189
# provide it for previous python versions. Also, we don't use the timeout
2190
# parameter (provided by the python implementation) so we don't implement
2192
err = socket.error('getaddrinfo returns an empty list')
2193
host, port = address
2194
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2195
af, socktype, proto, canonname, sa = res
2198
sock = socket.socket(af, socktype, proto)
2202
except socket.error as e:
2204
# 'err' is now the most recent error
2205
if sock is not None:
2210
def dereference_path(path):
2211
"""Determine the real path to a file.
2213
All parent elements are dereferenced. But the file itself is not
2215
:param path: The original path. May be absolute or relative.
2216
:return: the real path *to* the file
2218
parent, base = os.path.split(path)
2219
# The pathjoin for '.' is a workaround for Python bug #1213894.
2220
# (initial path components aren't dereferenced)
2221
return pathjoin(realpath(pathjoin('.', parent)), base)
2224
def supports_mapi():
2225
"""Return True if we can use MAPI to launch a mail client."""
2226
return sys.platform == "win32"
2229
def resource_string(package, resource_name):
2230
"""Load a resource from a package and return it as a string.
2232
Note: Only packages that start with breezy are currently supported.
2234
This is designed to be a lightweight implementation of resource
2235
loading in a way which is API compatible with the same API from
2237
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
2238
If and when pkg_resources becomes a standard library, this routine
2241
# Check package name is within breezy
2242
if package == "breezy":
2243
resource_relpath = resource_name
2244
elif package.startswith("breezy."):
2245
package = package[len("breezy."):].replace('.', os.sep)
2246
resource_relpath = pathjoin(package, resource_name)
2248
raise errors.BzrError('resource package %s not in breezy' % package)
2250
# Map the resource to a file and read its contents
2251
base = dirname(breezy.__file__)
2252
if getattr(sys, 'frozen', None): # bzr.exe
2253
base = abspath(pathjoin(base, '..', '..'))
2254
with open(pathjoin(base, resource_relpath), "rt") as f:
2258
def file_kind_from_stat_mode_thunk(mode):
2259
global file_kind_from_stat_mode
2260
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2262
from ._readdir_pyx import UTF8DirReader
2263
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2265
# This is one time where we won't warn that an extension failed to
2266
# load. The extension is never available on Windows anyway.
2267
from ._readdir_py import (
2268
_kind_from_mode as file_kind_from_stat_mode
2270
return file_kind_from_stat_mode(mode)
2273
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2276
def file_stat(f, _lstat=os.lstat):
2280
except OSError as e:
2281
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2282
raise errors.NoSuchFile(f)
2286
def file_kind(f, _lstat=os.lstat):
2287
stat_value = file_stat(f, _lstat)
2288
return file_kind_from_stat_mode(stat_value.st_mode)
2291
def until_no_eintr(f, *a, **kw):
2292
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2294
WARNING: you must be certain that it is safe to retry the call repeatedly
2295
if EINTR does occur. This is typically only true for low-level operations
2296
like os.read. If in any doubt, don't use this.
2298
Keep in mind that this is not a complete solution to EINTR. There is
2299
probably code in the Python standard library and other dependencies that
2300
may encounter EINTR if a signal arrives (and there is signal handler for
2301
that signal). So this function can reduce the impact for IO that breezy
2302
directly controls, but it is not a complete solution.
2304
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2308
except (IOError, OSError) as e:
2309
if e.errno == errno.EINTR:
2314
if sys.platform == "win32":
2317
return msvcrt.getch()
2322
fd = sys.stdin.fileno()
2323
settings = termios.tcgetattr(fd)
2326
ch = sys.stdin.read(1)
2328
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2331
if sys.platform.startswith('linux'):
2332
def _local_concurrency():
2334
return os.sysconf('SC_NPROCESSORS_ONLN')
2335
except (ValueError, OSError, AttributeError):
2337
elif sys.platform == 'darwin':
2338
def _local_concurrency():
2339
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2340
stdout=subprocess.PIPE).communicate()[0]
2341
elif "bsd" in sys.platform:
2342
def _local_concurrency():
2343
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2344
stdout=subprocess.PIPE).communicate()[0]
2345
elif sys.platform == 'sunos5':
2346
def _local_concurrency():
2347
return subprocess.Popen(['psrinfo', '-p', ],
2348
stdout=subprocess.PIPE).communicate()[0]
2349
elif sys.platform == "win32":
2350
def _local_concurrency():
2351
# This appears to return the number of cores.
2352
return os.environ.get('NUMBER_OF_PROCESSORS')
2354
def _local_concurrency():
2359
_cached_local_concurrency = None
2362
def local_concurrency(use_cache=True):
2363
"""Return how many processes can be run concurrently.
2365
Rely on platform specific implementations and default to 1 (one) if
2366
anything goes wrong.
2368
global _cached_local_concurrency
2370
if _cached_local_concurrency is not None and use_cache:
2371
return _cached_local_concurrency
2373
concurrency = os.environ.get('BRZ_CONCURRENCY', None)
2374
if concurrency is None:
2375
import multiprocessing
2377
concurrency = multiprocessing.cpu_count()
2378
except NotImplementedError:
2379
# multiprocessing.cpu_count() isn't implemented on all platforms
2381
concurrency = _local_concurrency()
2382
except (OSError, IOError):
2385
concurrency = int(concurrency)
2386
except (TypeError, ValueError):
2389
_cached_local_concurrency = concurrency
2393
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2394
"""A stream writer that doesn't decode str arguments."""
2396
def __init__(self, encode, stream, errors='strict'):
2397
codecs.StreamWriter.__init__(self, stream, errors)
2398
self.encode = encode
2400
def write(self, object):
2401
if isinstance(object, str):
2402
self.stream.write(object)
2404
data, _ = self.encode(object, self.errors)
2405
self.stream.write(data)
2408
if sys.platform == 'win32':
2409
def open_file(filename, mode='r', bufsize=-1):
2410
"""This function is used to override the ``open`` builtin.
2412
But it uses O_NOINHERIT flag so the file handle is not inherited by
2413
child processes. Deleting or renaming a closed file opened with this
2414
function is not blocking child processes.
2416
writing = 'w' in mode
2417
appending = 'a' in mode
2418
updating = '+' in mode
2419
binary = 'b' in mode
2422
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2423
# for flags for each modes.
2433
flags |= os.O_WRONLY
2434
flags |= os.O_CREAT | os.O_TRUNC
2439
flags |= os.O_WRONLY
2440
flags |= os.O_CREAT | os.O_APPEND
2445
flags |= os.O_RDONLY
2447
return os.fdopen(os.open(filename, flags), mode, bufsize)
2452
def available_backup_name(base, exists):
2453
"""Find a non-existing backup file name.
2455
This will *not* create anything, this only return a 'free' entry. This
2456
should be used for checking names in a directory below a locked
2457
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2458
Leap) and generally discouraged.
2460
:param base: The base name.
2462
:param exists: A callable returning True if the path parameter exists.
2465
name = "%s.~%d~" % (base, counter)
2468
name = "%s.~%d~" % (base, counter)
2472
def set_fd_cloexec(fd):
2473
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2474
support for this is not available.
2478
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2479
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2480
except (ImportError, AttributeError):
2481
# Either the fcntl module or specific constants are not present
2485
def find_executable_on_path(name):
2486
"""Finds an executable on the PATH.
2488
On Windows, this will try to append each extension in the PATHEXT
2489
environment variable to the name, if it cannot be found with the name
2492
:param name: The base name of the executable.
2493
:return: The path to the executable found or None.
2495
if sys.platform == 'win32':
2496
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2497
exts = [ext.lower() for ext in exts]
2498
base, ext = os.path.splitext(name)
2500
if ext.lower() not in exts:
2506
path = os.environ.get('PATH')
2507
if path is not None:
2508
path = path.split(os.pathsep)
2511
f = os.path.join(d, name) + ext
2512
if os.access(f, os.X_OK):
2514
if sys.platform == 'win32':
2515
app_path = win32utils.get_app_path(name)
2516
if app_path != name:
2521
def _posix_is_local_pid_dead(pid):
2522
"""True if pid doesn't correspond to live process on this machine"""
2524
# Special meaning of unix kill: just check if it's there.
2526
except OSError as e:
2527
if e.errno == errno.ESRCH:
2528
# On this machine, and really not found: as sure as we can be
2531
elif e.errno == errno.EPERM:
2532
# exists, though not ours
2535
trace.mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2536
# Don't really know.
2539
# Exists and our process: not dead.
2543
if sys.platform == "win32":
2544
is_local_pid_dead = win32utils.is_local_pid_dead
2546
is_local_pid_dead = _posix_is_local_pid_dead
2548
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2549
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
2550
if getattr(errno, name, None) is not None]
2553
def fdatasync(fileno):
2554
"""Flush file contents to disk if possible.
2556
:param fileno: Integer OS file handle.
2557
:raises TransportNotPossible: If flushing to disk is not possible.
2559
fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2563
except IOError as e:
2564
# See bug #1075108, on some platforms fdatasync exists, but can
2565
# raise ENOTSUP. However, we are calling fdatasync to be helpful
2566
# and reduce the chance of corruption-on-powerloss situations. It
2567
# is not a mandatory call, so it is ok to suppress failures.
2568
trace.mutter("ignoring error calling fdatasync: %s" % (e,))
2569
if getattr(e, 'errno', None) not in _fdatasync_ignored:
2573
def ensure_empty_directory_exists(path, exception_class):
2574
"""Make sure a local directory exists and is empty.
2576
If it does not exist, it is created. If it exists and is not empty, an
2577
instance of exception_class is raised.
2581
except OSError as e:
2582
if e.errno != errno.EEXIST:
2584
if os.listdir(path) != []:
2585
raise exception_class(path)
2588
def is_environment_error(evalue):
2589
"""True if exception instance is due to a process environment issue
2591
This includes OSError and IOError, but also other errors that come from
2592
the operating system or core libraries but are not subclasses of those.
2594
if isinstance(evalue, (EnvironmentError, select.error)):
2596
if sys.platform == "win32" and win32utils._is_pywintypes_error(evalue):
2601
def read_mtab(path):
2602
"""Read an fstab-style file and extract mountpoint+filesystem information.
2604
:param path: Path to read from
2605
:yield: Tuples with mountpoints (as bytestrings) and filesystem names
2607
with open(path, 'rb') as f:
2609
if line.startswith(b'#'):
2614
yield cols[1], cols[2].decode('ascii', 'replace')
2617
MTAB_PATH = '/etc/mtab'
2619
class FilesystemFinder(object):
2620
"""Find the filesystem for a particular path."""
2622
def __init__(self, mountpoints):
2625
self._mountpoints = sorted(mountpoints, key=key, reverse=True)
2629
"""Create a FilesystemFinder from an mtab-style file.
2631
Note that this will silenty ignore mtab if it doesn't exist or can not
2634
# TODO(jelmer): Use inotify to be notified when /etc/mtab changes and
2635
# we need to re-read it.
2637
return cls(read_mtab(MTAB_PATH))
2638
except EnvironmentError as e:
2639
trace.mutter('Unable to read mtab: %s', e)
2642
def find(self, path):
2643
"""Find the filesystem used by a particular path.
2645
:param path: Path to find (bytestring or text type)
2646
:return: Filesystem name (as text type) or None, if the filesystem is
2649
for mountpoint, filesystem in self._mountpoints:
2650
if is_inside(mountpoint, path):
2655
_FILESYSTEM_FINDER = None
2658
def get_fs_type(path):
2659
"""Return the filesystem type for the partition a path is in.
2661
:param path: Path to search filesystem type for
2662
:return: A FS type, as string. E.g. "ext2"
2664
global _FILESYSTEM_FINDER
2665
if _FILESYSTEM_FINDER is None:
2666
_FILESYSTEM_FINDER = FilesystemFinder.from_mtab()
2668
if not isinstance(path, bytes):
2669
path = path.encode(_fs_enc)
2671
return _FILESYSTEM_FINDER.find(path)
2674
perf_counter = time.perf_counter