77import sys
88from pathlib import Path
99from subprocess import PIPE , CalledProcessError , Popen
10+ from tempfile import TemporaryDirectory
1011from typing import TYPE_CHECKING , Final
1112
1213from packaging .specifiers import InvalidSpecifier , Specifier
14+ from packaging .utils import canonicalize_name
1315
1416from .bundle import from_bundle
1517from .periodic_update import UnverifiedWheelError , add_wheel_to_update_log , verify_wheel_digest
@@ -106,30 +108,18 @@ def download_wheel( # ruff:ignore[too-many-arguments]
106108 to_folder : Path ,
107109 env : dict [str , str ],
108110) -> Wheel :
109- """Invoke ``pip download`` in a subprocess to fetch a seed wheel.
110-
111- :param distribution: PEP 503 normalized project name; rejected if it contains anything other than
112- ``[A-Za-z0-9._-]``.
113- :param version_spec: optional version specifier of the form ``==<ver>`` or ``<<ver>`` as emitted by
114- :func:`Version.as_version_spec`, or ``None``/empty for the latest compatible release.
115- :param for_py_version: major.minor Python version to pass through to ``pip --python-version``.
116- :param search_dirs: additional directories to treat as a local wheel index when bootstrapping pip.
117- :param app_data: application data store used to locate the embedded pip wheel.
118- :param to_folder: directory the downloaded wheel is written into.
119- :param env: environment mapping passed through to the subprocess.
120-
121- :returns: the downloaded :class:`Wheel`.
122-
123- :raises ValueError: if ``distribution`` or ``version_spec`` fail the strict allow-list check.
124- :raises CalledProcessError: if ``pip download`` exits with a non-zero status.
125- :raises RuntimeError: if no downloaded wheel can be identified from ``pip``'s output or the search directory, or if
126- the caller has not configured a custom index and PyPI's sha256 for the downloaded filename cannot be obtained or
127- does not match, see :func:`virtualenv.seed.wheels.periodic_update.verify_wheel_digest`.
111+ """Download one wheel into a private staging directory and move it into ``to_folder`` once it checks out.
112+
113+ :raises ValueError: for an invalid distribution name or version specifier.
114+ :raises CalledProcessError: when ``pip download`` fails.
115+ :raises UnverifiedWheelError: when PyPI cannot supply the digest to verify against.
116+ :raises RuntimeError: when the staged file is not the requested wheel, its digest differs from PyPI's, or it does
117+ not support ``for_py_version``; nothing reaches ``to_folder`` in these cases.
128118
129119 """
130120 _check_distribution (distribution )
131121 _check_version_spec (version_spec )
132- to_download = f"{ distribution } { version_spec or '' } "
122+ to_download : Final = f"{ distribution } { version_spec or '' } "
133123 if to_download .lower ().endswith ((
134124 ".zip" ,
135125 ".whl" ,
@@ -147,52 +137,57 @@ def download_wheel( # ruff:ignore[too-many-arguments]
147137 msg = f"refusing to download wheel with archive-like requirement: { to_download !r} "
148138 raise ValueError (msg )
149139 LOGGER .debug ("download wheel %s %s to %s" , to_download , for_py_version , to_folder )
150- cmd = [
151- sys .executable ,
152- "-c" ,
153- PIP_RUN ,
154- "download" ,
155- "--progress-bar" ,
156- "off" ,
157- "--disable-pip-version-check" ,
158- "--only-binary=:all:" ,
159- "--no-deps" ,
160- "--python-version" ,
161- for_py_version ,
162- "-d" ,
163- str (to_folder ),
164- to_download ,
165- ]
166- verify_against_pypi = _uses_default_index (env )
167- # pip has no interface in python - must be a new sub-process
140+ verify_against_pypi : Final = _uses_default_index (env )
168141 env = pip_wheel_env_run (search_dirs , app_data , env )
169- process = Popen (cmd , env = env , stdout = PIPE , stderr = PIPE , universal_newlines = True , encoding = "utf-8" )
170- out , err = process .communicate ()
171- if process .returncode != 0 :
172- kwargs = {"output" : out , "stderr" : err }
173- raise CalledProcessError (process .returncode , cmd , ** kwargs )
174- result = _find_downloaded_wheel (distribution , version_spec , for_py_version , to_folder , out )
175- if result is None :
176- msg = f"could not find downloaded wheel for { to_download } "
142+ to_folder .mkdir (parents = True , exist_ok = True )
143+ with TemporaryDirectory (dir = to_folder , prefix = "download-" ) as staging :
144+ cmd : Final = [
145+ sys .executable ,
146+ "-c" ,
147+ PIP_RUN ,
148+ "download" ,
149+ "--progress-bar" ,
150+ "off" ,
151+ "--disable-pip-version-check" ,
152+ "--only-binary=:all:" ,
153+ "--no-deps" ,
154+ "--python-version" ,
155+ for_py_version ,
156+ "-d" ,
157+ staging ,
158+ to_download ,
159+ ]
160+ process : Final = Popen (cmd , env = env , stdout = PIPE , stderr = PIPE , universal_newlines = True , encoding = "utf-8" )
161+ out , err = process .communicate ()
162+ if process .returncode != 0 :
163+ raise CalledProcessError (process .returncode , cmd , output = out , stderr = err )
164+ result : Final = _downloaded_wheel (Path (staging ), distribution , version_spec )
165+ if verify_against_pypi :
166+ verify_wheel_digest (result )
167+ if not result .support_py (for_py_version ):
168+ msg : Final = f"downloaded wheel { result .name } does not support Python { for_py_version } "
169+ raise RuntimeError (msg )
170+ destination : Final = to_folder / result .name
171+ result .path .replace (destination )
172+ return Wheel (destination )
173+
174+
175+ def _downloaded_wheel (folder : Path , distribution : str , version_spec : str | None ) -> Wheel :
176+ files : Final = list (folder .iterdir ())
177+ if len (files ) != 1 or files [0 ].is_symlink () or not files [0 ].is_file ():
178+ msg : Final = f"could not find downloaded wheel for { distribution } : expected one archive"
179+ raise RuntimeError (msg )
180+ result : Final = Wheel .from_path (files [0 ])
181+ if (
182+ result is None
183+ or canonicalize_name (result .distribution ) != canonicalize_name (distribution )
184+ or (version_spec and not Specifier (version_spec ).contains (result .version ))
185+ ):
186+ msg : Final = f"unexpected downloaded wheel { files [0 ].name } for { distribution } { version_spec or '' } "
177187 raise RuntimeError (msg )
178- LOGGER .debug ("downloaded wheel %s" , result .name )
179- if verify_against_pypi :
180- verify_wheel_digest (result )
181188 return result
182189
183190
184- def _find_downloaded_wheel (
185- distribution : str , version_spec : str | None , for_py_version : str , to_folder : Path , out : str
186- ) -> Wheel | None :
187- for line in out .splitlines ():
188- stripped_line = line .lstrip ()
189- for marker in ("Saved " , "File was already downloaded " ):
190- if stripped_line .startswith (marker ):
191- return Wheel (Path (stripped_line [len (marker ) :]).absolute ())
192- # if for some reason the output does not match fallback to the latest version with that spec
193- return find_compatible_in_house (distribution , version_spec , for_py_version , to_folder )
194-
195-
196191def find_compatible_in_house (
197192 distribution : str , version_spec : str | None , for_py_version : str , in_folder : Path
198193) -> Wheel | None :
0 commit comments