Debian Codegraph @

testing/web-platform/tests/tools/wpt/virtualenv.py

raw
1 # mypy: allow-untyped-defs
2
3 import logging
4 import os
5 import shutil
6 import site
7 import sys
8 import sysconfig
9 from shutil import which
10
11 # The `pkg_resources` module is provided by `setuptools`, which is itself a
12 # dependency of `virtualenv`. Tolerate its absence so that this module may be
13 # evaluated when that module is not available. Because users may not recognize
14 # the `pkg_resources` module by name, raise a more descriptive error if it is
15 # referenced during execution.
16 try:
17 import pkg_resources as _pkg_resources
18 get_pkg_resources = lambda: _pkg_resources
19 except ImportError:
20 def get_pkg_resources():
21 raise ValueError("The Python module `virtualenv` is not installed.")
22
23 from tools.wpt.utils import call
24
25 logger = logging.getLogger(__name__)
26
27 class Virtualenv:
28 def __init__(self, path, skip_virtualenv_setup):
29 self.path = path
30 self.skip_virtualenv_setup = skip_virtualenv_setup
31 if not skip_virtualenv_setup:
32 self.virtualenv = [sys.executable, "-m", "venv"]
33 self._working_set = None
34
35 @property
36 def exists(self):
37 # We need to check also for lib_path because different python versions
38 # create different library paths.
39 return os.path.isdir(self.path) and os.path.isdir(self.lib_path)
40
41 @property
42 def broken_link(self):
43 python_link = os.path.join(self.path, ".Python")
44 return os.path.lexists(python_link) and not os.path.exists(python_link)
45
46 def create(self):
47 if os.path.exists(self.path):
48 shutil.rmtree(self.path, ignore_errors=True)
49 self._working_set = None
50 call(*self.virtualenv, self.path)
51
52 def get_paths(self):
53 """Wrapper around sysconfig.get_paths(), returning the appropriate paths for the env."""
54 if "venv" in sysconfig.get_scheme_names():
55 # This should always be used on Python 3.11 and above.
56 scheme = "venv"
57 elif os.name == "nt":
58 # This matches nt_venv, unless sysconfig has been modified.
59 scheme = "nt"
60 elif os.name == "posix":
61 # This matches posix_venv, unless sysconfig has been modified.
62 scheme = "posix_prefix"
63 elif sys.version_info >= (3, 10):
64 # Using the default scheme is somewhat fragile, as various Python
65 # distributors (e.g., what Debian and Fedora package, and what Xcode
66 # includes) change the default scheme away from the upstream
67 # defaults, but it's about as good as we can do.
68 scheme = sysconfig.get_default_scheme()
69 else:
70 # This is explicitly documented as having previously existed in the 3.10
71 # docs, and has existed since CPython 2.7 and 3.1 (but not 3.0).
72 scheme = sysconfig._get_default_scheme()
73
74 vars = {
75 "base": self.path,
76 "platbase": self.path,
77 "installed_base": self.path,
78 "installed_platbase": self.path,
79 }
80
81 return sysconfig.get_paths(scheme, vars)
82
83 @property
84 def bin_path(self):
85 return self.get_paths()["scripts"]
86
87 @property
88 def pip_path(self):
89 path = which("pip3", path=self.bin_path)
90 if path is None:
91 path = which("pip", path=self.bin_path)
92 if path is None:
93 raise ValueError("pip3 or pip not found")
94 return path
95
96 @property
97 def lib_path(self):
98 # We always return platlib here, even if it differs to purelib, because we can
99 # always install pure-Python code into the platlib safely too. It's also very
100 # unlikely to differ for a venv.
101 return self.get_paths()["platlib"]
102
103 @property
104 def working_set(self):
105 if not self.exists:
106 raise ValueError("trying to read working_set when venv doesn't exist")
107
108 if self._working_set is None:
109 self._working_set = get_pkg_resources().WorkingSet((self.lib_path,))
110
111 return self._working_set
112
113 def activate(self):
114 if sys.platform == "darwin":
115 # The default Python on macOS sets a __PYVENV_LAUNCHER__ environment
116 # variable which affects invocation of python (e.g. via pip) in a
117 # virtualenv. Unset it if present to avoid this. More background:
118 # https://github.com/web-platform-tests/wpt/issues/27377
119 # https://github.com/python/cpython/pull/9516
120 os.environ.pop("__PYVENV_LAUNCHER__", None)
121
122 paths = self.get_paths()
123
124 # Setup the path and site packages as if we'd launched with the virtualenv active
125 bin_dir = paths["scripts"]
126 os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep))
127
128 # While not required (`./venv/bin/python3` won't set it, but
129 # `source ./venv/bin/activate && python3` will), we have historically set this.
130 os.environ["VIRTUAL_ENV"] = self.path
131
132 prev_length = len(sys.path)
133
134 # Add the venv library paths as sitedirs.
135 for key in ["purelib", "platlib"]:
136 site.addsitedir(paths[key])
137
138 # Rearrange the path
139 sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
140
141 # Change prefixes, similar to what initconfig/site does for venvs.
142 sys.exec_prefix = self.path
143 sys.prefix = self.path
144
145 def start(self):
146 if not self.exists or self.broken_link:
147 self.create()
148 self.activate()
149
150 def install(self, *requirements):
151 try:
152 self.working_set.require(*requirements)
153 except Exception:
154 pass
155 else:
156 return
157
158 # `--prefer-binary` guards against race conditions when installation
159 # occurs while packages are in the process of being published.
160 call(self.pip_path, "install", "--prefer-binary", *requirements)
161
162 def install_requirements(self, *requirements_paths):
163 install = []
164 # Check which requirements are already satisfied, to skip calling pip
165 # at all in the case that we've already installed everything, and to
166 # minimise the installs in other cases.
167 for requirements_path in requirements_paths:
168 with open(requirements_path) as f:
169 try:
170 self.working_set.require(f.read())
171 except Exception:
172 install.append(requirements_path)
173
174 if install:
175 # `--prefer-binary` guards against race conditions when installation
176 # occurs while packages are in the process of being published.
177 cmd = [self.pip_path, "install", "--prefer-binary"]
178 for path in install:
179 cmd.extend(["-r", path])
180 call(*cmd)