11from __future__ import annotations
22
3+ import logging
34import os
4- from typing import TYPE_CHECKING
5+ from typing import TYPE_CHECKING , Final
56
67from virtualenv .activation .via_template import ViaTemplateActivator
8+ from virtualenv .util .text import collapse_line_boundaries
79
810if TYPE_CHECKING :
911 from collections .abc import Iterator
12+ from pathlib import Path
1013
1114 from python_discovery import PythonInfo
1215
1316 from virtualenv .create .creator import Creator
1417
18+ LOGGER = logging .getLogger (__name__ )
19+
20+ # cmd.exe's own command-line parser looks for these regardless of surrounding quotes: confirmed on a
21+ # real Windows runner that `@set "VAR=x & cmd"` still runs `cmd` as a second statement even though the
22+ # whole VAR=value expression is quoted. `(` and `)` are not in this set - confirmed on the same runner
23+ # that `@set "VAR=C:\Program Files (x86)\..."` round-trips unchanged, since parentheses are only special
24+ # to cmd.exe as block delimiters in control-flow syntax (if/for), not as bare characters in a value. `!`
25+ # is only live when the caller already has delayed expansion enabled (`setlocal enabledelayedexpansion`,
26+ # `cmd /V:ON`) - not cmd.exe's default, but confirmed on a real runner that a prompt like `foo!SECRET!`
27+ # then substitutes the actual value of an existing SECRET variable into the prompt, so it is neutered
28+ # unconditionally rather than only when that mode happens to be on.
29+ _CMD_OPERATORS : Final [tuple [str , ...]] = ("&" , "|" , "<" , ">" , "^" , "!" , '"' )
30+
31+ # Of _CMD_OPERATORS, only `&` can actually occur in a real Windows path: `|`, `<`, `>` and `"` are
32+ # already illegal in Windows filenames, and a literal `^` is silently dropped by cmd.exe itself even
33+ # with no help from quote(), confirmed on a real Windows runner - never exploitable, just a value that
34+ # reads one character short. `&` is different: quote() can neuter it in free text like the prompt, but
35+ # doing that to a path would silently point activate.bat at a directory that does not exist. There is no
36+ # way to represent it here and no way to fake the path, so refuse instead.
37+ _PATH_UNSAFE_CHARS : Final [tuple [str , ...]] = ("&" ,)
38+
39+ _PATH_REPLACEMENT_NAMES : Final [dict [str , str ]] = {
40+ "__VIRTUAL_ENV__" : "the destination directory" ,
41+ "__TCL_LIBRARY__" : "the interpreter's Tcl library path" ,
42+ "__TK_LIBRARY__" : "the interpreter's Tk library path" ,
43+ }
44+
1545
1646class BatchActivator (ViaTemplateActivator ):
1747 @classmethod
@@ -23,16 +53,47 @@ def templates(self) -> Iterator[str]:
2353 yield "deactivate.bat"
2454 yield "pydoc.bat"
2555
56+ def generate (self , creator : Creator ) -> list [Path ]:
57+ values = super ().replacements (creator , creator .bin_dir )
58+ problems = [reason for key in _PATH_REPLACEMENT_NAMES if (reason := _unsafe_path_reason (key , values [key ]))]
59+ if problems :
60+ for problem in problems :
61+ LOGGER .warning ("skipping batch activation scripts: %s" , problem )
62+ return []
63+ return super ().generate (creator )
64+
2665 @staticmethod
2766 def quote (string : str ) -> str :
28- return string
67+ """Make a value safe to sit inside ``@set "VAR=value"``.
68+
69+ Batch has no escape for a double quote in this context either: it always closes the quoted string, and whatever
70+ follows on the line runs as live cmd.exe syntax. A raw line boundary is worse - batch is line-oriented
71+ regardless of quote state, so it starts a brand-new statement instead of staying inside the value. None of these
72+ can be represented literally here, so replace them with a space. ``%`` still triggers variable expansion inside
73+ the quotes, but doubling it to ``%%`` is a real, in-file escape that keeps the literal character.
74+
75+ """
76+ string = string .replace ("%" , "%%" )
77+ for operator in _CMD_OPERATORS :
78+ string = string .replace (operator , " " )
79+ return collapse_line_boundaries (string )
2980
3081 def instantiate_template (self , replacements : dict [str , str ], template : str , creator : Creator ) -> str :
3182 # ensure the text has all newlines as \r\n - required by batch
3283 base = super ().instantiate_template (replacements , template , creator )
3384 return base .replace (os .linesep , "\n " ).replace ("\n " , os .linesep )
3485
3586
87+ def _unsafe_path_reason (key : str , value : str ) -> str | None :
88+ found = sorted ({char for char in value if char in _PATH_UNSAFE_CHARS })
89+ if not found :
90+ return None
91+ return (
92+ f"{ _PATH_REPLACEMENT_NAMES [key ]} ({ value !r} ) contains { '' .join (found )!r} , and cmd.exe has no way "
93+ f'to keep that literal inside the @set "VAR=value" lines activate.bat relies on'
94+ )
95+
96+
3697__all__ = [
3798 "BatchActivator" ,
3899]
0 commit comments