##// END OF EJS Templates
copies: no longer cache the ChangedFiles during copy tracing...
copies: no longer cache the ChangedFiles during copy tracing Now that the copies information for both parents are processed all at once, we no longer needs to cache this information, so we simplify the code. The simpler code is also a (tiny) bit faster overall. Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mercurial x_revs_x_added_0_copies ad6b123de1c7 39cfcef4f463 : 1 revs, 0.000041 s, 0.000041 s, +0.000000 s, × 1.0000, 41 µs/rev mercurial x_revs_x_added_x_copies 2b1c78674230 0c1d10351869 : 6 revs, 0.000102 s, 0.000096 s, -0.000006 s, × 0.9412, 16 µs/rev mercurial x000_revs_x000_added_x_copies 81f8ff2a9bf2 dd3267698d84 : 1032 revs, 0.004254 s, 0.004039 s, -0.000215 s, × 0.9495, 3 µs/rev pypy x_revs_x_added_0_copies aed021ee8ae8 099ed31b181b : 9 revs, 0.000282 s, 0.000189 s, -0.000093 s, × 0.6702, 21 µs/rev pypy x_revs_x000_added_0_copies 4aa4e1f8e19a 359343b9ac0e : 1 revs, 0.000048 s, 0.000047 s, -0.000001 s, × 0.9792, 47 µs/rev pypy x_revs_x_added_x_copies ac52eb7bbbb0 72e022663155 : 7 revs, 0.000211 s, 0.000103 s, -0.000108 s, × 0.4882, 14 µs/rev pypy x_revs_x00_added_x_copies c3b14617fbd7 ace7255d9a26 : 1 revs, 0.000375 s, 0.000286 s, -0.000089 s, × 0.7627, 286 µs/rev pypy x_revs_x000_added_x000_copies df6f7a526b60 a83dc6a2d56f : 6 revs, 0.010574 s, 0.010436 s, -0.000138 s, × 0.9869, 1739 µs/rev pypy x000_revs_xx00_added_0_copies 89a76aede314 2f22446ff07e : 4785 revs, 0.049974 s, 0.047465 s, -0.002509 s, × 0.9498, 9 µs/rev pypy x000_revs_x000_added_x_copies 8a3b5bfd266e 2c68e87c3efe : 6780 revs, 0.084300 s, 0.082351 s, -0.001949 s, × 0.9769, 12 µs/rev pypy x000_revs_x000_added_x000_copies 89a76aede314 7b3dda341c84 : 5441 revs, 0.060128 s, 0.058757 s, -0.001371 s, × 0.9772, 10 µs/rev pypy x0000_revs_x_added_0_copies d1defd0dc478 c9cb1334cc78 : 43645 revs, 0.686542 s, 0.674129 s, -0.012413 s, × 0.9819, 15 µs/rev pypy x0000_revs_xx000_added_0_copies bf2c629d0071 4ffed77c095c : 2 revs, 0.009277 s, 0.009434 s, +0.000157 s, × 1.0169, 4717 µs/rev pypy x0000_revs_xx000_added_x000_copies 08ea3258278e d9fa043f30c0 : 11316 revs, 0.114733 s, 0.111935 s, -0.002798 s, × 0.9756, 9 µs/rev netbeans x_revs_x_added_0_copies fb0955ffcbcd a01e9239f9e7 : 2 revs, 0.000081 s, 0.000078 s, -0.000003 s, × 0.9630, 39 µs/rev netbeans x_revs_x000_added_0_copies 6f360122949f 20eb231cc7d0 : 2 revs, 0.000107 s, 0.000106 s, -0.000001 s, × 0.9907, 53 µs/rev netbeans x_revs_x_added_x_copies 1ada3faf6fb6 5a39d12eecf4 : 3 revs, 0.000173 s, 0.000162 s, -0.000011 s, × 0.9364, 54 µs/rev netbeans x_revs_x00_added_x_copies 35be93ba1e2c 9eec5e90c05f : 9 revs, 0.000698 s, 0.000695 s, -0.000003 s, × 0.9957, 77 µs/rev netbeans x000_revs_xx00_added_0_copies eac3045b4fdd 51d4ae7f1290 : 1421 revs, 0.009248 s, 0.008901 s, -0.000347 s, × 0.9625, 6 µs/rev netbeans x000_revs_x000_added_x_copies e2063d266acd 6081d72689dc : 1533 revs, 0.015446 s, 0.014333 s, -0.001113 s, × 0.9279, 9 µs/rev netbeans x000_revs_x000_added_x000_copies ff453e9fee32 411350406ec2 : 5750 revs, 0.074373 s, 0.071998 s, -0.002375 s, × 0.9681, 12 µs/rev netbeans x0000_revs_xx000_added_x000_copies 588c2d1ced70 1aad62e59ddd : 66949 revs, 0.639870 s, 0.615346 s, -0.024524 s, × 0.9617, 9 µs/rev mozilla-central x_revs_x_added_0_copies 3697f962bb7b 7015fcdd43a2 : 2 revs, 0.000088 s, 0.000085 s, -0.000003 s, × 0.9659, 42 µs/rev mozilla-central x_revs_x000_added_0_copies dd390860c6c9 40d0c5bed75d : 8 revs, 0.000199 s, 0.000199 s, +0.000000 s, × 1.0000, 24 µs/rev mozilla-central x_revs_x_added_x_copies 8d198483ae3b 14207ffc2b2f : 9 revs, 0.000171 s, 0.000169 s, -0.000002 s, × 0.9883, 18 µs/rev mozilla-central x_revs_x00_added_x_copies 98cbc58cc6bc 446a150332c3 : 7 revs, 0.000592 s, 0.000590 s, -0.000002 s, × 0.9966, 84 µs/rev mozilla-central x_revs_x000_added_x000_copies 3c684b4b8f68 0a5e72d1b479 : 3 revs, 0.003151 s, 0.003122 s, -0.000029 s, × 0.9908, 1040 µs/rev mozilla-central x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.061612 s, 0.061192 s, -0.000420 s, × 0.9932, 10198 µs/rev mozilla-central x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.005381 s, 0.005137 s, -0.000244 s, × 0.9547, 3 µs/rev mozilla-central x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.003742 s, 0.003585 s, -0.000157 s, × 0.9580, 87 µs/rev mozilla-central x000_revs_x000_added_x000_copies 7c97034feb78 4407bd0c6330 : 7839 revs, 0.061983 s, 0.060592 s, -0.001391 s, × 0.9776, 7 µs/rev mozilla-central x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.019861 s, 0.019596 s, -0.000265 s, × 0.9867, 31 µs/rev mozilla-central x0000_revs_xx000_added_x000_copies f78c615a656c 96a38b690156 : 30263 revs, 0.188101 s, 0.183558 s, -0.004543 s, × 0.9758, 6 µs/rev mozilla-central x00000_revs_x0000_added_x0000_copies 6832ae71433c 4c222a1d9a00 : 153721 revs, 1.806696 s, 1.758083 s, -0.048613 s, × 0.9731, 11 µs/rev mozilla-central x00000_revs_x00000_added_x000_copies 76caed42cf7c 1daa622bbe42 : 204976 revs, 2.682987 s, 2.592955 s, -0.090032 s, × 0.9664, 12 µs/rev mozilla-try x_revs_x_added_0_copies aaf6dde0deb8 9790f499805a : 2 revs, 0.000852 s, 0.000844 s, -0.000008 s, × 0.9906, 422 µs/rev mozilla-try x_revs_x000_added_0_copies d8d0222927b4 5bb8ce8c7450 : 2 revs, 0.000859 s, 0.000861 s, +0.000002 s, × 1.0023, 430 µs/rev mozilla-try x_revs_x_added_x_copies 092fcca11bdb 936255a0384a : 4 revs, 0.000150 s, 0.000150 s, +0.000000 s, × 1.0000, 37 µs/rev mozilla-try x_revs_x00_added_x_copies b53d2fadbdb5 017afae788ec : 2 revs, 0.001158 s, 0.001166 s, +0.000008 s, × 1.0069, 583 µs/rev mozilla-try x_revs_x000_added_x000_copies 20408ad61ce5 6f0ee96e21ad : 1 revs, 0.027240 s, 0.027359 s, +0.000119 s, × 1.0044, 27359 µs/rev mozilla-try x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.062824 s, 0.061848 s, -0.000976 s, × 0.9845, 10308 µs/rev mozilla-try x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.005463 s, 0.005110 s, -0.000353 s, × 0.9354, 3 µs/rev mozilla-try x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.004238 s, 0.004168 s, -0.000070 s, × 0.9835, 101 µs/rev mozilla-try x000_revs_x000_added_x000_copies 1346fd0130e4 4c65cbdabc1f : 6657 revs, 0.064113 s, 0.063414 s, -0.000699 s, × 0.9891, 9 µs/rev mozilla-try x0000_revs_x_added_0_copies 63519bfd42ee a36a2a865d92 : 40314 revs, 0.294063 s, 0.288301 s, -0.005762 s, × 0.9804, 7 µs/rev mozilla-try x0000_revs_x_added_x_copies 9fe69ff0762d bcabf2a78927 : 38690 revs, 0.281493 s, 0.275798 s, -0.005695 s, × 0.9798, 7 µs/rev mozilla-try x0000_revs_xx000_added_x_copies 156f6e2674f2 4d0f2c178e66 : 8598 revs, 0.076323 s, 0.074640 s, -0.001683 s, × 0.9779, 8 µs/rev mozilla-try x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.020390 s, 0.020327 s, -0.000063 s, × 0.9969, 33 µs/rev mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 97052 revs, 3.023879 s, 2.970385 s, -0.053494 s, × 0.9823, 30 µs/rev mozilla-try x0000_revs_x0000_added_x0000_copies e928c65095ed e951f4ad123a : 52031 revs, 0.735549 s, 0.719432 s, -0.016117 s, × 0.9781, 13 µs/rev mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 363753 revs, 18.568900 s, 18.165143 s, -0.403757 s, × 0.9783, 49 µs/rev mozilla-try x00000_revs_x00000_added_0_copies dc8a3ca7010e d16fde900c9c : 34414 revs, 0.502584 s, 0.486769 s, -0.015815 s, × 0.9685, 14 µs/rev mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 362229 revs, 18.356645 s, 17.913924 s, -0.442721 s, × 0.9759, 49 µs/rev mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 359344 revs, 18.250393 s, 17.660113 s, -0.590280 s, × 0.9677, 49 µs/rev mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 192665 revs, 2.792459 s, 2.709446 s, -0.083013 s, × 0.9703, 14 µs/rev mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 228985 revs, 107.697264 s, 107.796891 s, +0.099627 s, × 1.0009, 470 µs/rev mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 382065 revs, 63.961040 s, 63.575217 s, -0.385823 s, × 0.9940, 166 µs/rev Differential Revision: https://phab.mercurial-scm.org/D9423

