Monkey-patch .pem path into standalone pip instead
@@ -41,6 +41,28 @@ class _Prefix:
self.lib_dirs = get_prefixed_libs(path)
+_CERTIFI_WHERE_PATCH = """
+from pip._vendor import certifi
+certifi.where = lambda: {pem!r}
+"""
+
+
+def _format_main_py(source: pathlib.Path) -> bytes:
+ """Create a patched pip/__main__.py for the standalone pip.
+
+ The default ``certifi.where()`` relies on the certificate bundle being a
+ real physical file on-disk, so we monkey-patch it to return the one used
+ by this process instead.
+
+ Passing ``--cert`` to the standalone pip does not work, since ``requests``
+ calls ``where()`` unconditionally on import.
+ """
+ with source.open("rb") as f:
+ content = f.read()
+ patch = _CERTIFI_WHERE_PATCH.format(pem=where()).encode("utf-8")
+ return patch + content
+
+
@contextlib.contextmanager
def _create_standalone_pip() -> Iterator[str]:
"""Create a zip file containing specified pip installation."""
@@ -49,8 +71,11 @@ def _create_standalone_pip() -> Iterator[str]:
pip_zip = os.path.join(tmp_dir.path, "pip.zip")
with zipfile.ZipFile(pip_zip, "w") as zf:
for child in source.rglob("*"):
- arcname = child.relative_to(source.parent)
- zf.write(child, arcname.as_posix())
+ arcname = child.relative_to(source.parent).as_posix()
+ if arcname == "pip/__main__.py":
+ zf.writestr(arcname, _format_main_py(child))
+ else:
+ zf.write(child, arcname)
yield os.path.join(pip_zip, "pip")
@@ -197,7 +222,7 @@ class BuildEnvironment:
args = [
sys.executable, standalone_pip, 'install',
'--ignore-installed', '--no-user', '--prefix', prefix.path,
- '--no-warn-script-location', '--cert', where(),
+ '--no-warn-script-location',
] # type: List[str]
if logger.getEffectiveLevel() <= logging.DEBUG:
args.append('-v')
