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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
25
25
from bzrlib.lazy_import import lazy_import
26
26
lazy_import(globals(), """
28
27
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,
31
# We need to import both shutil and rmtree as we export the later on posix
32
# and need the former on windows
34
from shutil import rmtree
37
# We need to import both tempfile and mkdtemp as we export the later on posix
38
# and need the former on windows
42
from tempfile import (
40
from tempfile import mkdtemp
47
43
from bzrlib import (
50
from bzrlib.i18n import gettext
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
53
from bzrlib.symbol_versioning import (
69
65
from bzrlib import symbol_versioning
68
# Cross platform wall-clock time functionality with decent resolution.
69
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
70
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
71
# synchronized with ``time.time()``, this is only meant to be used to find
72
# delta times by subtracting from another call to this function.
73
timer_func = time.time
74
if sys.platform == 'win32':
75
timer_func = time.clock
72
77
# On win32, O_BINARY is used to indicate the file should
73
78
# be opened in binary mode, rather than text mode.
74
79
# On other platforms, O_BINARY doesn't exist, because
75
80
# they always open in binary mode, so it is okay to
76
# OR with 0 on those platforms
81
# OR with 0 on those platforms.
82
# O_NOINHERIT and O_TEXT exists only on win32 too.
77
83
O_BINARY = getattr(os, 'O_BINARY', 0)
84
O_TEXT = getattr(os, 'O_TEXT', 0)
85
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
88
def get_unicode_argv():
90
user_encoding = get_user_encoding()
91
return [a.decode(user_encoding) for a in sys.argv[1:]]
92
except UnicodeDecodeError:
93
raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
94
"application locale.").format(a, user_encoding))
80
97
def make_readonly(filename):
166
191
if e.errno == errno.ENOENT:
169
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
194
raise errors.BzrError(gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
172
197
def fancy_rename(old, new, rename_func, unlink_func):
173
198
"""A fancy rename, when you don't have atomic rename.
175
200
:param old: The old path, to rename from
176
201
:param new: The new path, to rename to
177
202
:param rename_func: The potentially non-atomic rename function
178
:param unlink_func: A way to delete the target file if the full rename succeeds
203
:param unlink_func: A way to delete the target file if the full rename
181
206
# sftp rename doesn't allow overwriting, so play tricks:
182
207
base = os.path.basename(new)
183
208
dirname = os.path.dirname(new)
184
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
209
# callers use different encodings for the paths so the following MUST
210
# respect that. We rely on python upcasting to unicode if new is unicode
211
# and keeping a str if not.
212
tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
213
os.getpid(), rand_chars(10))
185
214
tmp_name = pathjoin(dirname, tmp_name)
187
216
# Rename the file out of the way, but keep track if it didn't exist
279
318
# /path => C:/path
280
319
path = unicode(path)
281
320
# check for absolute path
282
drive = _nt_splitdrive(path)[0]
321
drive = ntpath.splitdrive(path)[0]
283
322
if drive == '' and path[:2] not in('//','\\\\'):
284
323
cwd = os.getcwdu()
285
324
# we cannot simply os.path.join cwd and path
286
325
# because os.path.join('C:','/path') produce '/path'
287
326
# and this is incorrect
288
327
if path[:1] in ('/','\\'):
289
cwd = _nt_splitdrive(cwd)[0]
328
cwd = ntpath.splitdrive(cwd)[0]
291
330
path = cwd + '\\' + path
292
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
331
return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
295
334
def _win32_realpath(path):
296
# Real _nt_realpath doesn't have a problem with a unicode cwd
297
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
335
# Real ntpath.realpath doesn't have a problem with a unicode cwd
336
return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
300
339
def _win32_pathjoin(*args):
301
return _nt_join(*args).replace('\\', '/')
340
return ntpath.join(*args).replace('\\', '/')
304
343
def _win32_normpath(path):
305
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
344
return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
308
347
def _win32_getcwd():
827
939
if (f == '..') or (f is None) or (f == ''):
828
raise errors.BzrError("sorry, %r not allowed in path" % f)
940
raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
829
941
return pathjoin(*p)
944
def parent_directories(filename):
945
"""Return the list of parent directories, deepest first.
947
For example, parent_directories("a/b/c") -> ["a/b", "a"].
950
parts = splitpath(dirname(filename))
952
parents.append(joinpath(parts))
957
_extension_load_failures = []
960
def failed_to_load_extension(exception):
961
"""Handle failing to load a binary extension.
963
This should be called from the ImportError block guarding the attempt to
964
import the native extension. If this function returns, the pure-Python
965
implementation should be loaded instead::
968
>>> import bzrlib._fictional_extension_pyx
969
>>> except ImportError, e:
970
>>> bzrlib.osutils.failed_to_load_extension(e)
971
>>> import bzrlib._fictional_extension_py
973
# NB: This docstring is just an example, not a doctest, because doctest
974
# currently can't cope with the use of lazy imports in this namespace --
977
# This currently doesn't report the failure at the time it occurs, because
978
# they tend to happen very early in startup when we can't check config
979
# files etc, and also we want to report all failures but not spam the user
981
exception_str = str(exception)
982
if exception_str not in _extension_load_failures:
983
trace.mutter("failed to load compiled extension: %s" % exception_str)
984
_extension_load_failures.append(exception_str)
987
def report_extension_load_failures():
988
if not _extension_load_failures:
990
if config.GlobalStack().get('ignore_missing_extensions'):
992
# the warnings framework should by default show this only once
993
from bzrlib.trace import warning
995
"bzr: warning: some compiled extensions could not be loaded; "
996
"see <https://answers.launchpad.net/bzr/+faq/703>")
997
# we no longer show the specific missing extensions here, because it makes
998
# the message too long and scary - see
999
# https://bugs.launchpad.net/bzr/+bug/430529
833
1003
from bzrlib._chunks_to_lines_pyx import chunks_to_lines
1004
except ImportError, e:
1005
failed_to_load_extension(e)
835
1006
from bzrlib._chunks_to_lines_py import chunks_to_lines
875
1046
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.
883
1049
def delete_any(path):
884
"""Delete a file or directory."""
1050
"""Delete a file, symlink or directory.
1052
Will delete even if readonly.
1055
_delete_file_or_dir(path)
1056
except (OSError, IOError), e:
1057
if e.errno in (errno.EPERM, errno.EACCES):
1058
# make writable and try again
1061
except (OSError, IOError):
1063
_delete_file_or_dir(path)
1068
def _delete_file_or_dir(path):
1069
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1070
# Forgiveness than Permission (EAFP) because:
1071
# - root can damage a solaris file system by using unlink,
1072
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1073
# EACCES, OSX: EPERM) when invoked on a directory.
885
1074
if isdir(path): # Takes care of symlinks
1029
1243
# but for now, we haven't optimized...
1030
1244
return [canonical_relpath(base, p) for p in paths]
1247
def decode_filename(filename):
1248
"""Decode the filename using the filesystem encoding
1250
If it is unicode, it is returned.
1251
Otherwise it is decoded from the the filesystem's encoding. If decoding
1252
fails, a errors.BadFilenameEncoding exception is raised.
1254
if type(filename) is unicode:
1257
return filename.decode(_fs_enc)
1258
except UnicodeDecodeError:
1259
raise errors.BadFilenameEncoding(filename, _fs_enc)
1032
1262
def safe_unicode(unicode_or_utf8_string):
1033
1263
"""Coerce unicode_or_utf8_string into unicode.
1035
1265
If it is unicode, it is returned.
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.
1266
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1267
wrapped in a BzrBadParameterNotUnicode exception.
1040
1269
if isinstance(unicode_or_utf8_string, unicode):
1041
1270
return unicode_or_utf8_string
1154
1383
normalized_filename = _inaccessible_normalized_filename
1386
def set_signal_handler(signum, handler, restart_syscall=True):
1387
"""A wrapper for signal.signal that also calls siginterrupt(signum, False)
1388
on platforms that support that.
1390
:param restart_syscall: if set, allow syscalls interrupted by a signal to
1391
automatically restart (by calling `signal.siginterrupt(signum,
1392
False)`). May be ignored if the feature is not available on this
1393
platform or Python version.
1397
siginterrupt = signal.siginterrupt
1399
# This python implementation doesn't provide signal support, hence no
1402
except AttributeError:
1403
# siginterrupt doesn't exist on this platform, or for this version
1405
siginterrupt = lambda signum, flag: None
1407
def sig_handler(*args):
1408
# Python resets the siginterrupt flag when a signal is
1409
# received. <http://bugs.python.org/issue8354>
1410
# As a workaround for some cases, set it back the way we want it.
1411
siginterrupt(signum, False)
1412
# Now run the handler function passed to set_signal_handler.
1415
sig_handler = handler
1416
old_handler = signal.signal(signum, sig_handler)
1418
siginterrupt(signum, False)
1422
default_terminal_width = 80
1423
"""The default terminal width for ttys.
1425
This is defined so that higher levels can share a common fallback value when
1426
terminal_width() returns None.
1429
# Keep some state so that terminal_width can detect if _terminal_size has
1430
# returned a different size since the process started. See docstring and
1431
# comments of terminal_width for details.
1432
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1433
_terminal_size_state = 'no_data'
1434
_first_terminal_size = None
1157
1436
def terminal_width():
1158
"""Return estimated terminal width."""
1159
if sys.platform == 'win32':
1160
return win32utils.get_console_size()[0]
1437
"""Return terminal width.
1439
None is returned if the width can't established precisely.
1442
- if BZR_COLUMNS is set, returns its value
1443
- if there is no controlling terminal, returns None
1444
- query the OS, if the queried size has changed since the last query,
1446
- if COLUMNS is set, returns its value,
1447
- if the OS has a value (even though it's never changed), return its value.
1449
From there, we need to query the OS to get the size of the controlling
1452
On Unices we query the OS by:
1453
- get termios.TIOCGWINSZ
1454
- if an error occurs or a negative value is obtained, returns None
1456
On Windows we query the OS by:
1457
- win32utils.get_console_size() decides,
1458
- returns None on error (provided default value)
1460
# Note to implementors: if changing the rules for determining the width,
1461
# make sure you've considered the behaviour in these cases:
1462
# - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1463
# - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1465
# - (add more interesting cases here, if you find any)
1466
# Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1467
# but we don't want to register a signal handler because it is impossible
1468
# to do so without risking EINTR errors in Python <= 2.6.5 (see
1469
# <http://bugs.python.org/issue8354>). Instead we check TIOCGWINSZ every
1470
# time so we can notice if the reported size has changed, which should have
1473
# If BZR_COLUMNS is set, take it, user is always right
1474
# Except if they specified 0 in which case, impose no limit here
1476
width = int(os.environ['BZR_COLUMNS'])
1477
except (KeyError, ValueError):
1479
if width is not None:
1485
isatty = getattr(sys.stdout, 'isatty', None)
1486
if isatty is None or not isatty():
1487
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1491
width, height = os_size = _terminal_size(None, None)
1492
global _first_terminal_size, _terminal_size_state
1493
if _terminal_size_state == 'no_data':
1494
_first_terminal_size = os_size
1495
_terminal_size_state = 'unchanged'
1496
elif (_terminal_size_state == 'unchanged' and
1497
_first_terminal_size != os_size):
1498
_terminal_size_state = 'changed'
1500
# If the OS claims to know how wide the terminal is, and this value has
1501
# ever changed, use that.
1502
if _terminal_size_state == 'changed':
1503
if width is not None and width > 0:
1506
# If COLUMNS is set, use it.
1508
return int(os.environ['COLUMNS'])
1509
except (KeyError, ValueError):
1512
# Finally, use an unchanged size from the OS, if we have one.
1513
if _terminal_size_state == 'unchanged':
1514
if width is not None and width > 0:
1517
# The width could not be determined.
1521
def _win32_terminal_size(width, height):
1522
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1523
return width, height
1526
def _ioctl_terminal_size(width, height):
1163
1528
import struct, fcntl, termios
1164
1529
s = struct.pack('HHHH', 0, 0, 0, 0)
1165
1530
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1166
width = struct.unpack('HHHH', x)[1]
1531
height, width = struct.unpack('HHHH', x)[0:2]
1532
except (IOError, AttributeError):
1171
width = int(os.environ['COLUMNS'])
1534
return width, height
1536
_terminal_size = None
1537
"""Returns the terminal size as (width, height).
1539
:param width: Default value for width.
1540
:param height: Default value for height.
1542
This is defined specifically for each OS and query the size of the controlling
1543
terminal. If any error occurs, the provided default values should be returned.
1545
if sys.platform == 'win32':
1546
_terminal_size = _win32_terminal_size
1548
_terminal_size = _ioctl_terminal_size
1180
1551
def supports_executable():
1604
2005
return socket.gethostname().decode(get_user_encoding())
1607
def recv_all(socket, bytes):
2008
# We must not read/write any more than 64k at a time from/to a socket so we
2009
# don't risk "no buffer space available" errors on some platforms. Windows in
2010
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2012
MAX_SOCKET_CHUNK = 64 * 1024
2014
_end_of_stream_errors = [errno.ECONNRESET]
2015
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2016
_eno = getattr(errno, _eno, None)
2017
if _eno is not None:
2018
_end_of_stream_errors.append(_eno)
2022
def read_bytes_from_socket(sock, report_activity=None,
2023
max_read_size=MAX_SOCKET_CHUNK):
2024
"""Read up to max_read_size of bytes from sock and notify of progress.
2026
Translates "Connection reset by peer" into file-like EOF (return an
2027
empty string rather than raise an error), and repeats the recv if
2028
interrupted by a signal.
2032
bytes = sock.recv(max_read_size)
2033
except socket.error, e:
2035
if eno in _end_of_stream_errors:
2036
# The connection was closed by the other side. Callers expect
2037
# an empty string to signal end-of-stream.
2039
elif eno == errno.EINTR:
2040
# Retry the interrupted recv.
2044
if report_activity is not None:
2045
report_activity(len(bytes), 'read')
2049
def recv_all(socket, count):
1608
2050
"""Receive an exact number of bytes.
1610
2052
Regular Socket.recv() may return less than the requested number of bytes,
1611
dependning on what's in the OS buffer. MSG_WAITALL is not available
2053
depending on what's in the OS buffer. MSG_WAITALL is not available
1612
2054
on all platforms, but this should work everywhere. This will return
1613
2055
less than the requested amount if the remote end closes.
1615
2057
This isn't optimized and is intended mostly for use in testing.
1618
while len(b) < bytes:
1619
new = until_no_eintr(socket.recv, bytes - len(b))
2060
while len(b) < count:
2061
new = read_bytes_from_socket(socket, None, count - len(b))
1626
def send_all(socket, bytes):
2068
def send_all(sock, bytes, report_activity=None):
1627
2069
"""Send all bytes on a socket.
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.
2071
Breaks large blocks in smaller chunks to avoid buffering limitations on
2072
some platforms, and catches EINTR which may be thrown if the send is
2073
interrupted by a signal.
2075
This is preferred to socket.sendall(), because it avoids portability bugs
2076
and provides activity reporting.
2078
:param report_activity: Call this as bytes are read, see
2079
Transport._report_activity
1633
for pos in xrange(0, len(bytes), chunk_size):
1634
until_no_eintr(socket.sendall, bytes[pos:pos+chunk_size])
2082
byte_count = len(bytes)
2083
while sent_total < byte_count:
2085
sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
2086
except socket.error, e:
2087
if e.args[0] != errno.EINTR:
2091
report_activity(sent, 'write')
2094
def connect_socket(address):
2095
# Slight variation of the socket.create_connection() function (provided by
2096
# python-2.6) that can fail if getaddrinfo returns an empty list. We also
2097
# provide it for previous python versions. Also, we don't use the timeout
2098
# parameter (provided by the python implementation) so we don't implement
2100
err = socket.error('getaddrinfo returns an empty list')
2101
host, port = address
2102
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2103
af, socktype, proto, canonname, sa = res
2106
sock = socket.socket(af, socktype, proto)
2110
except socket.error, err:
2111
# 'err' is now the most recent error
2112
if sock is not None:
1637
2117
def dereference_path(path):
1689
2171
from bzrlib._readdir_pyx import UTF8DirReader
1690
2172
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2173
except ImportError, e:
2174
# This is one time where we won't warn that an extension failed to
2175
# load. The extension is never available on Windows anyway.
1692
2176
from bzrlib._readdir_py import (
1693
2177
_kind_from_mode as file_kind_from_stat_mode
1695
2179
return file_kind_from_stat_mode(mode)
1696
2180
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1699
def file_kind(f, _lstat=os.lstat):
2182
def file_stat(f, _lstat=os.lstat):
1701
return file_kind_from_stat_mode(_lstat(f).st_mode)
1702
2186
except OSError, e:
1703
2187
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1704
2188
raise errors.NoSuchFile(f)
2191
def file_kind(f, _lstat=os.lstat):
2192
stat_value = file_stat(f, _lstat)
2193
return file_kind_from_stat_mode(stat_value.st_mode)
1708
2195
def until_no_eintr(f, *a, **kw):
1709
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2196
"""Run f(*a, **kw), retrying if an EINTR error occurs.
2198
WARNING: you must be certain that it is safe to retry the call repeatedly
2199
if EINTR does occur. This is typically only true for low-level operations
2200
like os.read. If in any doubt, don't use this.
2202
Keep in mind that this is not a complete solution to EINTR. There is
2203
probably code in the Python standard library and other dependencies that
2204
may encounter EINTR if a signal arrives (and there is signal handler for
2205
that signal). So this function can reduce the impact for IO that bzrlib
2206
directly controls, but it is not a complete solution.
1710
2208
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
1734
2256
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2259
if sys.platform.startswith('linux'):
2260
def _local_concurrency():
2262
return os.sysconf('SC_NPROCESSORS_ONLN')
2263
except (ValueError, OSError, AttributeError):
2265
elif sys.platform == 'darwin':
2266
def _local_concurrency():
2267
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2268
stdout=subprocess.PIPE).communicate()[0]
2269
elif "bsd" in sys.platform:
2270
def _local_concurrency():
2271
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2272
stdout=subprocess.PIPE).communicate()[0]
2273
elif sys.platform == 'sunos5':
2274
def _local_concurrency():
2275
return subprocess.Popen(['psrinfo', '-p',],
2276
stdout=subprocess.PIPE).communicate()[0]
2277
elif sys.platform == "win32":
2278
def _local_concurrency():
2279
# This appears to return the number of cores.
2280
return os.environ.get('NUMBER_OF_PROCESSORS')
2282
def _local_concurrency():
2287
_cached_local_concurrency = None
2289
def local_concurrency(use_cache=True):
2290
"""Return how many processes can be run concurrently.
2292
Rely on platform specific implementations and default to 1 (one) if
2293
anything goes wrong.
2295
global _cached_local_concurrency
2297
if _cached_local_concurrency is not None and use_cache:
2298
return _cached_local_concurrency
2300
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2301
if concurrency is None:
2303
import multiprocessing
2305
# multiprocessing is only available on Python >= 2.6
2307
concurrency = _local_concurrency()
2308
except (OSError, IOError):
2311
concurrency = multiprocessing.cpu_count()
2313
concurrency = int(concurrency)
2314
except (TypeError, ValueError):
2317
_cached_concurrency = concurrency
2321
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2322
"""A stream writer that doesn't decode str arguments."""
2324
def __init__(self, encode, stream, errors='strict'):
2325
codecs.StreamWriter.__init__(self, stream, errors)
2326
self.encode = encode
2328
def write(self, object):
2329
if type(object) is str:
2330
self.stream.write(object)
2332
data, _ = self.encode(object, self.errors)
2333
self.stream.write(data)
2335
if sys.platform == 'win32':
2336
def open_file(filename, mode='r', bufsize=-1):
2337
"""This function is used to override the ``open`` builtin.
2339
But it uses O_NOINHERIT flag so the file handle is not inherited by
2340
child processes. Deleting or renaming a closed file opened with this
2341
function is not blocking child processes.
2343
writing = 'w' in mode
2344
appending = 'a' in mode
2345
updating = '+' in mode
2346
binary = 'b' in mode
2349
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2350
# for flags for each modes.
2360
flags |= os.O_WRONLY
2361
flags |= os.O_CREAT | os.O_TRUNC
2366
flags |= os.O_WRONLY
2367
flags |= os.O_CREAT | os.O_APPEND
2372
flags |= os.O_RDONLY
2374
return os.fdopen(os.open(filename, flags), mode, bufsize)
2379
def getuser_unicode():
2380
"""Return the username as unicode.
2383
user_encoding = get_user_encoding()
2384
username = getpass.getuser().decode(user_encoding)
2385
except UnicodeDecodeError:
2386
raise errors.BzrError("Can't decode username as %s." % \
2388
except ImportError, e:
2389
if sys.platform != 'win32':
2391
if str(e) != 'No module named pwd':
2393
# https://bugs.launchpad.net/bzr/+bug/660174
2394
# getpass.getuser() is unable to return username on Windows
2395
# if there is no USERNAME environment variable set.
2396
# That could be true if bzr is running as a service,
2397
# e.g. running `bzr serve` as a service on Windows.
2398
# We should not fail with traceback in this case.
2399
username = u'UNKNOWN'
2403
def available_backup_name(base, exists):
2404
"""Find a non-existing backup file name.
2406
This will *not* create anything, this only return a 'free' entry. This
2407
should be used for checking names in a directory below a locked
2408
tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2409
Leap) and generally discouraged.
2411
:param base: The base name.
2413
:param exists: A callable returning True if the path parameter exists.
2416
name = "%s.~%d~" % (base, counter)
2419
name = "%s.~%d~" % (base, counter)
2423
def set_fd_cloexec(fd):
2424
"""Set a Unix file descriptor's FD_CLOEXEC flag. Do nothing if platform
2425
support for this is not available.
2429
old = fcntl.fcntl(fd, fcntl.F_GETFD)
2430
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2431
except (ImportError, AttributeError):
2432
# Either the fcntl module or specific constants are not present
2436
def find_executable_on_path(name):
2437
"""Finds an executable on the PATH.
2439
On Windows, this will try to append each extension in the PATHEXT
2440
environment variable to the name, if it cannot be found with the name
2443
:param name: The base name of the executable.
2444
:return: The path to the executable found or None.
2446
path = os.environ.get('PATH')
2449
path = path.split(os.pathsep)
2450
if sys.platform == 'win32':
2451
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2452
exts = [ext.lower() for ext in exts]
2453
base, ext = os.path.splitext(name)
2455
if ext.lower() not in exts:
2463
f = os.path.join(d, name) + ext
2464
if os.access(f, os.X_OK):
2469
def _posix_is_local_pid_dead(pid):
2470
"""True if pid doesn't correspond to live process on this machine"""
2472
# Special meaning of unix kill: just check if it's there.
2475
if e.errno == errno.ESRCH:
2476
# On this machine, and really not found: as sure as we can be
2479
elif e.errno == errno.EPERM:
2480
# exists, though not ours
2483
mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2484
# Don't really know.
2487
# Exists and our process: not dead.
2490
if sys.platform == "win32":
2491
is_local_pid_dead = win32utils.is_local_pid_dead
2493
is_local_pid_dead = _posix_is_local_pid_dead
2496
def fdatasync(fileno):
2497
"""Flush file contents to disk if possible.
2499
:param fileno: Integer OS file handle.
2500
:raises TransportNotPossible: If flushing to disk is not possible.
2502
fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))