Skip to content

Commit 00e5adf

Browse files
committed
Rework the pip runner to use PathFinder
This makes it possible to only "replace" `pip` and have the submodules get correctly located by the regular importlib machinery. This also asserts that it was able to locate the module, ensuring that failure to locate the module results in an exception.
1 parent 5f2a858 commit 00e5adf

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

src/pip/__pip-runner__.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,14 @@
44
an import statement.
55
"""
66

7-
import importlib.util
87
import runpy
98
import sys
109
import types
11-
from importlib.machinery import ModuleSpec
12-
from os.path import dirname, join
10+
from importlib.machinery import ModuleSpec, PathFinder
11+
from os.path import dirname
1312
from typing import Optional, Sequence, Union
1413

15-
PIP_SOURCES_ROOT = dirname(dirname(dirname(__file__)))
14+
PIP_SOURCES_ROOT = dirname(dirname(__file__))
1615

1716

1817
class PipImportRedirectingFinder:
@@ -23,15 +22,15 @@ def find_spec(
2322
path: Optional[Sequence[Union[bytes, str]]] = None,
2423
target: Optional[types.ModuleType] = None,
2524
) -> Optional[ModuleSpec]:
26-
if not fullname.startswith("pip."):
25+
if fullname != "pip":
2726
return None
2827

29-
# Import pip from the source directory of this file
30-
location = join(PIP_SOURCES_ROOT, *fullname.split("."))
31-
return importlib.util.spec_from_file_location(fullname, location)
28+
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
29+
assert spec, (PIP_SOURCES_ROOT, fullname)
30+
return spec
3231

3332

3433
sys.meta_path.insert(0, PipImportRedirectingFinder())
3534

3635
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
37-
runpy.run_module("pip", run_name="__main__")
36+
runpy.run_module("pip", run_name="__main__", alter_sys=True)

0 commit comments

Comments
 (0)