File last commit:

r46554:89a2afe3 default
r46765:a132aa59 default
Show More
windows.py
691 lines | 20.0 KiB | text/x-python | PythonLexer
# windows.py - Windows utility function implementations for Mercurial
#
# Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import errno
import getpass
import msvcrt
import os
import re
import stat
import string
import sys
from .i18n import _
from .pycompat import getattr
from . import (
encoding,
error,
policy,
pycompat,
win32,
)
try:
import _winreg as winreg # pytype: disable=import-error
winreg.CloseKey
except ImportError:
# py2 only
import winreg # pytype: disable=import-error
osutil = policy.importmod('osutil')
getfsmountpoint = win32.getvolumename
getfstype = win32.getfstype
getuser = win32.getuser
hidewindow = win32.hidewindow
makedir = win32.makedir
nlinks = win32.nlinks
oslink = win32.oslink
samedevice = win32.samedevice
samefile = win32.samefile
setsignalhandler = win32.setsignalhandler
spawndetached = win32.spawndetached
split = os.path.split
testpid = win32.testpid
unlink = win32.unlink
umask = 0o022
class mixedfilemodewrapper(object):
"""Wraps a file handle when it is opened in read/write mode.
fopen() and fdopen() on Windows have a specific-to-Windows requirement
that files opened with mode r+, w+, or a+ make a call to a file positioning
function when switching between reads and writes. Without this extra call,
Python will raise a not very intuitive "IOError: [Errno 0] Error."
This class wraps posixfile instances when the file is opened in read/write
mode and automatically adds checks or inserts appropriate file positioning
calls when necessary.
"""
OPNONE = 0
OPREAD = 1
OPWRITE = 2
def __init__(self, fp):
object.__setattr__(self, '_fp', fp)
object.__setattr__(self, '_lastop', 0)
def __enter__(self):
self._fp.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._fp.__exit__(exc_type, exc_val, exc_tb)
def __getattr__(self, name):
return getattr(self._fp, name)
def __setattr__(self, name, value):
return self._fp.__setattr__(name, value)
def _noopseek(self):
self._fp.seek(0, os.SEEK_CUR)
def seek(self, *args, **kwargs):
object.__setattr__(self, '_lastop', self.OPNONE)
return self._fp.seek(*args, **kwargs)
def write(self, d):
if self._lastop == self.OPREAD:
self._noopseek()
object.__setattr__(self, '_lastop', self.OPWRITE)
return self._fp.write(d)
def writelines(self, *args, **kwargs):
if self._lastop == self.OPREAD:
self._noopeseek()
object.__setattr__(self, '_lastop', self.OPWRITE)
return self._fp.writelines(*args, **kwargs)
def read(self, *args, **kwargs):
if self._lastop == self.OPWRITE:
self._noopseek()
object.__setattr__(self, '_lastop', self.OPREAD)
return self._fp.read(*args, **kwargs)
def readline(self, *args, **kwargs):
if self._lastop == self.OPWRITE:
self._noopseek()
object.__setattr__(self, '_lastop', self.OPREAD)
return self._fp.readline(*args, **kwargs)
def readlines(self, *args, **kwargs):
if self._lastop == self.OPWRITE:
self._noopseek()
object.__setattr__(self, '_lastop', self.OPREAD)
return self._fp.readlines(*args, **kwargs)
class fdproxy(object):
"""Wraps osutil.posixfile() to override the name attribute to reflect the
underlying file name.
"""
def __init__(self, name, fp):
self.name = name
self._fp = fp
def __enter__(self):
self._fp.__enter__()
# Return this wrapper for the context manager so that the name is
# still available.
return self
def __exit__(self, exc_type, exc_value, traceback):
self._fp.__exit__(exc_type, exc_value, traceback)
def __iter__(self):
return iter(self._fp)
def __getattr__(self, name):
return getattr(self._fp, name)
def posixfile(name, mode=b'r', buffering=-1):
'''Open a file with even more POSIX-like semantics'''
try:
fp = osutil.posixfile(name, mode, buffering) # may raise WindowsError
# PyFile_FromFd() ignores the name, and seems to report fp.name as the
# underlying file descriptor.
if pycompat.ispy3:
fp = fdproxy(name, fp)
# The position when opening in append mode is implementation defined, so
# make it consistent with other platforms, which position at EOF.
if b'a' in mode:
fp.seek(0, os.SEEK_END)
if b'+' in mode:
return mixedfilemodewrapper(fp)
return fp
except WindowsError as err:
# convert to a friendlier exception
raise IOError(
err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror)
)
# may be wrapped by win32mbcs extension
listdir = osutil.listdir
# copied from .utils.procutil, remove after Python 2 support was dropped
def _isatty(fp):
try:
return fp.isatty()
except AttributeError:
return False
class winstdout(object):
"""Some files on Windows misbehave.
When writing to a broken pipe, EINVAL instead of EPIPE may be raised.
When writing too many bytes to a console at the same, a "Not enough space"
error may happen. Python 3 already works around that.
"""
def __init__(self, fp):
self.fp = fp
self.throttle = not pycompat.ispy3 and _isatty(fp)
def __getattr__(self, key):
return getattr(self.fp, key)
def close(self):
try:
self.fp.close()
except IOError:
pass
def write(self, s):
try:
if not self.throttle:
return self.fp.write(s)
# This is workaround for "Not enough space" error on
# writing large size of data to console.
limit = 16000
l = len(s)
start = 0
while start < l:
end = start + limit
self.fp.write(s[start:end])
start = end
except IOError as inst:
if inst.errno != 0 and not win32.lasterrorwaspipeerror(inst):
raise
self.close()
raise IOError(errno.EPIPE, 'Broken pipe')
def flush(self):
try:
return self.fp.flush()
except IOError as inst:
if not win32.lasterrorwaspipeerror(inst):
raise
raise IOError(errno.EPIPE, 'Broken pipe')
def openhardlinks():
return True
def parsepatchoutput(output_line):
"""parses the output produced by patch and returns the filename"""
pf = output_line[14:]
if pf[0] == b'`':
pf = pf[1:-1] # Remove the quotes
return pf
def sshargs(sshcmd, host, user, port):
'''Build argument list for ssh or Plink'''
pflag = b'plink' in sshcmd.lower() and b'-P' or b'-p'
args = user and (b"%s@%s" % (user, host)) or host
if args.startswith(b'-') or args.startswith(b'/'):
raise error.Abort(
_(b'illegal ssh hostname or username starting with - or /: %s')
% args
)
args = shellquote(args)
if port:
args = b'%s %s %s' % (pflag, shellquote(port), args)
return args
def setflags(f, l, x):
pass
def copymode(src, dst, mode=None, enforcewritable=False):
pass
def checkexec(path):
return False
def checklink(path):
return False
def setbinary(fd):
# When run without console, pipes may expose invalid
# fileno(), usually set to -1.
fno = getattr(fd, 'fileno', None)
if fno is not None and fno() >= 0:
msvcrt.setmode(fno(), os.O_BINARY) # pytype: disable=module-attr
def pconvert(path):
return path.replace(pycompat.ossep, b'/')
def localpath(path):
return path.replace(b'/', b'\\')
def normpath(path):
return pconvert(os.path.normpath(path))
def normcase(path):
return encoding.upper(path) # NTFS compares via upper()
# see posix.py for definitions
normcasespec = encoding.normcasespecs.upper
normcasefallback = encoding.upperfallback
def samestat(s1, s2):
return False
def shelltocmdexe(path, env):
r"""Convert shell variables in the form $var and ${var} inside ``path``
to %var% form. Existing Windows style variables are left unchanged.
The variables are limited to the given environment. Unknown variables are
left unchanged.
>>> e = {b'var1': b'v1', b'var2': b'v2', b'var3': b'v3'}
>>> # Only valid values are expanded
>>> shelltocmdexe(b'cmd $var1 ${var2} %var3% $missing ${missing} %missing%',
... e)
'cmd %var1% %var2% %var3% $missing ${missing} %missing%'
>>> # Single quote prevents expansion, as does \$ escaping
>>> shelltocmdexe(b"cmd '$var1 ${var2} %var3%' \$var1 \${var2} \\", e)
'cmd "$var1 ${var2} %var3%" $var1 ${var2} \\'
>>> # $$ is not special. %% is not special either, but can be the end and
>>> # start of consecutive variables
>>> shelltocmdexe(b"cmd $$ %% %var1%%var2%", e)
'cmd $$ %% %var1%%var2%'
>>> # No double substitution
>>> shelltocmdexe(b"$var1 %var1%", {b'var1': b'%var2%', b'var2': b'boom'})
'%var1% %var1%'
>>> # Tilde expansion
>>> shelltocmdexe(b"~/dir ~\dir2 ~tmpfile \~/", {})
'%USERPROFILE%/dir %USERPROFILE%\\dir2 ~tmpfile ~/'
"""
if not any(c in path for c in b"$'~"):
return path
varchars = pycompat.sysbytes(string.ascii_letters + string.digits) + b'_-'
res = b''
index = 0
pathlen = len(path)
while index < pathlen:
c = path[index : index + 1]
if c == b'\'': # no expansion within single quotes
path = path[index + 1 :]
pathlen = len(path)
try:
index = path.index(b'\'')
res += b'"' + path[:index] + b'"'
except ValueError:
res += c + path
index = pathlen - 1
elif c == b'%': # variable
path = path[index + 1 :]
pathlen = len(path)
try:
index = path.index(b'%')
except ValueError:
res += b'%' + path
index = pathlen - 1
else:
var = path[:index]
res += b'%' + var + b'%'
elif c == b'$': # variable
if path[index + 1 : index + 2] == b'{':
path = path[index + 2 :]
pathlen = len(path)
try:
index = path.index(b'}')
var = path[:index]
# See below for why empty variables are handled specially
if env.get(var, b'') != b'':
res += b'%' + var + b'%'
else:
res += b'${' + var + b'}'
except ValueError:
res += b'${' + path
index = pathlen - 1
else:
var = b''
index += 1
c = path[index : index + 1]
while c != b'' and c in varchars:
var += c
index += 1
c = path[index : index + 1]
# Some variables (like HG_OLDNODE) may be defined, but have an
# empty value. Those need to be skipped because when spawning
# cmd.exe to run the hook, it doesn't replace %VAR% for an empty
# VAR, and that really confuses things like revset expressions.
# OTOH, if it's left in Unix format and the hook runs sh.exe, it
# will substitute to an empty string, and everything is happy.
if env.get(var, b'') != b'':
res += b'%' + var + b'%'
else:
res += b'$' + var
if c != b'':
index -= 1
elif (
c == b'~'
and index + 1 < pathlen
and path[index + 1 : index + 2] in (b'\\', b'/')
):
res += b"%USERPROFILE%"
elif (
c == b'\\'
and index + 1 < pathlen
and path[index + 1 : index + 2] in (b'$', b'~')
):
# Skip '\', but only if it is escaping $ or ~
res += path[index + 1 : index + 2]
index += 1
else:
res += c
index += 1
return res
# A sequence of backslashes is special iff it precedes a double quote:
# - if there's an even number of backslashes, the double quote is not
# quoted (i.e. it ends the quoted region)
# - if there's an odd number of backslashes, the double quote is quoted
# - in both cases, every pair of backslashes is unquoted into a single
# backslash
# (See http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx )
# So, to quote a string, we must surround it in double quotes, double
# the number of backslashes that precede double quotes and add another
# backslash before every double quote (being careful with the double
# quote we've appended to the end)
_quotere = None
_needsshellquote = None
def shellquote(s):
r"""
>>> shellquote(br'C:\Users\xyz')
'"C:\\Users\\xyz"'
>>> shellquote(br'C:\Users\xyz/mixed')
'"C:\\Users\\xyz/mixed"'
>>> # Would be safe not to quote too, since it is all double backslashes
>>> shellquote(br'C:\\Users\\xyz')
'"C:\\\\Users\\\\xyz"'
>>> # But this must be quoted
>>> shellquote(br'C:\\Users\\xyz/abc')
'"C:\\\\Users\\\\xyz/abc"'
"""
global _quotere
if _quotere is None:
_quotere = re.compile(br'(\\*)("|\\$)')
global _needsshellquote
if _needsshellquote is None:
# ":" is also treated as "safe character", because it is used as a part
# of path name on Windows. "\" is also part of a path name, but isn't
# safe because shlex.split() (kind of) treats it as an escape char and
# drops it. It will leave the next character, even if it is another
# "\".
_needsshellquote = re.compile(br'[^a-zA-Z0-9._:/-]').search
if s and not _needsshellquote(s) and not _quotere.search(s):
# "s" shouldn't have to be quoted
return s
return b'"%s"' % _quotere.sub(br'\1\1\\\2', s)
def _unquote(s):
if s.startswith(b'"') and s.endswith(b'"'):
return s[1:-1]
return s
def shellsplit(s):
"""Parse a command string in cmd.exe way (best-effort)"""
return pycompat.maplist(_unquote, pycompat.shlexsplit(s, posix=False))
# if you change this stub into a real check, please try to implement the
# username and groupname functions above, too.
def isowner(st):
return True
def findexe(command):
"""Find executable for command searching like cmd.exe does.
If command is a basename then PATH is searched for command.
PATH isn't searched if command is an absolute or relative path.
An extension from PATHEXT is found and added if not present.
If command isn't found None is returned."""
pathext = encoding.environ.get(b'PATHEXT', b'.COM;.EXE;.BAT;.CMD')
pathexts = [ext for ext in pathext.lower().split(pycompat.ospathsep)]
if os.path.splitext(command)[1].lower() in pathexts:
pathexts = [b'']
def findexisting(pathcommand):
"""Will append extension (if needed) and return existing file"""
for ext in pathexts:
executable = pathcommand + ext
if os.path.exists(executable):
return executable
return None
if pycompat.ossep in command:
return findexisting(command)
for path in encoding.environ.get(b'PATH', b'').split(pycompat.ospathsep):
executable = findexisting(os.path.join(path, command))
if executable is not None:
return executable
return findexisting(os.path.expanduser(os.path.expandvars(command)))
_wantedkinds = {stat.S_IFREG, stat.S_IFLNK}
def statfiles(files):
"""Stat each file in files. Yield each stat, or None if a file
does not exist or has a type we don't care about.
Cluster and cache stat per directory to minimize number of OS stat calls."""
dircache = {} # dirname -> filename -> status | None if file does not exist
getkind = stat.S_IFMT
for nf in files:
nf = normcase(nf)
dir, base = os.path.split(nf)
if not dir:
dir = b'.'
cache = dircache.get(dir, None)
if cache is None:
try:
dmap = {
normcase(n): s
for n, k, s in listdir(dir, True)
if getkind(s.st_mode) in _wantedkinds
}
except OSError as err:
# Python >= 2.5 returns ENOENT and adds winerror field
# EINVAL is raised if dir is not a directory.
if err.errno not in (errno.ENOENT, errno.EINVAL, errno.ENOTDIR):
raise
dmap = {}
cache = dircache.setdefault(dir, dmap)
yield cache.get(base, None)
def username(uid=None):
"""Return the name of the user with the given uid.
If uid is None, return the name of the current user."""
if not uid:
return pycompat.fsencode(getpass.getuser())
return None
def groupname(gid=None):
"""Return the name of the group with the given gid.
If gid is None, return the name of the current group."""
return None
def readlink(pathname):
return pycompat.fsencode(os.readlink(pycompat.fsdecode(pathname)))
def removedirs(name):
"""special version of os.removedirs that does not remove symlinked
directories or junction points if they actually contain files"""
if listdir(name):
return
os.rmdir(name)
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
while head and tail:
try:
if listdir(head):
return
os.rmdir(head)
except (ValueError, OSError):
break
head, tail = os.path.split(head)
def rename(src, dst):
'''atomically rename file src to dst, replacing dst if it exists'''
try:
os.rename(src, dst)
except OSError as e:
if e.errno != errno.EEXIST:
raise
unlink(dst)
os.rename(src, dst)
def gethgcmd():
return [encoding.strtolocal(arg) for arg in [sys.executable] + sys.argv[:1]]
def groupmembers(name):
# Don't support groups on Windows for now
raise KeyError
def isexec(f):
return False
class cachestat(object):
def __init__(self, path):
pass
def cacheable(self):
return False
def lookupreg(key, valname=None, scope=None):
"""Look up a key/value name in the Windows registry.
valname: value name. If unspecified, the default value for the key
is used.
scope: optionally specify scope for registry lookup, this can be
a sequence of scopes to look up in order. Default (CURRENT_USER,
LOCAL_MACHINE).
"""
if scope is None:
scope = (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE)
elif not isinstance(scope, (list, tuple)):
scope = (scope,)
for s in scope:
try:
with winreg.OpenKey(s, encoding.strfromlocal(key)) as hkey:
name = valname and encoding.strfromlocal(valname) or valname
val = winreg.QueryValueEx(hkey, name)[0]
# never let a Unicode string escape into the wild
return encoding.unitolocal(val)
except EnvironmentError:
pass
expandglobs = True
def statislink(st):
'''check whether a stat result is a symlink'''
return False
def statisexec(st):
'''check whether a stat result is an executable file'''
return False
def poll(fds):
# see posix.py for description
raise NotImplementedError()
def readpipe(pipe):
"""Read all available data from a pipe."""
chunks = []
while True:
size = win32.peekpipe(pipe)
if not size:
break
s = pipe.read(size)
if not s:
break
chunks.append(s)
return b''.join(chunks)
def bindunixsocket(sock, path):
raise NotImplementedError('unsupported platform')