windows.py
713 lines
| 20.6 KiB
| text/x-python
|
PythonLexer
/ mercurial / windows.py
Martin Geisler
|
r8226 | # windows.py - Windows utility function implementations for Mercurial | ||
# | ||||
Raphaël Gomès
|
r47575 | # Copyright 2005-2009 Olivia Mackall <olivia@selenic.com> and others | ||
Martin Geisler
|
r8226 | # | ||
# This software may be used and distributed according to the terms of the | ||||
Matt Mackall
|
r10263 | # GNU General Public License version 2 or any later version. | ||
Matt Mackall
|
r7890 | |||
Gregory Szorc
|
r27360 | from __future__ import absolute_import | ||
Sune Foldager
|
r8421 | |||
Gregory Szorc
|
r27360 | import errno | ||
Augie Fackler
|
r44356 | import getpass | ||
Gregory Szorc
|
r27360 | import msvcrt | ||
import os | ||||
import re | ||||
import stat | ||||
Matt Harbison
|
r38502 | import string | ||
Gregory Szorc
|
r27360 | import sys | ||
from .i18n import _ | ||||
Gregory Szorc
|
r43359 | from .pycompat import getattr | ||
Gregory Szorc
|
r27360 | from . import ( | ||
encoding, | ||||
Augie Fackler
|
r33724 | error, | ||
Yuya Nishihara
|
r32367 | policy, | ||
Pulkit Goyal
|
r30612 | pycompat, | ||
Matt Harbison
|
r27436 | win32, | ||
Gregory Szorc
|
r27360 | ) | ||
Pulkit Goyal
|
r29760 | try: | ||
Matt Harbison
|
r44207 | import _winreg as winreg # pytype: disable=import-error | ||
Augie Fackler
|
r43346 | |||
Pulkit Goyal
|
r29760 | winreg.CloseKey | ||
except ImportError: | ||||
Matt Harbison
|
r44207 | # py2 only | ||
import winreg # pytype: disable=import-error | ||||
Pulkit Goyal
|
r29760 | |||
Augie Fackler
|
r43906 | osutil = policy.importmod('osutil') | ||
Yuya Nishihara
|
r32367 | |||
Matt Harbison
|
r35531 | getfsmountpoint = win32.getvolumename | ||
Matt Harbison
|
r35528 | getfstype = win32.getfstype | ||
Matt Mackall
|
r15016 | 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 | ||||
Bryan O'Sullivan
|
r17560 | split = os.path.split | ||
Matt Mackall
|
r15016 | testpid = win32.testpid | ||
unlink = win32.unlink | ||||
Adrian Buehlmann
|
r14985 | |||
Gregory Szorc
|
r25658 | umask = 0o022 | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Gregory Szorc
|
r26375 | 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. | ||||
""" | ||||
Augie Fackler
|
r43346 | |||
Gregory Szorc
|
r26375 | OPNONE = 0 | ||
OPREAD = 1 | ||||
OPWRITE = 2 | ||||
def __init__(self, fp): | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_fp', fp) | ||
object.__setattr__(self, '_lastop', 0) | ||||
Gregory Szorc
|
r26375 | |||
Matt Harbison
|
r31891 | def __enter__(self): | ||
Matt Harbison
|
r40974 | self._fp.__enter__() | ||
return self | ||||
Matt Harbison
|
r31891 | |||
def __exit__(self, exc_type, exc_val, exc_tb): | ||||
self._fp.__exit__(exc_type, exc_val, exc_tb) | ||||
Gregory Szorc
|
r26375 | 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): | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPNONE) | ||
Gregory Szorc
|
r26375 | return self._fp.seek(*args, **kwargs) | ||
def write(self, d): | ||||
if self._lastop == self.OPREAD: | ||||
self._noopseek() | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPWRITE) | ||
Gregory Szorc
|
r26375 | return self._fp.write(d) | ||
def writelines(self, *args, **kwargs): | ||||
if self._lastop == self.OPREAD: | ||||
self._noopeseek() | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPWRITE) | ||
Gregory Szorc
|
r26375 | return self._fp.writelines(*args, **kwargs) | ||
def read(self, *args, **kwargs): | ||||
if self._lastop == self.OPWRITE: | ||||
self._noopseek() | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPREAD) | ||
Gregory Szorc
|
r26375 | return self._fp.read(*args, **kwargs) | ||
def readline(self, *args, **kwargs): | ||||
if self._lastop == self.OPWRITE: | ||||
self._noopseek() | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPREAD) | ||
Gregory Szorc
|
r26375 | return self._fp.readline(*args, **kwargs) | ||
def readlines(self, *args, **kwargs): | ||||
if self._lastop == self.OPWRITE: | ||||
self._noopseek() | ||||
Augie Fackler
|
r43906 | object.__setattr__(self, '_lastop', self.OPREAD) | ||
Gregory Szorc
|
r26375 | return self._fp.readlines(*args, **kwargs) | ||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r39845 | class fdproxy(object): | ||
"""Wraps osutil.posixfile() to override the name attribute to reflect the | ||||
underlying file name. | ||||
""" | ||||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r39845 | def __init__(self, name, fp): | ||
self.name = name | ||||
self._fp = fp | ||||
def __enter__(self): | ||||
Matt Harbison
|
r40973 | self._fp.__enter__() | ||
# Return this wrapper for the context manager so that the name is | ||||
# still available. | ||||
return self | ||||
Matt Harbison
|
r39845 | |||
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) | ||||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r43347 | def posixfile(name, mode=b'r', buffering=-1): | ||
Adrian Buehlmann
|
r24069 | '''Open a file with even more POSIX-like semantics''' | ||
Sune Foldager
|
r8421 | try: | ||
Augie Fackler
|
r43346 | fp = osutil.posixfile(name, mode, buffering) # may raise WindowsError | ||
Matt Harbison
|
r24051 | |||
Matt Harbison
|
r39845 | # PyFile_FromFd() ignores the name, and seems to report fp.name as the | ||
# underlying file descriptor. | ||||
if pycompat.ispy3: | ||||
fp = fdproxy(name, fp) | ||||
Matt Harbison
|
r24051 | # The position when opening in append mode is implementation defined, so | ||
# make it consistent with other platforms, which position at EOF. | ||||
Augie Fackler
|
r43347 | if b'a' in mode: | ||
Adrian Buehlmann
|
r25462 | fp.seek(0, os.SEEK_END) | ||
Matt Harbison
|
r24051 | |||
Augie Fackler
|
r43347 | if b'+' in mode: | ||
Gregory Szorc
|
r26375 | return mixedfilemodewrapper(fp) | ||
Matt Harbison
|
r24051 | return fp | ||
Gregory Szorc
|
r25660 | except WindowsError as err: | ||
Adrian Buehlmann
|
r24069 | # convert to a friendlier exception | ||
Augie Fackler
|
r43346 | raise IOError( | ||
Augie Fackler
|
r43906 | err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror) | ||
Augie Fackler
|
r43346 | ) | ||
Matt Mackall
|
r7890 | |||
Yuya Nishihara
|
r32203 | # may be wrapped by win32mbcs extension | ||
listdir = osutil.listdir | ||||
Augie Fackler
|
r43346 | |||
Manuel Jacob
|
r45717 | # copied from .utils.procutil, remove after Python 2 support was dropped | ||
def _isatty(fp): | ||||
try: | ||||
return fp.isatty() | ||||
except AttributeError: | ||||
return False | ||||
Matt Harbison
|
r47949 | def get_password(): | ||
"""Prompt for password with echo off, using Windows getch(). | ||||
This shouldn't be called directly- use ``ui.getpass()`` instead, which | ||||
checks if the session is interactive first. | ||||
""" | ||||
pw = "" | ||||
while True: | ||||
c = msvcrt.getwch() | ||||
if c == '\r' or c == '\n': | ||||
break | ||||
if c == '\003': | ||||
raise KeyboardInterrupt | ||||
if c == '\b': | ||||
pw = pw[:-1] | ||||
else: | ||||
pw = pw + c | ||||
msvcrt.putwch('\r') | ||||
msvcrt.putwch('\n') | ||||
return encoding.strtolocal(pw) | ||||
Benoit Boissinot
|
r8778 | class winstdout(object): | ||
Augie Fackler
|
r46554 | """Some files on Windows misbehave. | ||
Manuel Jacob
|
r45705 | |||
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. | ||||
Augie Fackler
|
r46554 | """ | ||
Matt Mackall
|
r7890 | |||
def __init__(self, fp): | ||||
self.fp = fp | ||||
Manuel Jacob
|
r45717 | self.throttle = not pycompat.ispy3 and _isatty(fp) | ||
Matt Mackall
|
r7890 | |||
def __getattr__(self, key): | ||||
return getattr(self.fp, key) | ||||
def close(self): | ||||
try: | ||||
self.fp.close() | ||||
Idan Kamara
|
r14004 | except IOError: | ||
pass | ||||
Matt Mackall
|
r7890 | |||
def write(self, s): | ||||
try: | ||||
Manuel Jacob
|
r45708 | if not self.throttle: | ||
return self.fp.write(s) | ||||
Matt Mackall
|
r7890 | # 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 | ||||
Gregory Szorc
|
r25660 | except IOError as inst: | ||
Sune Foldager
|
r38575 | if inst.errno != 0 and not win32.lasterrorwaspipeerror(inst): | ||
Matt Mackall
|
r10282 | raise | ||
Matt Mackall
|
r7890 | self.close() | ||
Augie Fackler
|
r43906 | raise IOError(errno.EPIPE, 'Broken pipe') | ||
Matt Mackall
|
r7890 | |||
def flush(self): | ||||
try: | ||||
return self.fp.flush() | ||||
Gregory Szorc
|
r25660 | except IOError as inst: | ||
Sune Foldager
|
r38575 | if not win32.lasterrorwaspipeerror(inst): | ||
Matt Mackall
|
r10282 | raise | ||
Augie Fackler
|
r43906 | raise IOError(errno.EPIPE, 'Broken pipe') | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def openhardlinks(): | ||
Matt Harbison
|
r44374 | return True | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14231 | def parsepatchoutput(output_line): | ||
timeless
|
r8761 | """parses the output produced by patch and returns the filename""" | ||
Matt Mackall
|
r7890 | pf = output_line[14:] | ||
Augie Fackler
|
r43347 | if pf[0] == b'`': | ||
Augie Fackler
|
r43346 | pf = pf[1:-1] # Remove the quotes | ||
Matt Mackall
|
r7890 | return pf | ||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def sshargs(sshcmd, host, user, port): | ||
'''Build argument list for ssh or Plink''' | ||||
Augie Fackler
|
r43347 | 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'/'): | ||||
Augie Fackler
|
r33724 | raise error.Abort( | ||
Augie Fackler
|
r43347 | _(b'illegal ssh hostname or username starting with - or /: %s') | ||
Augie Fackler
|
r43346 | % args | ||
) | ||||
Jun Wu
|
r33732 | args = shellquote(args) | ||
if port: | ||||
Augie Fackler
|
r43347 | args = b'%s %s %s' % (pflag, shellquote(port), args) | ||
Jun Wu
|
r33732 | return args | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14232 | def setflags(f, l, x): | ||
Matt Mackall
|
r7890 | pass | ||
Augie Fackler
|
r43346 | |||
Boris Feld
|
r41325 | def copymode(src, dst, mode=None, enforcewritable=False): | ||
Adrian Buehlmann
|
r15011 | pass | ||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13879 | def checkexec(path): | ||
return False | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13890 | def checklink(path): | ||
return False | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14233 | def setbinary(fd): | ||
Matt Mackall
|
r7890 | # When run without console, pipes may expose invalid | ||
# fileno(), usually set to -1. | ||||
Augie Fackler
|
r14969 | fno = getattr(fd, 'fileno', None) | ||
if fno is not None and fno() >= 0: | ||||
Matt Harbison
|
r44207 | msvcrt.setmode(fno(), os.O_BINARY) # pytype: disable=module-attr | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def pconvert(path): | ||
Augie Fackler
|
r43347 | return path.replace(pycompat.ossep, b'/') | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def localpath(path): | ||
Augie Fackler
|
r43347 | return path.replace(b'/', b'\\') | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def normpath(path): | ||
return pconvert(os.path.normpath(path)) | ||||
Augie Fackler
|
r43346 | |||
FUJIWARA Katsunori
|
r15671 | def normcase(path): | ||
Augie Fackler
|
r43346 | return encoding.upper(path) # NTFS compares via upper() | ||
Matt Mackall
|
r15488 | |||
Siddharth Agarwal
|
r24598 | # see posix.py for definitions | ||
normcasespec = encoding.normcasespecs.upper | ||||
normcasefallback = encoding.upperfallback | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def samestat(s1, s2): | ||
return False | ||||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r38502 | 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) | ||||
Matt Harbison
|
r38747 | 'cmd "$var1 ${var2} %var3%" $var1 ${var2} \\' | ||
Matt Harbison
|
r38646 | >>> # $$ is not special. %% is not special either, but can be the end and | ||
>>> # start of consecutive variables | ||||
Matt Harbison
|
r38502 | >>> shelltocmdexe(b"cmd $$ %% %var1%%var2%", e) | ||
Matt Harbison
|
r38646 | 'cmd $$ %% %var1%%var2%' | ||
Matt Harbison
|
r38502 | >>> # No double substitution | ||
>>> shelltocmdexe(b"$var1 %var1%", {b'var1': b'%var2%', b'var2': b'boom'}) | ||||
'%var1% %var1%' | ||||
Matt Harbison
|
r38748 | >>> # Tilde expansion | ||
>>> shelltocmdexe(b"~/dir ~\dir2 ~tmpfile \~/", {}) | ||||
'%USERPROFILE%/dir %USERPROFILE%\\dir2 ~tmpfile ~/' | ||||
Matt Harbison
|
r38502 | """ | ||
Matt Harbison
|
r38748 | if not any(c in path for c in b"$'~"): | ||
Matt Harbison
|
r38502 | return path | ||
varchars = pycompat.sysbytes(string.ascii_letters + string.digits) + b'_-' | ||||
res = b'' | ||||
index = 0 | ||||
pathlen = len(path) | ||||
while index < pathlen: | ||||
Augie Fackler
|
r43346 | c = path[index : index + 1] | ||
if c == b'\'': # no expansion within single quotes | ||||
path = path[index + 1 :] | ||||
Matt Harbison
|
r38502 | pathlen = len(path) | ||
try: | ||||
index = path.index(b'\'') | ||||
Matt Harbison
|
r38747 | res += b'"' + path[:index] + b'"' | ||
Matt Harbison
|
r38502 | except ValueError: | ||
res += c + path | ||||
index = pathlen - 1 | ||||
elif c == b'%': # variable | ||||
Augie Fackler
|
r43346 | path = path[index + 1 :] | ||
Matt Harbison
|
r38502 | pathlen = len(path) | ||
try: | ||||
index = path.index(b'%') | ||||
except ValueError: | ||||
res += b'%' + path | ||||
index = pathlen - 1 | ||||
else: | ||||
var = path[:index] | ||||
res += b'%' + var + b'%' | ||||
Matt Harbison
|
r38646 | elif c == b'$': # variable | ||
Augie Fackler
|
r43346 | if path[index + 1 : index + 2] == b'{': | ||
path = path[index + 2 :] | ||||
Matt Harbison
|
r38502 | pathlen = len(path) | ||
try: | ||||
index = path.index(b'}') | ||||
var = path[:index] | ||||
# See below for why empty variables are handled specially | ||||
Matt Harbison
|
r39946 | if env.get(var, b'') != b'': | ||
Matt Harbison
|
r38502 | res += b'%' + var + b'%' | ||
else: | ||||
res += b'${' + var + b'}' | ||||
except ValueError: | ||||
res += b'${' + path | ||||
index = pathlen - 1 | ||||
else: | ||||
var = b'' | ||||
index += 1 | ||||
Augie Fackler
|
r43346 | c = path[index : index + 1] | ||
Matt Harbison
|
r38502 | while c != b'' and c in varchars: | ||
var += c | ||||
index += 1 | ||||
Augie Fackler
|
r43346 | c = path[index : index + 1] | ||
Matt Harbison
|
r38502 | # 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. | ||||
Matt Harbison
|
r39946 | if env.get(var, b'') != b'': | ||
Matt Harbison
|
r38502 | res += b'%' + var + b'%' | ||
else: | ||||
res += b'$' + var | ||||
Matt Harbison
|
r39946 | if c != b'': | ||
Matt Harbison
|
r38502 | index -= 1 | ||
Augie Fackler
|
r43346 | elif ( | ||
c == b'~' | ||||
and index + 1 < pathlen | ||||
and path[index + 1 : index + 2] in (b'\\', b'/') | ||||
): | ||||
Augie Fackler
|
r43347 | res += b"%USERPROFILE%" | ||
Augie Fackler
|
r43346 | elif ( | ||
c == b'\\' | ||||
and index + 1 < pathlen | ||||
and path[index + 1 : index + 2] in (b'$', b'~') | ||||
): | ||||
Matt Harbison
|
r38748 | # Skip '\', but only if it is escaping $ or ~ | ||
Augie Fackler
|
r43346 | res += path[index + 1 : index + 2] | ||
Matt Harbison
|
r38502 | index += 1 | ||
else: | ||||
res += c | ||||
index += 1 | ||||
return res | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | # 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 | ||||
timeless@mozdev.org
|
r17505 | # the number of backslashes that precede double quotes and add another | ||
Matt Mackall
|
r7890 | # backslash before every double quote (being careful with the double | ||
# quote we've appended to the end) | ||||
_quotere = None | ||||
FUJIWARA Katsunori
|
r23682 | _needsshellquote = None | ||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def shellquote(s): | ||
Matt Harbison
|
r24908 | r""" | ||
Yuya Nishihara
|
r34133 | >>> shellquote(br'C:\Users\xyz') | ||
Matt Harbison
|
r24908 | '"C:\\Users\\xyz"' | ||
Yuya Nishihara
|
r34133 | >>> shellquote(br'C:\Users\xyz/mixed') | ||
Matt Harbison
|
r24908 | '"C:\\Users\\xyz/mixed"' | ||
>>> # Would be safe not to quote too, since it is all double backslashes | ||||
Yuya Nishihara
|
r34133 | >>> shellquote(br'C:\\Users\\xyz') | ||
Matt Harbison
|
r24908 | '"C:\\\\Users\\\\xyz"' | ||
>>> # But this must be quoted | ||||
Yuya Nishihara
|
r34133 | >>> shellquote(br'C:\\Users\\xyz/abc') | ||
Matt Harbison
|
r24908 | '"C:\\\\Users\\\\xyz/abc"' | ||
""" | ||||
Matt Mackall
|
r7890 | global _quotere | ||
if _quotere is None: | ||||
Matt Harbison
|
r39680 | _quotere = re.compile(br'(\\*)("|\\$)') | ||
FUJIWARA Katsunori
|
r23682 | global _needsshellquote | ||
if _needsshellquote is None: | ||||
Matt Harbison
|
r24885 | # ":" 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 | ||||
# "\". | ||||
Matt Harbison
|
r39680 | _needsshellquote = re.compile(br'[^a-zA-Z0-9._:/-]').search | ||
Yuya Nishihara
|
r24108 | if s and not _needsshellquote(s) and not _quotere.search(s): | ||
FUJIWARA Katsunori
|
r23682 | # "s" shouldn't have to be quoted | ||
return s | ||||
Matt Harbison
|
r39680 | return b'"%s"' % _quotere.sub(br'\1\1\\\2', s) | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r36433 | def _unquote(s): | ||
if s.startswith(b'"') and s.endswith(b'"'): | ||||
return s[1:-1] | ||||
return s | ||||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r36433 | def shellsplit(s): | ||
"""Parse a command string in cmd.exe way (best-effort)""" | ||||
return pycompat.maplist(_unquote, pycompat.shlexsplit(s, posix=False)) | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | # if you change this stub into a real check, please try to implement the | ||
# username and groupname functions above, too. | ||||
Martin Geisler
|
r8657 | def isowner(st): | ||
Matt Mackall
|
r7890 | return True | ||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14271 | def findexe(command): | ||
Augie Fackler
|
r46554 | """Find executable for command searching like cmd.exe does. | ||
Matt Mackall
|
r7890 | 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. | ||||
Augie Fackler
|
r46554 | If command isn't found None is returned.""" | ||
Augie Fackler
|
r43347 | pathext = encoding.environ.get(b'PATHEXT', b'.COM;.EXE;.BAT;.CMD') | ||
Pulkit Goyal
|
r30612 | pathexts = [ext for ext in pathext.lower().split(pycompat.ospathsep)] | ||
Matt Mackall
|
r7890 | if os.path.splitext(command)[1].lower() in pathexts: | ||
Augie Fackler
|
r43347 | pathexts = [b''] | ||
Matt Mackall
|
r7890 | |||
def findexisting(pathcommand): | ||||
Matt Harbison
|
r44226 | """Will append extension (if needed) and return existing file""" | ||
Matt Mackall
|
r7890 | for ext in pathexts: | ||
executable = pathcommand + ext | ||||
if os.path.exists(executable): | ||||
return executable | ||||
return None | ||||
Pulkit Goyal
|
r30615 | if pycompat.ossep in command: | ||
Matt Mackall
|
r7890 | return findexisting(command) | ||
Augie Fackler
|
r43347 | for path in encoding.environ.get(b'PATH', b'').split(pycompat.ospathsep): | ||
Matt Mackall
|
r7890 | executable = findexisting(os.path.join(path, command)) | ||
if executable is not None: | ||||
return executable | ||||
Steve Borho
|
r10156 | return findexisting(os.path.expanduser(os.path.expandvars(command))) | ||
Matt Mackall
|
r7890 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r32291 | _wantedkinds = {stat.S_IFREG, stat.S_IFLNK} | ||
Bryan O'Sullivan
|
r18017 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | def statfiles(files): | ||
Augie Fackler
|
r46554 | """Stat each file in files. Yield each stat, or None if a file | ||
Bryan O'Sullivan
|
r18017 | does not exist or has a type we don't care about. | ||
Augie Fackler
|
r46554 | Cluster and cache stat per directory to minimize number of OS stat calls.""" | ||
Augie Fackler
|
r43346 | dircache = {} # dirname -> filename -> status | None if file does not exist | ||
Bryan O'Sullivan
|
r18017 | getkind = stat.S_IFMT | ||
Matt Mackall
|
r7890 | for nf in files: | ||
Augie Fackler
|
r43346 | nf = normcase(nf) | ||
Shun-ichi GOTO
|
r9099 | dir, base = os.path.split(nf) | ||
if not dir: | ||||
Augie Fackler
|
r43347 | dir = b'.' | ||
Matt Mackall
|
r7890 | cache = dircache.get(dir, None) | ||
if cache is None: | ||||
try: | ||||
Augie Fackler
|
r44937 | dmap = { | ||
normcase(n): s | ||||
for n, k, s in listdir(dir, True) | ||||
if getkind(s.st_mode) in _wantedkinds | ||||
} | ||||
Gregory Szorc
|
r25660 | except OSError as err: | ||
Matt Mackall
|
r7890 | # Python >= 2.5 returns ENOENT and adds winerror field | ||
# EINVAL is raised if dir is not a directory. | ||||
Augie Fackler
|
r43346 | if err.errno not in (errno.ENOENT, errno.EINVAL, errno.ENOTDIR): | ||
Matt Mackall
|
r7890 | raise | ||
dmap = {} | ||||
cache = dircache.setdefault(dir, dmap) | ||||
yield cache.get(base, None) | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | 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.""" | ||||
Augie Fackler
|
r44356 | if not uid: | ||
return pycompat.fsencode(getpass.getuser()) | ||||
Matt Mackall
|
r7890 | return None | ||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r7890 | 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 | ||||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r39940 | def readlink(pathname): | ||
return pycompat.fsencode(os.readlink(pycompat.fsdecode(pathname))) | ||||
Augie Fackler
|
r43346 | |||
FUJIWARA Katsunori
|
r24692 | def removedirs(name): | ||
Henrik Stuart
|
r8364 | """special version of os.removedirs that does not remove symlinked | ||
directories or junction points if they actually contain files""" | ||||
Yuya Nishihara
|
r32203 | if listdir(name): | ||
Henrik Stuart
|
r8364 | return | ||
os.rmdir(name) | ||||
head, tail = os.path.split(name) | ||||
if not tail: | ||||
head, tail = os.path.split(head) | ||||
while head and tail: | ||||
try: | ||||
Yuya Nishihara
|
r32203 | if listdir(head): | ||
Henrik Stuart
|
r8364 | return | ||
os.rmdir(head) | ||||
Idan Kamara
|
r14004 | except (ValueError, OSError): | ||
Henrik Stuart
|
r8364 | break | ||
head, tail = os.path.split(head) | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r9549 | def rename(src, dst): | ||
'''atomically rename file src to dst, replacing dst if it exists''' | ||||
try: | ||||
os.rename(src, dst) | ||||
Gregory Szorc
|
r25660 | except OSError as e: | ||
Adrian Buehlmann
|
r13278 | if e.errno != errno.EEXIST: | ||
raise | ||||
Adrian Buehlmann
|
r13280 | unlink(dst) | ||
Adrian Buehlmann
|
r9549 | os.rename(src, dst) | ||
Augie Fackler
|
r43346 | |||
Patrick Mezard
|
r10239 | def gethgcmd(): | ||
Matt Harbison
|
r39755 | return [encoding.strtolocal(arg) for arg in [sys.executable] + sys.argv[:1]] | ||
Patrick Mezard
|
r10239 | |||
Augie Fackler
|
r43346 | |||
Patrick Mezard
|
r11138 | def groupmembers(name): | ||
# Don't support groups on Windows for now | ||||
Brodie Rao
|
r16687 | raise KeyError | ||
Patrick Mezard
|
r11138 | |||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14926 | def isexec(f): | ||
return False | ||||
Augie Fackler
|
r43346 | |||
Idan Kamara
|
r14927 | class cachestat(object): | ||
def __init__(self, path): | ||||
pass | ||||
def cacheable(self): | ||||
return False | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r16807 | def lookupreg(key, valname=None, scope=None): | ||
Augie Fackler
|
r46554 | """Look up a key/value name in the Windows registry. | ||
Adrian Buehlmann
|
r16807 | |||
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). | ||||
Augie Fackler
|
r46554 | """ | ||
Adrian Buehlmann
|
r16807 | if scope is None: | ||
Pulkit Goyal
|
r29760 | scope = (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE) | ||
Adrian Buehlmann
|
r16807 | elif not isinstance(scope, (list, tuple)): | ||
scope = (scope,) | ||||
for s in scope: | ||||
try: | ||||
Matt Harbison
|
r39679 | with winreg.OpenKey(s, encoding.strfromlocal(key)) as hkey: | ||
Matt Harbison
|
r40302 | name = valname and encoding.strfromlocal(valname) or valname | ||
val = winreg.QueryValueEx(hkey, name)[0] | ||||
Matt Harbison
|
r39679 | # never let a Unicode string escape into the wild | ||
return encoding.unitolocal(val) | ||||
Adrian Buehlmann
|
r16807 | except EnvironmentError: | ||
pass | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r8614 | expandglobs = True | ||
Bryan O'Sullivan
|
r18868 | |||
Augie Fackler
|
r43346 | |||
Bryan O'Sullivan
|
r18868 | def statislink(st): | ||
'''check whether a stat result is a symlink''' | ||||
return False | ||||
Augie Fackler
|
r43346 | |||
Bryan O'Sullivan
|
r18868 | def statisexec(st): | ||
'''check whether a stat result is an executable file''' | ||||
return False | ||||
Gregory Szorc
|
r22245 | |||
Augie Fackler
|
r43346 | |||
Pierre-Yves David
|
r25420 | def poll(fds): | ||
# see posix.py for description | ||||
raise NotImplementedError() | ||||
Augie Fackler
|
r43346 | |||
Gregory Szorc
|
r22245 | def readpipe(pipe): | ||
"""Read all available data from a pipe.""" | ||||
chunks = [] | ||||
while True: | ||||
Matt Harbison
|
r24653 | size = win32.peekpipe(pipe) | ||
Gregory Szorc
|
r22245 | if not size: | ||
break | ||||
s = pipe.read(size) | ||||
if not s: | ||||
break | ||||
chunks.append(s) | ||||
Augie Fackler
|
r43347 | return b''.join(chunks) | ||
Yuya Nishihara
|
r29530 | |||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r29530 | def bindunixsocket(sock, path): | ||
Augie Fackler
|
r43906 | raise NotImplementedError('unsupported platform') | ||