13
13
# You should have received a copy of the GNU General Public License
14
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
17
from __future__ import absolute_import
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
27
from .lazy_import import lazy_import
28
lazy_import(globals(), """
29
28
from datetime import datetime
30
from ntpath import (abspath as _nt_abspath,
32
normpath as _nt_normpath,
33
realpath as _nt_realpath,
34
splitdrive as _nt_splitdrive,
35
# We need to import both shutil and rmtree as we export the later on posix
36
# and need the former on windows
38
from shutil import rmtree
41
# We need to import both tempfile and mkdtemp as we export the later on posix
42
# and need the former on windows
44
from tempfile import mkdtemp
42
from tempfile import (
52
from breezy.i18n import gettext
73
# Cross platform wall-clock time functionality with decent resolution.
74
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
75
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
76
# synchronized with ``time.time()``, this is only meant to be used to find
77
# delta times by subtracting from another call to this function.
78
timer_func = time.time
79
if sys.platform == 'win32':
80
timer_func = time.clock
54
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
56
if sys.version_info < (2, 5):
57
import md5 as _mod_md5
59
import sha as _mod_sha
69
from bzrlib import symbol_versioning
82
72
# On win32, O_BINARY is used to indicate the file should
83
73
# be opened in binary mode, rather than text mode.
84
74
# On other platforms, O_BINARY doesn't exist, because
85
75
# they always open in binary mode, so it is okay to
86
# OR with 0 on those platforms.
87
# O_NOINHERIT and O_TEXT exists only on win32 too.
76
# OR with 0 on those platforms
88
77
O_BINARY = getattr(os, 'O_BINARY', 0)
89
O_TEXT = getattr(os, 'O_TEXT', 0)
90
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
93
class UnsupportedTimezoneFormat(errors.BzrError):
95
_fmt = ('Unsupported timezone format "%(timezone)s", '
96
'options are "utc", "original", "local".')
98
def __init__(self, timezone):
99
self.timezone = timezone
102
def get_unicode_argv():
106
user_encoding = get_user_encoding()
107
return [a.decode(user_encoding) for a in sys.argv[1:]]
108
except UnicodeDecodeError:
109
raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
110
"application locale.").format(a, user_encoding))
113
80
def make_readonly(filename):
114
81
"""Make a filename read-only."""
115
82
mod = os.lstat(filename).st_mode
116
83
if not stat.S_ISLNK(mod):
118
chmod_if_possible(filename, mod)
85
os.chmod(filename, mod)
121
88
def make_writable(filename):
122
89
mod = os.lstat(filename).st_mode
123
90
if not stat.S_ISLNK(mod):
125
chmod_if_possible(filename, mod)
128
def chmod_if_possible(filename, mode):
129
# Set file mode if that can be safely done.
130
# Sometimes even on unix the filesystem won't allow it - see
131
# https://bugs.launchpad.net/bzr/+bug/606537
133
# It is probably faster to just do the chmod, rather than
134
# doing a stat, and then trying to compare
135
os.chmod(filename, mode)
136
except (IOError, OSError) as e:
137
# Permission/access denied seems to commonly happen on smbfs; there's
138
# probably no point warning about it.
139
# <https://bugs.launchpad.net/bzr/+bug/606537>
140
if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
141
trace.mutter("ignore error on chmod of %r: %r" % (
92
os.chmod(filename, mod)
147
95
def minimum_path_selection(paths):
226
162
stat = getattr(os, 'lstat', os.stat)
230
166
if e.errno == errno.ENOENT:
233
raise errors.BzrError(
234
gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
169
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
237
172
def fancy_rename(old, new, rename_func, unlink_func):
238
173
"""A fancy rename, when you don't have atomic rename.
240
175
:param old: The old path, to rename from
241
176
:param new: The new path, to rename to
242
177
:param rename_func: The potentially non-atomic rename function
243
:param unlink_func: A way to delete the target file if the full rename
178
:param unlink_func: A way to delete the target file if the full rename succeeds
246
181
# sftp rename doesn't allow overwriting, so play tricks:
247
182
base = os.path.basename(new)
248
183
dirname = os.path.dirname(new)
249
# callers use different encodings for the paths so the following MUST
250
# respect that. We rely on python upcasting to unicode if new is unicode
251
# and keeping a str if not.
252
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
253
os.getpid(), rand_chars(10))
184
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
254
185
tmp_name = pathjoin(dirname, tmp_name)
256
187
# Rename the file out of the way, but keep track if it didn't exist
261
192
file_existed = False
263
194
rename_func(new, tmp_name)
264
except (errors.NoSuchFile,):
195
except (errors.NoSuchFile,), e:
267
198
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
268
199
# function raises an IOError with errno is None when a rename fails.
269
200
# This then gets caught here.
270
201
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
272
except Exception as e:
273
204
if (getattr(e, 'errno', None) is None
274
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
205
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
277
208
file_existed = True
281
# This may throw an exception, in which case success will
283
rename_func(old, new)
285
except (IOError, OSError) as e:
286
# source and target may be aliases of each other (e.g. on a
287
# case-insensitive filesystem), so we may have accidentally renamed
288
# source by when we tried to rename target
289
if (file_existed and e.errno in (None, errno.ENOENT)
290
and old.lower() == new.lower()):
291
# source and target are the same file on a case-insensitive
292
# filesystem, so we don't generate an exception
213
# This may throw an exception, in which case success will
215
rename_func(old, new)
217
except (IOError, OSError), e:
218
# source and target may be aliases of each other (e.g. on a
219
# case-insensitive filesystem), so we may have accidentally renamed
220
# source by when we tried to rename target
221
if not (file_existed and e.errno in (None, errno.ENOENT)):
298
225
# If the file used to exist, rename it back into place
307
234
# choke on a Unicode string containing a relative path if
308
235
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
237
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
310
238
def _posix_abspath(path):
311
239
# jam 20060426 rather than encoding to fsencoding
312
240
# copy posixpath.abspath, but use os.getcwdu instead
313
241
if not posixpath.isabs(path):
314
242
path = posixpath.join(getcwd(), path)
315
return _posix_normpath(path)
243
return posixpath.normpath(path)
318
246
def _posix_realpath(path):
319
247
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
322
def _posix_normpath(path):
323
path = posixpath.normpath(path)
324
# Bug 861008: posixpath.normpath() returns a path normalized according to
325
# the POSIX standard, which stipulates (for compatibility reasons) that two
326
# leading slashes must not be simplified to one, and only if there are 3 or
327
# more should they be simplified as one. So we treat the leading 2 slashes
328
# as a special case here by simply removing the first slash, as we consider
329
# that breaking POSIX compatibility for this obscure feature is acceptable.
330
# This is not a paranoid precaution, as we notably get paths like this when
331
# the repo is hosted at the root of the filesystem, i.e. in "/".
332
if path.startswith('//'):
337
def _posix_path_from_environ(key):
338
"""Get unicode path from `key` in environment or None if not present
340
Note that posix systems use arbitrary byte strings for filesystem objects,
341
so a path that raises BadFilenameEncoding here may still be accessible.
343
val = os.environ.get(key, None)
344
if PY3 or val is None:
347
return val.decode(_fs_enc)
348
except UnicodeDecodeError:
349
# GZ 2011-12-12:Ideally want to include `key` in the exception message
350
raise errors.BadFilenameEncoding(val, _fs_enc)
353
def _posix_get_home_dir():
354
"""Get the home directory of the current user as a unicode path"""
355
path = posixpath.expanduser("~")
357
return path.decode(_fs_enc)
358
except AttributeError:
360
except UnicodeDecodeError:
361
raise errors.BadFilenameEncoding(path, _fs_enc)
364
def _posix_getuser_unicode():
365
"""Get username from environment or password database as unicode"""
366
name = getpass.getuser()
369
user_encoding = get_user_encoding()
371
return name.decode(user_encoding)
372
except UnicodeDecodeError:
373
raise errors.BzrError("Encoding of username %r is unsupported by %s "
374
"application locale." % (name, user_encoding))
377
250
def _win32_fixdrive(path):
378
251
"""Force drive letters to be consistent.
383
256
running python.exe under cmd.exe return capital C:\\
384
257
running win32 python inside a cygwin shell returns lowercase c:\\
386
drive, path = ntpath.splitdrive(path)
259
drive, path = _nt_splitdrive(path)
387
260
return drive.upper() + path
390
263
def _win32_abspath(path):
391
# Real ntpath.abspath doesn't have a problem with a unicode cwd
392
return _win32_fixdrive(ntpath.abspath(path).replace('\\', '/'))
264
# Real _nt_abspath doesn't have a problem with a unicode cwd
265
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
268
def _win98_abspath(path):
269
"""Return the absolute version of a path.
270
Windows 98 safe implementation (python reimplementation
271
of Win32 API function GetFullPathNameW)
276
# \\HOST\path => //HOST/path
277
# //HOST/path => //HOST/path
278
# path => C:/cwd/path
281
# check for absolute path
282
drive = _nt_splitdrive(path)[0]
283
if drive == '' and path[:2] not in('//','\\\\'):
285
# we cannot simply os.path.join cwd and path
286
# because os.path.join('C:','/path') produce '/path'
287
# and this is incorrect
288
if path[:1] in ('/','\\'):
289
cwd = _nt_splitdrive(cwd)[0]
291
path = cwd + '\\' + path
292
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
395
295
def _win32_realpath(path):
396
# Real ntpath.realpath doesn't have a problem with a unicode cwd
397
return _win32_fixdrive(ntpath.realpath(path).replace('\\', '/'))
296
# Real _nt_realpath doesn't have a problem with a unicode cwd
297
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
400
300
def _win32_pathjoin(*args):
401
return ntpath.join(*args).replace('\\', '/')
301
return _nt_join(*args).replace('\\', '/')
404
304
def _win32_normpath(path):
405
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
305
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
408
308
def _win32_getcwd():
409
return _win32_fixdrive(_getcwd().replace('\\', '/'))
309
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
412
312
def _win32_mkdtemp(*args, **kwargs):
434
334
def _mac_getcwd():
435
return unicodedata.normalize('NFC', _getcwd())
438
def _rename_wrap_exception(rename_func):
439
"""Adds extra information to any exceptions that come from rename().
441
The exception has an updated message and 'old_filename' and 'new_filename'
445
def _rename_wrapper(old, new):
447
rename_func(old, new)
449
detailed_error = OSError(e.errno, e.strerror +
450
" [occurred when renaming '%s' to '%s']" %
452
detailed_error.old_filename = old
453
detailed_error.new_filename = new
456
return _rename_wrapper
459
if sys.version_info > (3,):
465
# Default rename wraps os.rename()
466
rename = _rename_wrap_exception(os.rename)
335
return unicodedata.normalize('NFC', os.getcwdu())
468
338
# Default is to just use the python builtins, but these can be rebound on
469
339
# particular platforms.
470
340
abspath = _posix_abspath
471
341
realpath = _posix_realpath
472
342
pathjoin = os.path.join
473
normpath = _posix_normpath
474
path_from_environ = _posix_path_from_environ
475
_get_home_dir = _posix_get_home_dir
476
getuser_unicode = _posix_getuser_unicode
343
normpath = os.path.normpath
478
346
dirname = os.path.dirname
479
347
basename = os.path.basename
480
348
split = os.path.split
481
349
splitext = os.path.splitext
482
# These were already lazily imported into local scope
350
# These were already imported into local scope
483
351
# mkdtemp = tempfile.mkdtemp
484
352
# rmtree = shutil.rmtree
493
354
MIN_ABS_PATHLENGTH = 1
496
357
if sys.platform == 'win32':
497
abspath = _win32_abspath
358
if win32utils.winver == 'Windows 98':
359
abspath = _win98_abspath
361
abspath = _win32_abspath
498
362
realpath = _win32_realpath
499
363
pathjoin = _win32_pathjoin
500
364
normpath = _win32_normpath
501
365
getcwd = _win32_getcwd
502
366
mkdtemp = _win32_mkdtemp
503
rename = _rename_wrap_exception(_win32_rename)
505
from . import _walkdirs_win32
509
lstat = _walkdirs_win32.lstat
510
fstat = _walkdirs_win32.fstat
511
wrap_stat = _walkdirs_win32.wrap_stat
367
rename = _win32_rename
513
369
MIN_ABS_PATHLENGTH = 3
553
401
On my standard US Windows XP, the preferred encoding is
554
402
cp1252, but the console is cp437
556
:param trace: If True trace the selected encoding via mutter().
558
from .trace import mutter
404
from bzrlib.trace import mutter
559
405
output_encoding = getattr(sys.stdout, 'encoding', None)
560
406
if not output_encoding:
561
407
input_encoding = getattr(sys.stdin, 'encoding', None)
562
408
if not input_encoding:
563
409
output_encoding = get_user_encoding()
565
mutter('encoding stdout as osutils.get_user_encoding() %r',
410
mutter('encoding stdout as osutils.get_user_encoding() %r',
568
413
output_encoding = input_encoding
570
mutter('encoding stdout as sys.stdin encoding %r',
414
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
574
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
416
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
575
417
if output_encoding == 'cp0':
576
418
# invalid encoding (cp0 means 'no codepage' on Windows)
577
419
output_encoding = get_user_encoding()
579
mutter('cp0 is invalid encoding.'
580
' encoding stdout as osutils.get_user_encoding() %r',
420
mutter('cp0 is invalid encoding.'
421
' encoding stdout as osutils.get_user_encoding() %r',
584
425
codecs.lookup(output_encoding)
585
426
except LookupError:
586
sys.stderr.write('brz: warning:'
427
sys.stderr.write('bzr: warning:'
587
428
' unknown terminal encoding %s.\n'
588
429
' Using encoding %s instead.\n'
589
430
% (output_encoding, get_user_encoding())
591
432
output_encoding = get_user_encoding()
593
434
return output_encoding
860
662
:param show_offset: Whether to append the timezone.
862
664
(date_fmt, tt, offset_str) = \
863
_format_date(t, offset, timezone, date_fmt, show_offset)
665
_format_date(t, offset, timezone, date_fmt, show_offset)
864
666
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
865
667
date_str = time.strftime(date_fmt, tt)
866
668
return date_str + offset_str
869
# Cache of formatted offset strings
873
def format_date_with_offset_in_original_timezone(t, offset=0,
874
_cache=_offset_cache):
875
"""Return a formatted date string in the original timezone.
877
This routine may be faster then format_date.
879
:param t: Seconds since the epoch.
880
:param offset: Timezone offset in seconds east of utc.
884
tt = time.gmtime(t + offset)
885
date_fmt = _default_format_by_weekday_num[tt[6]]
886
date_str = time.strftime(date_fmt, tt)
887
offset_str = _cache.get(offset, None)
888
if offset_str is None:
889
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
890
_cache[offset] = offset_str
891
return date_str + offset_str
894
670
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
895
671
show_offset=True):
896
672
"""Return an unicode date string formatted according to the current locale.
1062
825
def joinpath(p):
1064
827
if (f == '..') or (f is None) or (f == ''):
1065
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
828
raise errors.BzrError("sorry, %r not allowed in path" % f)
1066
829
return pathjoin(*p)
1069
def parent_directories(filename):
1070
"""Return the list of parent directories, deepest first.
1072
For example, parent_directories("a/b/c") -> ["a/b", "a"].
1075
parts = splitpath(dirname(filename))
1077
parents.append(joinpath(parts))
1082
_extension_load_failures = []
1085
def failed_to_load_extension(exception):
1086
"""Handle failing to load a binary extension.
1088
This should be called from the ImportError block guarding the attempt to
1089
import the native extension. If this function returns, the pure-Python
1090
implementation should be loaded instead::
1093
>>> import breezy._fictional_extension_pyx
1094
>>> except ImportError, e:
1095
>>> breezy.osutils.failed_to_load_extension(e)
1096
>>> import breezy._fictional_extension_py
1098
# NB: This docstring is just an example, not a doctest, because doctest
1099
# currently can't cope with the use of lazy imports in this namespace --
1102
# This currently doesn't report the failure at the time it occurs, because
1103
# they tend to happen very early in startup when we can't check config
1104
# files etc, and also we want to report all failures but not spam the user
1106
exception_str = str(exception)
1107
if exception_str not in _extension_load_failures:
1108
trace.mutter("failed to load compiled extension: %s" % exception_str)
1109
_extension_load_failures.append(exception_str)
1112
def report_extension_load_failures():
1113
if not _extension_load_failures:
1115
if config.GlobalConfig().suppress_warning('missing_extensions'):
1117
# the warnings framework should by default show this only once
1118
from .trace import warning
1120
"brz: warning: some compiled extensions could not be loaded; "
1121
"see ``brz help missing-extensions``")
1122
# we no longer show the specific missing extensions here, because it makes
1123
# the message too long and scary - see
1124
# https://bugs.launchpad.net/bzr/+bug/430529
1128
from ._chunks_to_lines_pyx import chunks_to_lines
1129
except ImportError as e:
1130
failed_to_load_extension(e)
1131
from ._chunks_to_lines_py import chunks_to_lines
833
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
835
from bzrlib._chunks_to_lines_py import chunks_to_lines
1134
838
def split_lines(s):
1135
839
"""Split s into lines, but without removing the newline characters."""
1136
840
# Trivially convert a fulltext into a 'chunked' representation, and let
1137
841
# chunks_to_lines do the heavy lifting.
1138
if isinstance(s, bytes):
842
if isinstance(s, str):
1139
843
# chunks_to_lines only supports 8-bit strings
1140
844
return chunks_to_lines([s])
1168
871
os.link(src, dest)
1169
except (OSError, IOError) as e:
872
except (OSError, IOError), e:
1170
873
if e.errno != errno.EXDEV:
1172
875
shutil.copyfile(src, dest)
878
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
879
# Forgiveness than Permission (EAFP) because:
880
# - root can damage a solaris file system by using unlink,
881
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
882
# EACCES, OSX: EPERM) when invoked on a directory.
1175
883
def delete_any(path):
1176
"""Delete a file, symlink or directory.
1178
Will delete even if readonly.
1181
_delete_file_or_dir(path)
1182
except (OSError, IOError) as e:
1183
if e.errno in (errno.EPERM, errno.EACCES):
1184
# make writable and try again
1187
except (OSError, IOError):
1189
_delete_file_or_dir(path)
1194
def _delete_file_or_dir(path):
1195
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1196
# Forgiveness than Permission (EAFP) because:
1197
# - root can damage a solaris file system by using unlink,
1198
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1199
# EACCES, OSX: EPERM) when invoked on a directory.
1200
if isdir(path): # Takes care of symlinks
884
"""Delete a file or directory."""
885
if isdir(path): # Takes care of symlinks
1371
1029
# but for now, we haven't optimized...
1372
1030
return [canonical_relpath(base, p) for p in paths]
1375
def decode_filename(filename):
1376
"""Decode the filename using the filesystem encoding
1378
If it is unicode, it is returned.
1379
Otherwise it is decoded from the the filesystem's encoding. If decoding
1380
fails, a errors.BadFilenameEncoding exception is raised.
1382
if isinstance(filename, text_type):
1385
return filename.decode(_fs_enc)
1386
except UnicodeDecodeError:
1387
raise errors.BadFilenameEncoding(filename, _fs_enc)
1390
1032
def safe_unicode(unicode_or_utf8_string):
1391
1033
"""Coerce unicode_or_utf8_string into unicode.
1393
1035
If it is unicode, it is returned.
1394
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1395
wrapped in a BzrBadParameterNotUnicode exception.
1036
Otherwise it is decoded from utf-8. If a decoding error
1037
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
1038
as a BzrBadParameter exception.
1397
if isinstance(unicode_or_utf8_string, text_type):
1040
if isinstance(unicode_or_utf8_string, unicode):
1398
1041
return unicode_or_utf8_string
1400
1043
return unicode_or_utf8_string.decode('utf8')
1472
1129
On platforms where the system normalizes filenames (Mac OSX),
1473
1130
you can access a file by any path which will normalize correctly.
1474
On platforms where the system does not normalize filenames
1475
(everything else), you have to access a file by its exact path.
1131
On platforms where the system does not normalize filenames
1132
(Windows, Linux), you have to access a file by its exact path.
1477
Internally, bzr only supports NFC normalization, since that is
1134
Internally, bzr only supports NFC normalization, since that is
1478
1135
the standard for XML documents.
1480
1137
So return the normalized path, and a flag indicating if the file
1481
1138
can be accessed by that path.
1484
if isinstance(path, bytes):
1485
path = path.decode(sys.getfilesystemencoding())
1486
return unicodedata.normalize('NFC', path), True
1141
return unicodedata.normalize('NFC', unicode(path)), True
1489
1144
def _inaccessible_normalized_filename(path):
1490
1145
__doc__ = _accessible_normalized_filename.__doc__
1492
if isinstance(path, bytes):
1493
path = path.decode(sys.getfilesystemencoding())
1494
normalized = unicodedata.normalize('NFC', path)
1147
normalized = unicodedata.normalize('NFC', unicode(path))
1495
1148
return normalized, normalized == path
1501
1154
normalized_filename = _inaccessible_normalized_filename
1504
def set_signal_handler(signum, handler, restart_syscall=True):
1505
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1506
on platforms that support that.
1508
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1509
automatically restart (by calling `signal.siginterrupt(signum,
1510
False)`). May be ignored if the feature is not available on this
1511
platform or Python version.
1515
siginterrupt = signal.siginterrupt
1517
# This python implementation doesn't provide signal support, hence no
1520
except AttributeError:
1521
# siginterrupt doesn't exist on this platform, or for this version
1523
def siginterrupt(signum, flag): return None
1525
def sig_handler(*args):
1526
# Python resets the siginterrupt flag when a signal is
1527
# received. <http://bugs.python.org/issue8354>
1528
# As a workaround for some cases, set it back the way we want it.
1529
siginterrupt(signum, False)
1530
# Now run the handler function passed to set_signal_handler.
1533
sig_handler = handler
1534
old_handler = signal.signal(signum, sig_handler)
1536
siginterrupt(signum, False)
1540
default_terminal_width = 80
1541
"""The default terminal width for ttys.
1543
This is defined so that higher levels can share a common fallback value when
1544
terminal_width() returns None.
1547
# Keep some state so that terminal_width can detect if _terminal_size has
1548
# returned a different size since the process started. See docstring and
1549
# comments of terminal_width for details.
1550
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1551
_terminal_size_state = 'no_data'
1552
_first_terminal_size = None
1555
1157
def terminal_width():
1556
"""Return terminal width.
1558
None is returned if the width can't established precisely.
1561
- if BRZ_COLUMNS is set, returns its value
1562
- if there is no controlling terminal, returns None
1563
- query the OS, if the queried size has changed since the last query,
1565
- if COLUMNS is set, returns its value,
1566
- if the OS has a value (even though it's never changed), return its value.
1568
From there, we need to query the OS to get the size of the controlling
1571
On Unices we query the OS by:
1572
- get termios.TIOCGWINSZ
1573
- if an error occurs or a negative value is obtained, returns None
1575
On Windows we query the OS by:
1576
- win32utils.get_console_size() decides,
1577
- returns None on error (provided default value)
1579
# Note to implementors: if changing the rules for determining the width,
1580
# make sure you've considered the behaviour in these cases:
1581
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1582
# - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1584
# - (add more interesting cases here, if you find any)
1585
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1586
# but we don't want to register a signal handler because it is impossible
1587
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1588
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1589
# time so we can notice if the reported size has changed, which should have
1592
# If BRZ_COLUMNS is set, take it, user is always right
1593
# Except if they specified 0 in which case, impose no limit here
1595
width = int(os.environ['BRZ_COLUMNS'])
1596
except (KeyError, ValueError):
1598
if width is not None:
1604
isatty = getattr(sys.stdout, 'isatty', None)
1605
if isatty is None or not isatty():
1606
# Don't guess, setting BRZ_COLUMNS is the recommended way to override.
1610
width, height = os_size = _terminal_size(None, None)
1611
global _first_terminal_size, _terminal_size_state
1612
if _terminal_size_state == 'no_data':
1613
_first_terminal_size = os_size
1614
_terminal_size_state = 'unchanged'
1615
elif (_terminal_size_state == 'unchanged' and
1616
_first_terminal_size != os_size):
1617
_terminal_size_state = 'changed'
1619
# If the OS claims to know how wide the terminal is, and this value has
1620
# ever changed, use that.
1621
if _terminal_size_state == 'changed':
1622
if width is not None and width > 0:
1625
# If COLUMNS is set, use it.
1627
return int(os.environ['COLUMNS'])
1628
except (KeyError, ValueError):
1631
# Finally, use an unchanged size from the OS, if we have one.
1632
if _terminal_size_state == 'unchanged':
1633
if width is not None and width > 0:
1636
# The width could not be determined.
1640
def _win32_terminal_size(width, height):
1641
width, height = win32utils.get_console_size(
1642
defaultx=width, defaulty=height)
1643
return width, height
1646
def _ioctl_terminal_size(width, height):
1158
"""Return estimated terminal width."""
1159
if sys.platform == 'win32':
1160
return win32utils.get_console_size()[0]
1163
import struct, fcntl, termios
1651
1164
s = struct.pack('HHHH', 0, 0, 0, 0)
1652
1165
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1653
height, width = struct.unpack('HHHH', x)[0:2]
1654
except (IOError, AttributeError):
1166
width = struct.unpack('HHHH', x)[1]
1656
return width, height
1659
_terminal_size = None
1660
"""Returns the terminal size as (width, height).
1662
:param width: Default value for width.
1663
:param height: Default value for height.
1665
This is defined specifically for each OS and query the size of the controlling
1666
terminal. If any error occurs, the provided default values should be returned.
1668
if sys.platform == 'win32':
1669
_terminal_size = _win32_terminal_size
1671
_terminal_size = _ioctl_terminal_size
1171
width = int(os.environ['COLUMNS'])
1674
1180
def supports_executable():
1740
1245
:return: True if this represents an ENOTDIR error. False otherwise.
1742
1247
en = getattr(e, 'errno', None)
1743
if (en == errno.ENOTDIR or
1744
(sys.platform == 'win32' and
1745
(en == _WIN32_ERROR_DIRECTORY or
1747
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1248
if (en == errno.ENOTDIR
1249
or (sys.platform == 'win32'
1250
and (en == _WIN32_ERROR_DIRECTORY
1251
or (en == errno.EINVAL
1252
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1753
1258
def walkdirs(top, prefix=""):
1754
1259
"""Yield data about all the directories in a tree.
1756
1261
This yields all the data about the contents of a directory at a time.
1757
1262
After each directory has been yielded, if the caller has mutated the list
1758
1263
to exclude some directories, they are then not descended into.
1760
1265
The data yielded is of the form:
1761
1266
((directory-relpath, directory-path-from-top),
1762
1267
[(relpath, basename, kind, lstat, path-from-top), ...]),
1763
1268
- directory-relpath is the relative path of the directory being returned
1764
1269
with respect to top. prefix is prepended to this.
1765
- directory-path-from-root is the path including top for this directory.
1270
- directory-path-from-root is the path including top for this directory.
1766
1271
It is suitable for use with os functions.
1767
1272
- relpath is the relative path within the subtree being walked.
1768
1273
- basename is the basename of the path
1861
1366
global _selected_dir_reader
1862
1367
if _selected_dir_reader is None:
1863
if sys.platform == "win32":
1368
fs_encoding = _fs_enc.upper()
1369
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1370
# Win98 doesn't have unicode apis like FindFirstFileW
1371
# TODO: We possibly could support Win98 by falling back to the
1372
# original FindFirstFile, and using TCHAR instead of WCHAR,
1373
# but that gets a bit tricky, and requires custom compiling
1865
from ._walkdirs_win32 import Win32ReadDir
1376
from bzrlib._walkdirs_win32 import Win32ReadDir
1378
_selected_dir_reader = UnicodeDirReader()
1866
1380
_selected_dir_reader = Win32ReadDir()
1381
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1382
# ANSI_X3.4-1968 is a form of ASCII
1383
_selected_dir_reader = UnicodeDirReader()
1386
from bzrlib._readdir_pyx import UTF8DirReader
1867
1387
except ImportError:
1869
elif _fs_enc in ('utf-8', 'ascii'):
1871
from ._readdir_pyx import UTF8DirReader
1388
# No optimised code path
1389
_selected_dir_reader = UnicodeDirReader()
1872
1391
_selected_dir_reader = UTF8DirReader()
1873
except ImportError as e:
1874
failed_to_load_extension(e)
1877
if _selected_dir_reader is None:
1878
# Fallback to the python version
1879
_selected_dir_reader = UnicodeDirReader()
1881
1392
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1882
1393
# But we don't actually uses 1-3 in pending, so set them to None
1883
1394
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1921
1432
See DirReader.read_dir for details.
1923
1434
_utf8_encode = self._utf8_encode
1925
def _fs_decode(s): return s.decode(_fs_enc)
1927
def _fs_encode(s): return s.encode(_fs_enc)
1928
1435
_lstat = os.lstat
1929
1436
_listdir = os.listdir
1930
1437
_kind_from_mode = file_kind_from_stat_mode
1933
relprefix = prefix + b'/'
1440
relprefix = prefix + '/'
1936
top_slash = top + '/'
1443
top_slash = top + u'/'
1939
1446
append = dirblock.append
1940
for name_native in _listdir(top.encode('utf-8')):
1447
for name in sorted(_listdir(top)):
1942
name = _fs_decode(name_native)
1449
name_utf8 = _utf8_encode(name)[0]
1943
1450
except UnicodeDecodeError:
1944
1451
raise errors.BadFilenameEncoding(
1945
relprefix + name_native, _fs_enc)
1946
name_utf8 = _utf8_encode(name)[0]
1452
_utf8_encode(relprefix)[0] + name, _fs_enc)
1947
1453
abspath = top_slash + name
1948
1454
statvalue = _lstat(abspath)
1949
1455
kind = _kind_from_mode(statvalue.st_mode)
1950
1456
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1951
return sorted(dirblock)
1954
1460
def copy_tree(from_path, to_path, handlers={}):
1955
1461
"""Copy all of the entries in from_path into to_path.
1957
:param from_path: The base directory to copy.
1463
:param from_path: The base directory to copy.
1958
1464
:param to_path: The target directory. If it does not exist, it will
1960
1466
:param handlers: A dictionary of functions, which takes a source and
1993
1499
real_handlers[kind](abspath, relpath)
1996
def copy_ownership_from_path(dst, src=None):
1997
"""Copy usr/grp ownership from src file/dir to dst file/dir.
1999
If src is None, the containing directory is used as source. If chown
2000
fails, the error is ignored and a warning is printed.
2002
chown = getattr(os, 'chown', None)
2007
src = os.path.dirname(dst)
2013
chown(dst, s.st_uid, s.st_gid)
2016
'Unable to copy ownership from "%s" to "%s". '
2017
'You may want to set it manually.', src, dst)
2018
trace.log_exception_quietly()
2021
1502
def path_prefix_key(path):
2022
1503
"""Generate a prefix-order path key for path.
2024
1505
This can be used to sort paths in the same way that walkdirs does.
2026
return (dirname(path), path)
1507
return (dirname(path) , path)
2029
1510
def compare_paths_prefix_order(path_a, path_b):
2030
1511
"""Compare path_a and path_b to generate the same order walkdirs uses."""
2031
1512
key_a = path_prefix_key(path_a)
2032
1513
key_b = path_prefix_key(path_b)
2033
return (key_a > key_b) - (key_a < key_b)
1514
return cmp(key_a, key_b)
2036
1517
_cached_user_encoding = None
2039
def get_user_encoding():
1520
def get_user_encoding(use_cache=True):
2040
1521
"""Find out what the preferred user encoding is.
2042
1523
This is generally the encoding that is used for command line parameters
2043
1524
and file contents. This may be different from the terminal encoding
2044
1525
or the filesystem encoding.
1527
:param use_cache: Enable cache for detected encoding.
1528
(This parameter is turned on by default,
1529
and required only for selftesting)
2046
1531
:return: A string defining the preferred user encoding
2048
1533
global _cached_user_encoding
2049
if _cached_user_encoding is not None:
1534
if _cached_user_encoding is not None and use_cache:
2050
1535
return _cached_user_encoding
2052
if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2053
# Use the existing locale settings and call nl_langinfo directly
2054
# rather than going through getpreferredencoding. This avoids
2055
# <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2056
# possibility of the setlocale call throwing an error.
2057
user_encoding = locale.nl_langinfo(locale.CODESET)
1537
if sys.platform == 'darwin':
1538
# python locale.getpreferredencoding() always return
1539
# 'mac-roman' on darwin. That's a lie.
1540
sys.platform = 'posix'
1542
if os.environ.get('LANG', None) is None:
1543
# If LANG is not set, we end up with 'ascii', which is bad
1544
# ('mac-roman' is more than ascii), so we set a default which
1545
# will give us UTF-8 (which appears to work in all cases on
1546
# OSX). Users are still free to override LANG of course, as
1547
# long as it give us something meaningful. This work-around
1548
# *may* not be needed with python 3k and/or OSX 10.5, but will
1549
# work with them too -- vila 20080908
1550
os.environ['LANG'] = 'en_US.UTF-8'
1553
sys.platform = 'darwin'
2059
# GZ 2011-12-19: On windows could call GetACP directly instead.
2060
user_encoding = locale.getpreferredencoding(False)
2063
user_encoding = codecs.lookup(user_encoding).name
2065
if user_encoding not in ("", "cp0"):
2066
sys.stderr.write('brz: warning:'
1558
user_encoding = locale.getpreferredencoding()
1559
except locale.Error, e:
1560
sys.stderr.write('bzr: warning: %s\n'
1561
' Could not determine what text encoding to use.\n'
1562
' This error usually means your Python interpreter\n'
1563
' doesn\'t support the locale set by $LANG (%s)\n'
1564
" Continuing with ascii encoding.\n"
1565
% (e, os.environ.get('LANG')))
1566
user_encoding = 'ascii'
1568
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1569
# treat that as ASCII, and not support printing unicode characters to the
1572
# For python scripts run under vim, we get '', so also treat that as ASCII
1573
if user_encoding in (None, 'cp0', ''):
1574
user_encoding = 'ascii'
1578
codecs.lookup(user_encoding)
1580
sys.stderr.write('bzr: warning:'
2067
1581
' unknown encoding %s.'
2068
1582
' Continuing with ascii encoding.\n'
2069
1583
% user_encoding
2071
user_encoding = 'ascii'
2073
# Get 'ascii' when setlocale has not been called or LANG=C or unset.
2074
if user_encoding == 'ascii':
2075
if sys.platform == 'darwin':
2076
# OSX is special-cased in Python to have a UTF-8 filesystem
2077
# encoding and previously had LANG set here if not present.
2078
user_encoding = 'utf-8'
2079
# GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2080
# for some other posix platforms as well.
2082
_cached_user_encoding = user_encoding
1585
user_encoding = 'ascii'
1588
_cached_user_encoding = user_encoding
2083
1590
return user_encoding
2086
def get_diff_header_encoding():
2087
return get_terminal_encoding()
2090
1593
def get_host_name():
2091
1594
"""Return the current unicode host name.
2094
1597
behaves inconsistently on different platforms.
2096
1599
if sys.platform == "win32":
2097
1601
return win32utils.get_host_name()
2101
return socket.gethostname()
2102
1604
return socket.gethostname().decode(get_user_encoding())
2105
# We must not read/write any more than 64k at a time from/to a socket so we
2106
# don't risk "no buffer space available" errors on some platforms. Windows in
2107
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2109
MAX_SOCKET_CHUNK = 64 * 1024
2111
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
2112
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2113
_eno = getattr(errno, _eno, None)
2114
if _eno is not None:
2115
_end_of_stream_errors.append(_eno)
2119
def read_bytes_from_socket(sock, report_activity=None,
2120
max_read_size=MAX_SOCKET_CHUNK):
2121
"""Read up to max_read_size of bytes from sock and notify of progress.
2123
Translates "Connection reset by peer" into file-like EOF (return an
2124
empty string rather than raise an error), and repeats the recv if
2125
interrupted by a signal.
2129
data = sock.recv(max_read_size)
2130
except socket.error as e:
2132
if eno in _end_of_stream_errors:
2133
# The connection was closed by the other side. Callers expect
2134
# an empty string to signal end-of-stream.
2136
elif eno == errno.EINTR:
2137
# Retry the interrupted recv.
2141
if report_activity is not None:
2142
report_activity(len(data), 'read')
2146
def recv_all(socket, count):
1607
def recv_all(socket, bytes):
2147
1608
"""Receive an exact number of bytes.
2149
1610
Regular Socket.recv() may return less than the requested number of bytes,
2150
depending on what's in the OS buffer. MSG_WAITALL is not available
1611
dependning on what's in the OS buffer. MSG_WAITALL is not available
2151
1612
on all platforms, but this should work everywhere. This will return
2152
1613
less than the requested amount if the remote end closes.
2154
1615
This isn't optimized and is intended mostly for use in testing.
2157
while len(b) < count:
2158
new = read_bytes_from_socket(socket, None, count - len(b))
1618
while len(b) < bytes:
1619
new = until_no_eintr(socket.recv, bytes - len(b))
2165
def send_all(sock, bytes, report_activity=None):
1626
def send_all(socket, bytes):
2166
1627
"""Send all bytes on a socket.
2168
Breaks large blocks in smaller chunks to avoid buffering limitations on
2169
some platforms, and catches EINTR which may be thrown if the send is
2170
interrupted by a signal.
2172
This is preferred to socket.sendall(), because it avoids portability bugs
2173
and provides activity reporting.
2175
:param report_activity: Call this as bytes are read, see
2176
Transport._report_activity
1629
Regular socket.sendall() can give socket error 10053 on Windows. This
1630
implementation sends no more than 64k at a time, which avoids this problem.
2179
byte_count = len(bytes)
2180
view = memoryview(bytes)
2181
while sent_total < byte_count:
2183
sent = sock.send(view[sent_total:sent_total + MAX_SOCKET_CHUNK])
2184
except (socket.error, IOError) as e:
2185
if e.args[0] in _end_of_stream_errors:
2186
raise errors.ConnectionReset(
2187
"Error trying to write to socket", e)
2188
if e.args[0] != errno.EINTR:
2192
raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2195
if report_activity is not None:
2196
report_activity(sent, 'write')
2199
def connect_socket(address):
2200
# Slight variation of the socket.create_connection() function (provided by
2201
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2202
# provide it for previous python versions. Also, we don't use the timeout
2203
# parameter (provided by the python implementation) so we don't implement
2205
err = socket.error('getaddrinfo returns an empty list')
2206
host, port = address
2207
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2208
af, socktype, proto, canonname, sa = res
2211
sock = socket.socket(af, socktype, proto)
2215
except socket.error as e:
2217
# 'err' is now the most recent error
2218
if sock is not None:
1633
for pos in xrange(0, len(bytes), chunk_size):
1634
until_no_eintr(socket.sendall, bytes[pos:pos+chunk_size])
2223
1637
def dereference_path(path):
2251
1665
If and when pkg_resources becomes a standard library, this routine
2252
1666
can delegate to it.
2254
# Check package name is within breezy
2255
if package == "breezy":
1668
# Check package name is within bzrlib
1669
if package == "bzrlib":
2256
1670
resource_relpath = resource_name
2257
elif package.startswith("breezy."):
2258
package = package[len("breezy."):].replace('.', os.sep)
1671
elif package.startswith("bzrlib."):
1672
package = package[len("bzrlib."):].replace('.', os.sep)
2259
1673
resource_relpath = pathjoin(package, resource_name)
2261
raise errors.BzrError('resource package %s not in breezy' % package)
1675
raise errors.BzrError('resource package %s not in bzrlib' % package)
2263
1677
# Map the resource to a file and read its contents
2264
base = dirname(breezy.__file__)
1678
base = dirname(bzrlib.__file__)
2265
1679
if getattr(sys, 'frozen', None): # bzr.exe
2266
1680
base = abspath(pathjoin(base, '..', '..'))
2267
with open(pathjoin(base, resource_relpath), "rt") as f:
1681
filename = pathjoin(base, resource_relpath)
1682
return open(filename, 'rU').read()
2271
1685
def file_kind_from_stat_mode_thunk(mode):
2272
1686
global file_kind_from_stat_mode
2273
1687
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2275
from ._readdir_pyx import UTF8DirReader
1689
from bzrlib._readdir_pyx import UTF8DirReader
2276
1690
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2277
1691
except ImportError:
2278
# This is one time where we won't warn that an extension failed to
2279
# load. The extension is never available on Windows anyway.
2280
from ._readdir_py import (
1692
from bzrlib._readdir_py import (
2281
1693
_kind_from_mode as file_kind_from_stat_mode
2283
1695
return file_kind_from_stat_mode(mode)
2286
1696
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2289
def file_stat(f, _lstat=os.lstat):
1699
def file_kind(f, _lstat=os.lstat):
2293
except OSError as e:
1701
return file_kind_from_stat_mode(_lstat(f).st_mode)
2294
1703
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2295
1704
raise errors.NoSuchFile(f)
2299
def file_kind(f, _lstat=os.lstat):
2300
stat_value = file_stat(f, _lstat)
2301
return file_kind_from_stat_mode(stat_value.st_mode)
2304
1708
def until_no_eintr(f, *a, **kw):
2305
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2307
WARNING: you must be certain that it is safe to retry the call repeatedly
2308
if EINTR does occur. This is typically only true for low-level operations
2309
like os.read. If in any doubt, don't use this.
2311
Keep in mind that this is not a complete solution to EINTR. There is
2312
probably code in the Python standard library and other dependencies that
2313
may encounter EINTR if a signal arrives (and there is signal handler for
2314
that signal). So this function can reduce the impact for IO that breezy
2315
directly controls, but it is not a complete solution.
1709
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2317
1710
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2320
1713
return f(*a, **kw)
2321
except (IOError, OSError) as e:
1714
except (IOError, OSError), e:
2322
1715
if e.errno == errno.EINTR:
2327
1720
if sys.platform == "win32":
2330
1723
return msvcrt.getch()
2335
1728
fd = sys.stdin.fileno()
2336
1729
settings = termios.tcgetattr(fd)
2341
1734
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2344
if sys.platform.startswith('linux'):
2345
def _local_concurrency():
2347
return os.sysconf('SC_NPROCESSORS_ONLN')
2348
except (ValueError, OSError, AttributeError):
2350
elif sys.platform == 'darwin':
2351
def _local_concurrency():
2352
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2353
stdout=subprocess.PIPE).communicate()[0]
2354
elif "bsd" in sys.platform:
2355
def _local_concurrency():
2356
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2357
stdout=subprocess.PIPE).communicate()[0]
2358
elif sys.platform == 'sunos5':
2359
def _local_concurrency():
2360
return subprocess.Popen(['psrinfo', '-p', ],
2361
stdout=subprocess.PIPE).communicate()[0]
2362
elif sys.platform == "win32":
2363
def _local_concurrency():
2364
# This appears to return the number of cores.
2365
return os.environ.get('NUMBER_OF_PROCESSORS')
2367
def _local_concurrency():
2372
_cached_local_concurrency = None
2375
def local_concurrency(use_cache=True):
2376
"""Return how many processes can be run concurrently.
2378
Rely on platform specific implementations and default to 1 (one) if
2379
anything goes wrong.
2381
global _cached_local_concurrency
2383
if _cached_local_concurrency is not None and use_cache:
2384
return _cached_local_concurrency
2386
concurrency = os.environ.get('BRZ_CONCURRENCY', None)
2387
if concurrency is None:
2388
import multiprocessing
2390
concurrency = multiprocessing.cpu_count()
2391
except NotImplementedError:
2392
# multiprocessing.cpu_count() isn't implemented on all platforms
2394
concurrency = _local_concurrency()
2395
except (OSError, IOError):
2398
concurrency = int(concurrency)
2399
except (TypeError, ValueError):
2402
_cached_local_concurrency = concurrency
2406
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2407
"""A stream writer that doesn't decode str arguments."""
2409
def __init__(self, encode, stream, errors='strict'):
2410
codecs.StreamWriter.__init__(self, stream, errors)
2411
self.encode = encode
2413
def write(self, object):
2414
if isinstance(object, str):
2415
self.stream.write(object)
2417
data, _ = self.encode(object, self.errors)
2418
self.stream.write(data)
2421
if sys.platform == 'win32':
2422
def open_file(filename, mode='r', bufsize=-1):
2423
"""This function is used to override the ``open`` builtin.
2425
But it uses O_NOINHERIT flag so the file handle is not inherited by
2426
child processes. Deleting or renaming a closed file opened with this
2427
function is not blocking child processes.
2429
writing = 'w' in mode
2430
appending = 'a' in mode
2431
updating = '+' in mode
2432
binary = 'b' in mode
2435
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2436
# for flags for each modes.
2446
flags |= os.O_WRONLY
2447
flags |= os.O_CREAT | os.O_TRUNC
2452
flags |= os.O_WRONLY
2453
flags |= os.O_CREAT | os.O_APPEND
2458
flags |= os.O_RDONLY
2460
return os.fdopen(os.open(filename, flags), mode, bufsize)
2465
def available_backup_name(base, exists):
2466
"""Find a non-existing backup file name.
2468
This will *not* create anything, this only return a 'free' entry. This
2469
should be used for checking names in a directory below a locked
2470
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2471
Leap) and generally discouraged.
2473
:param base: The base name.
2475
:param exists: A callable returning True if the path parameter exists.
2478
name = "%s.~%d~" % (base, counter)
2481
name = "%s.~%d~" % (base, counter)
2485
def set_fd_cloexec(fd):
2486
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2487
support for this is not available.
2491
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2492
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2493
except (ImportError, AttributeError):
2494
# Either the fcntl module or specific constants are not present
2498
def find_executable_on_path(name):
2499
"""Finds an executable on the PATH.
2501
On Windows, this will try to append each extension in the PATHEXT
2502
environment variable to the name, if it cannot be found with the name
2505
:param name: The base name of the executable.
2506
:return: The path to the executable found or None.
2508
if sys.platform == 'win32':
2509
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2510
exts = [ext.lower() for ext in exts]
2511
base, ext = os.path.splitext(name)
2513
if ext.lower() not in exts:
2519
path = os.environ.get('PATH')
2520
if path is not None:
2521
path = path.split(os.pathsep)
2524
f = os.path.join(d, name) + ext
2525
if os.access(f, os.X_OK):
2527
if sys.platform == 'win32':
2528
app_path = win32utils.get_app_path(name)
2529
if app_path != name:
2534
def _posix_is_local_pid_dead(pid):
2535
"""True if pid doesn't correspond to live process on this machine"""
2537
# Special meaning of unix kill: just check if it's there.
2539
except OSError as e:
2540
if e.errno == errno.ESRCH:
2541
# On this machine, and really not found: as sure as we can be
2544
elif e.errno == errno.EPERM:
2545
# exists, though not ours
2548
trace.mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2549
# Don't really know.
2552
# Exists and our process: not dead.
2556
if sys.platform == "win32":
2557
is_local_pid_dead = win32utils.is_local_pid_dead
2559
is_local_pid_dead = _posix_is_local_pid_dead
2561
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2562
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
2563
if getattr(errno, name, None) is not None]
2566
def fdatasync(fileno):
2567
"""Flush file contents to disk if possible.
2569
:param fileno: Integer OS file handle.
2570
:raises TransportNotPossible: If flushing to disk is not possible.
2572
fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2576
except IOError as e:
2577
# See bug #1075108, on some platforms fdatasync exists, but can
2578
# raise ENOTSUP. However, we are calling fdatasync to be helpful
2579
# and reduce the chance of corruption-on-powerloss situations. It
2580
# is not a mandatory call, so it is ok to suppress failures.
2581
trace.mutter("ignoring error calling fdatasync: %s" % (e,))
2582
if getattr(e, 'errno', None) not in _fdatasync_ignored:
2586
def ensure_empty_directory_exists(path, exception_class):
2587
"""Make sure a local directory exists and is empty.
2589
If it does not exist, it is created. If it exists and is not empty, an
2590
instance of exception_class is raised.
2594
except OSError as e:
2595
if e.errno != errno.EEXIST:
2597
if os.listdir(path) != []:
2598
raise exception_class(path)
2601
def is_environment_error(evalue):
2602
"""True if exception instance is due to a process environment issue
2604
This includes OSError and IOError, but also other errors that come from
2605
the operating system or core libraries but are not subclasses of those.
2607
if isinstance(evalue, (EnvironmentError, select.error)):
2609
if sys.platform == "win32" and win32utils._is_pywintypes_error(evalue):