Quote arguments with carets for cmd.exe

Carets introduce a difficult situation since they are essentially
"lossy" when parses. Consider this in cmd.exe:

    > echo "foo^bar"
    "foo^bar"
    > echo foo^^bar
    foo^bar

The two commands produce different results, but are both parsed by the
shell as `foo^bar`, and there's essentially no sensible way to tell what
was actually passed in. This implementation assumes the quoted variation
(the first) since it is easier to implement, and arguably the more common
case.
This commit is contained in:
Tzu-ping Chung
2018-11-28 19:22:47 +08:00
parent f4c325c668
commit 6a93e6cf44
3 changed files with 27 additions and 2 deletions
+1
View File
@@ -0,0 +1 @@
Quote command arguments with carets (``^``) on Windows to work around unintended shell escapes.
+17 -2
View File
@@ -70,14 +70,29 @@ class Script(object):
Foul characters include:
* Whitespaces.
* Carets (^). (pypa/pipenv#3307)
* Parentheses in the command. (pypa/pipenv#3168)
Carets introduce a difficult situation since they are essentially
"lossy" when parsed. Consider this in cmd.exe::
> echo "foo^bar"
"foo^bar"
> echo foo^^bar
foo^bar
The two commands produce different results, but are both parsed by the
shell as `foo^bar`, and there's essentially no sensible way to tell
what was actually passed in. This implementation assumes the quoted
variation (the first) since it is easier to implement, and arguably
the more common case.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
"""
return " ".join(itertools.chain(
[_quote_if_contains(self.command, r'[\s()]')],
(_quote_if_contains(arg, r'\s') for arg in self.args),
[_quote_if_contains(self.command, r'[\s^()]')],
(_quote_if_contains(arg, r'[\s^]') for arg in self.args),
))
+9
View File
@@ -64,3 +64,12 @@ def test_cmdify_quote_if_paren_in_command():
'-c',
"print(123)",
]), script
@pytest.mark.run
@pytest.mark.script
def test_cmdify_quote_if_carets():
"""Ensure arguments are quoted if they contain carets.
"""
script = Script('foo^bar', ['baz^rex'])
assert script.cmdify() == '"foo^bar" "baz^rex"', script