Debian Codegraph @

src/briefcase/integrations/virtual_environment.py

raw
1 import os
2 import shutil
3 import subprocess as stdlib_subprocess
4 import sys
5 from pathlib import Path
6
7 from briefcase.exceptions import BriefcaseCommandError
8 from briefcase.integrations import subprocess
9 from briefcase.integrations.base import Tool, ToolCache
10 from briefcase.integrations.subprocess import SubprocessArgsT
11
12
13 class VenvContext:
14 def __init__(self, tools: ToolCache, venv_path: Path):
15 self.tools = tools
16 self.venv_path = venv_path
17 self.created = False
18
19 @property
20 def bin_dir(self) -> Path:
21 """Return the path to the virtual environment's binary directory.
22
23 :returns: The ``/bin`` (``\\Scripts`` on Windows) directory of the venv.
24 """
25
26 return self.venv_path / ("Scripts" if os.name == "nt" else "bin")
27
28 @property
29 def executable(self) -> str:
30 """Path to the Python executable in the virtual environment.
31
32 :returns: Absolute filesystem path to the venv's Python executable.
33 """
34 python = self.bin_dir / ("python.exe" if os.name == "nt" else "python")
35 return python
36
37 def exists(self) -> bool:
38 """Check whether the virtual environment exists.
39
40 :returns: True if venv exists and contains a pyvenv.cfg file.
41 """
42 return self.venv_path.exists() and (self.venv_path / "pyvenv.cfg").exists()
43
44 def create(self) -> None:
45 """Create the virtual environment.
46
47 :raises: BriefcaseCommandError if venv creation fails.
48 """
49 try:
50 self.venv_path.parent.mkdir(parents=True, exist_ok=True)
51 self.tools.subprocess.run(
52 [sys.executable, "-m", "venv", self.venv_path],
53 check=True,
54 )
55 self.update_core_tools()
56 self.created = True
57 except stdlib_subprocess.CalledProcessError as e:
58 raise BriefcaseCommandError(
59 f"Failed to create virtual environment at {self.venv_path}"
60 ) from e
61
62 def clean(self) -> None:
63 """Remove the virtual environment."""
64 if self.exists():
65 shutil.rmtree(self.venv_path)
66
67 def recreate(self) -> None:
68 """Remove and re-create the virtual environment."""
69 self.clean()
70 self.create()
71
72 def update_core_tools(self) -> None:
73 """Upgrade core Python packaging tooling in the venv."""
74 try:
75 self.run([self.executable, "-m", "pip", "install", "-U", "pip"], check=True)
76 except Exception as e:
77 raise BriefcaseCommandError(
78 f"Failed to update core tooling for {self.venv_path}"
79 ) from e
80
81 def _rewrite_head(self, args: SubprocessArgsT) -> SubprocessArgsT:
82 """Rewrite the first argument to ensure it points to the venv's Python
83 executable.
84
85 :param args: Original subprocess arguments.
86 :returns: Updated subprocess arguments.
87 """
88 if not args:
89 return args
90 head = os.fspath(args[0])
91 if os.path.normcase(head) == os.path.normcase(sys.executable):
92 return [self.executable, *args[1:]]
93
94 return list(args)
95
96 def full_env(self, overrides: dict[str, str | None] | None) -> dict[str, str]:
97 """Generate the full environment for the venv.
98
99 :param overrides: Environment variables to override or unset. Can be ``None`` if
100 there are no explicit environment changes. Use ``None`` as a values to unset
101 environment variables
102 :returns: environment mapping for the venv with overrides applied.
103 """
104
105 if overrides:
106 env = overrides.copy()
107 else:
108 env = {}
109
110 old_path = env.get("PATH") or os.environ.get("PATH", "")
111 env["PATH"] = os.fspath(self.bin_dir) + (
112 os.pathsep + old_path if old_path else ""
113 )
114 env["VIRTUAL_ENV"] = os.fspath(self.venv_path)
115
116 # Remove PYTHONHOME to avoid conflicts with the venv.
117 env.pop("PYTHONHOME", None)
118
119 return env
120
121 def run(self, args: SubprocessArgsT, **kwargs) -> subprocess.CompletedProcess:
122 """Run a command in the virtual environment.
123
124 :param args: Command and arguments to run.
125 :param kwargs: Additional keyword arguments to pass to subprocess.run.
126 :returns: CompletedProcess from the subprocess execution.
127 """
128 args = self._rewrite_head(list(args))
129 user_env = kwargs.pop("env", None)
130 kwargs["env"] = self.full_env(user_env)
131 return self.tools.subprocess.run(args, **kwargs)
132
133 def Popen(self, args: SubprocessArgsT, **kwargs) -> stdlib_subprocess.Popen:
134 """Run a command in the virtual environment using Popen.
135
136 :param args: Command and arguments to run.
137 :param kwargs: Additional keyword arguments to pass to subprocess.Popen.
138 :returns: A Popen instance for the subprocess execution.
139 """
140 args = self._rewrite_head(list(args))
141 user_env = kwargs.pop("env", None)
142 kwargs["env"] = self.full_env(user_env)
143 return self.tools.subprocess.Popen(args, **kwargs)
144
145 def check_output(self, args: SubprocessArgsT, **kwargs) -> str:
146 """Run a command in the virtual environment and return its output.
147
148 :param args: Command and arguments to run.
149 :param kwargs: Additional keyword arguments to pass to subprocess.check_output.
150 :returns: String output from the subprocess execution.
151 """
152 args = self._rewrite_head(list(args))
153 user_env = kwargs.pop("env", None)
154 kwargs["env"] = self.full_env(user_env)
155 return self.tools.subprocess.check_output(args, **kwargs)
156
157
158 class VenvEnvironment:
159 """Context manager for creating and managing a venv."""
160
161 def __init__(
162 self,
163 tools: ToolCache,
164 *,
165 path: Path,
166 recreate: bool = False,
167 ):
168 self.tools = tools
169 self.path = path
170 self.recreate = recreate
171
172 self.venv_context = VenvContext(tools=self.tools, venv_path=self.path)
173
174 def __enter__(self):
175 if self.recreate:
176 with self.tools.console.wait_bar(
177 f"Recreating virtual environment ({self.path.name})..."
178 ):
179 self.venv_context.recreate()
180 elif not self.venv_context.exists():
181 with self.tools.console.wait_bar(
182 f"Creating virtual environment ({self.path.name})..."
183 ):
184 self.venv_context.create()
185
186 return self.venv_context
187
188 def __exit__(self, exc_type, exc_val, exc_tb):
189 return False
190
191
192 class NoOpVenvContext:
193 """Context for wrapping subprocess for no-op venv.
194
195 Provides the same interface as VenvContext but pass calls through to the native
196 subprocess.
197 """
198
199 def __init__(self, tools, venv_path: Path):
200 self.tools = tools
201 self.venv_path = venv_path
202
203 self.created = False
204 self.marker_path = venv_path / "venv_path"
205
206 def exists(self) -> bool:
207 """A no-op env always exists."""
208 return True
209
210 def create(self) -> bool:
211 """Creates the no-op environment.
212
213 This isn't a strict "create", as the no-op environment will always exist.
214 However, the "creation" process will identify if the currently active
215 environment has been used previously, and set the `created` flag if the
216 environment hasn't been used before. This can then be used to identify "first
217 use" behavior, such as installing requirements.
218 """
219 if not self.marker_path.exists():
220 self.marker_path.parent.mkdir(parents=True, exist_ok=True)
221 self.marker_path.write_text(sys.executable, encoding="utf-8")
222 self.created = True
223 try:
224 existing_executable = self.marker_path.read_text(encoding="utf-8").strip()
225 if existing_executable != sys.executable:
226 self.marker_path.write_text(sys.executable, encoding="utf-8")
227 self.created = True
228 except (OSError, UnicodeDecodeError):
229 self.marker_path.write_text(sys.executable, encoding="utf-8")
230 self.created = True
231
232 def clean(self) -> None:
233 """Remove the virtual environment marker."""
234 if self.marker_path.exists():
235 self.marker_path.unlink()
236
237 def recreate(self) -> None:
238 """Recreate the no-op environment.
239
240 Since the no-op environment always exists, this essentially amounts to ensuring
241 that the created flag is set.
242 """
243 self.clean()
244 self.create()
245
246 def run(self, args: SubprocessArgsT, **kwargs) -> subprocess.CompletedProcess:
247 """Run command through native subprocess."""
248 return self.tools.subprocess.run(args, **kwargs)
249
250 def Popen(self, args: SubprocessArgsT, **kwargs) -> stdlib_subprocess.Popen:
251 """Run command through native subprocess.Popen."""
252 return self.tools.subprocess.Popen(args, **kwargs)
253
254 def check_output(self, args: SubprocessArgsT, **kwargs) -> str:
255 """Run command through native subprocess.check_output."""
256 return self.tools.subprocess.check_output(args, **kwargs)
257
258
259 class NoOpEnvironment:
260 """A no-op environment that returns a native runner."""
261
262 def __init__(self, tools: ToolCache, *, path: Path, recreate: bool):
263 self.tools = tools
264 self.path = path
265 self.recreate = recreate
266
267 self.noop_context = NoOpVenvContext(tools=tools, venv_path=path)
268
269 def __enter__(self):
270 if self.recreate:
271 self.noop_context.recreate()
272 else:
273 self.noop_context.create()
274
275 return self.noop_context
276
277 def __exit__(self, exc_type, exc_val, exc_tb):
278 return False
279
280
281 class VirtualEnvironment(Tool):
282 name = "virtual_environment"
283 full_name = "Virtual Environment management"
284
285 @classmethod
286 def verify_install(cls, tools: ToolCache, **kwargs) -> "VirtualEnvironment":
287 """Make virtual environment available in tool cache."""
288 # short circuit since already verified and available
289 if hasattr(tools, "virtual_environment"):
290 return tools.virtual_environment
291
292 tools.virtual_environment = VirtualEnvironment(tools=tools)
293 return tools.virtual_environment
294
295 def create(
296 self,
297 venv_path: Path,
298 *,
299 isolated: bool = True,
300 recreate: bool = False,
301 ) -> VenvEnvironment | NoOpEnvironment:
302 """Return a environment context for the requested isolation settings. Creates
303 either a virtual environment context or a no-op context.
304
305 :param tools: The tools instance
306 :param venv_path: Path for the virtual environment
307 :param isolated: If False, return NoOpEnvironment. Default True.
308 :param recreate: Whether to recreate existing venv. Default False.
309 :returns: A context manager for an environment where code can be executed.
310 """
311 if not isolated:
312 return NoOpEnvironment(
313 tools=self.tools,
314 path=venv_path,
315 recreate=recreate,
316 )
317 else:
318 return VenvEnvironment(
319 tools=self.tools,
320 path=venv_path,
321 recreate=recreate,
322 )