|
| 1 | +"""Maintain and use a protected copy of pip for use during development. |
| 2 | +
|
| 3 | +The protected copy of pip can be used to manipulate the environment while keeping a |
| 4 | +potentially-non-functional installation of in-development pip in the development virtual |
| 5 | +environment. |
| 6 | +
|
| 7 | +This allows for setting up the test environments and exercising the in-development code, |
| 8 | +even when it is not functional-enough to install the packages for setting up the |
| 9 | +environment that it is being used it. |
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | +import shutil |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +from glob import glob |
| 17 | +from typing import List |
| 18 | + |
| 19 | +VIRTUAL_ENV = os.environ["VIRTUAL_ENV"] |
| 20 | +PROTECTED_PIP_DIR = os.path.join(VIRTUAL_ENV, "pip") |
| 21 | + |
| 22 | + |
| 23 | +def _setup_protected_pip() -> None: |
| 24 | + # This setup happens before any development version of pip is installed in this |
| 25 | + # environment. So, at this point, the existing pip installation should be from a |
| 26 | + # stable release and can be safely used to create the protected copy. |
| 27 | + subprocess.check_call( |
| 28 | + [ |
| 29 | + sys.executable, |
| 30 | + "-m", |
| 31 | + "pip", |
| 32 | + "--disable-pip-version-check", |
| 33 | + "install", |
| 34 | + "-t", |
| 35 | + PROTECTED_PIP_DIR, |
| 36 | + "pip", |
| 37 | + ] |
| 38 | + ) |
| 39 | + # Make it impossible for pip (and other Python tooling) to discover this protected |
| 40 | + # installation of pip using the metadata, by deleting the metadata. |
| 41 | + shutil.rmtree(glob(os.path.join(PROTECTED_PIP_DIR, "pip-*.dist-info"))[0]) |
| 42 | + |
| 43 | + |
| 44 | +def main(args: List[str]) -> None: |
| 45 | + # If we don't have a protected pip, let's set it up. |
| 46 | + if not os.path.exists(PROTECTED_PIP_DIR): |
| 47 | + _setup_protected_pip() |
| 48 | + |
| 49 | + # Run Python, with the protected pip copy on PYTHONPATH. |
| 50 | + old_PYTHONPATH_entries = os.environ.get("PYTHONPATH", "").split(os.pathsep) |
| 51 | + new_PYTHONPATH = os.pathsep.join([PROTECTED_PIP_DIR] + old_PYTHONPATH_entries) |
| 52 | + |
| 53 | + subprocess.check_call( |
| 54 | + [sys.executable, "-m", "pip"] + args, |
| 55 | + env={"PYTHONPATH": new_PYTHONPATH}, |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + main(sys.argv[1:]) |
0 commit comments