Debian Codegraph @

src/briefcase/commands/dev.py

raw
1 from __future__ import annotations
2
3 import importlib.machinery
4 import os
5 import subprocess
6 import sys
7 from collections.abc import Mapping
8 from pathlib import Path
9
10 from briefcase.commands.create import _is_local_path
11 from briefcase.commands.run import RunAppMixin
12 from briefcase.config import AppConfig
13 from briefcase.exceptions import BriefcaseCommandError, RequirementsInstallError
14 from briefcase.integrations.virtual_environment import VenvContext
15
16 from .base import BaseCommand
17 from .create import write_dist_info
18
19
20 class DevCommand(RunAppMixin, BaseCommand):
21 cmd_line = "briefcase dev"
22 command = "dev"
23 output_format = ""
24 description = "Run a Briefcase project in the dev environment."
25
26 # On macOS CoreFoundation/NSApplication will do its own independent parsing of
27 # argc/argv. This means that whatever we pass to the Python interpreter on start-up
28 # will also be visible to NSApplication which will interpret things like `-u` (used
29 # to make I/O unbuffered in CPython) as `-u [URL]` (a request to open a document by
30 # URL). This is, rather patently, Not Good.
31 # To avoid this causing unwanted hilarity, we use environment variables to configure
32 # the Python interpreter rather than command-line options.
33 DEV_ENVIRONMENT: Mapping[str, str] = {
34 # Equivalent of passing "-u"
35 "PYTHONUNBUFFERED": "1",
36 # Equivalent of passing "-X dev"
37 "PYTHONDEVMODE": "1",
38 # Equivalent of passing "-X utf8"
39 "PYTHONUTF8": "1",
40 }
41
42 @property
43 def platform(self):
44 """The dev command always reports as the local platform."""
45 return {
46 "darwin": "macOS",
47 "linux": "linux",
48 "win32": "windows",
49 }[sys.platform]
50
51 def bundle_path(self, app):
52 """A placeholder; Dev command doesn't have a bundle path."""
53 raise NotImplementedError()
54
55 def binary_path(self, app):
56 """A placeholder; Dev command doesn't have a binary path."""
57 raise NotImplementedError()
58
59 def add_options(self, parser):
60 parser.add_argument("-a", "--app", dest="appname", help="The app to run")
61 parser.add_argument(
62 "-r",
63 "--update-requirements",
64 action="store_true",
65 help="Update requirements for the app",
66 )
67 parser.add_argument(
68 "--no-isolation",
69 dest="isolated",
70 action="store_false",
71 help=(
72 "Run without creating an isolated environment "
73 "(not recommended for web)."
74 ),
75 )
76 parser.add_argument(
77 "--no-run",
78 dest="run_app",
79 action="store_false",
80 default=True,
81 help="Do not run the app, just install requirements",
82 )
83 parser.add_argument(
84 "--test",
85 dest="test_mode",
86 action="store_true",
87 help="Run the app in test mode",
88 )
89
90 def install_dev_requirements(self, app: AppConfig, venv: VenvContext, **options):
91 """Install the requirements for the app dev.
92
93 This will always include test requirements, if specified. Local dependencies are
94 installed editable.
95
96 :param app: The config object for the app
97 :param venv: The context object used to run commands inside the virtual
98 environment.
99 """
100
101 requires = app.requires or []
102 if app.test_requires:
103 requires.extend(app.test_requires)
104 if not requires:
105 self.console.info("No application requirements")
106 return
107
108 require_args = []
109 for req in requires:
110 # Any requirement that is a local path, but *not* a reference to an archive
111 # file (zip, whl, etc), can be installed editable. If in doubt, install
112 # non-editable.
113 if _is_local_path(req) and not _is_archive(req):
114 require_args.extend(["-e", req])
115 else:
116 require_args.append(req)
117
118 with self.console.wait_bar("Installing dev requirements..."):
119 try:
120 venv.run(
121 [
122 sys.executable,
123 "-u",
124 "-X",
125 "utf8",
126 "-m",
127 "pip",
128 "install",
129 "--upgrade",
130 *(["-vv"] if self.console.is_deep_debug else []),
131 *require_args,
132 *app.requirement_installer_args,
133 ],
134 check=True,
135 encoding="UTF-8",
136 )
137 except subprocess.CalledProcessError as e:
138 raise RequirementsInstallError() from e
139
140 def run_dev_app(
141 self,
142 app: AppConfig,
143 env: dict,
144 venv: VenvContext,
145 passthrough: list[str],
146 **options,
147 ):
148 """Run the app in the dev environment.
149
150 :param app: The config object for the app
151 :param env: environment dictionary for sub command
152 :param passthrough: A list of arguments to pass to the app
153 """
154 main_module = app.main_module()
155
156 # Add in the environment settings to get Python in the state we want.
157 # If an environment variable is already defined, don't overwrite it.
158 for env_key, env_value in self.DEV_ENVIRONMENT.items():
159 env[env_key] = self.tools.os.environ.get(env_key, env_value)
160
161 cmdline = [
162 # Do not add additional switches for sys.executable; see DEV_ENVIRONMENT
163 sys.executable,
164 "-c",
165 (
166 "import runpy, sys;"
167 "sys.path.pop(0);"
168 f"sys.argv.extend({passthrough!r});"
169 f"runpy.run_module("
170 f'"{main_module}", run_name="__main__", alter_sys=True'
171 f")"
172 ),
173 ]
174
175 # Console apps must operate in non-streaming mode so that console input can
176 # be handled correctly. However, if we're in test mode, we *must* stream so
177 # that we can see the test exit sentinel
178 if app.console_app and not app.test_mode:
179 self.console.info("=" * 75)
180 venv.run(
181 cmdline,
182 env=env,
183 encoding="UTF-8",
184 cwd=self.tools.home_path,
185 bufsize=1,
186 stream_output=False,
187 )
188 else:
189 app_popen = venv.Popen(
190 cmdline,
191 env=env,
192 encoding="UTF-8",
193 cwd=self.tools.home_path,
194 stdout=subprocess.PIPE,
195 stderr=subprocess.STDOUT,
196 bufsize=1,
197 )
198
199 # Start streaming logs for the app.
200 self._stream_app_logs(
201 app,
202 popen=app_popen,
203 clean_output=False,
204 )
205
206 def get_environment(self, app: AppConfig):
207 """Create a shell environment where PYTHONPATH points to the source directories
208 described by the app config.
209
210 :param app: The config object for the app
211 """
212
213 env = {
214 "PYTHONPATH": os.pathsep.join(
215 os.fsdecode(Path.cwd() / path) for path in app.PYTHONPATH()
216 )
217 }
218
219 # On Windows, we need to disable the debug allocator because it
220 # conflicts with Python.net. See
221 # https://github.com/pythonnet/pythonnet/issues/1977 for details.
222 if self.platform == "windows": # pragma: no branch
223 env["PYTHONMALLOC"] = "default" # pragma: no-cover-if-not-windows
224
225 # If we're in verbose mode, put BRIEFCASE_DEBUG into the environment
226 if self.console.is_debug:
227 env["BRIEFCASE_DEBUG"] = "1"
228
229 return env
230
231 @property
232 def venv_name(self) -> str:
233 """Returns the name of the virtual environment directory.
234
235 The environment name is platform and Python version specific, so
236 that multiple OSes and Python versions can share a `.briefcase`
237 folder. The name is based on the extension module filename that the
238 platform uses (e.g., cpython-313-darwin).
239
240 :returns: Name for virtual environment directory
241 """
242 ext = importlib.machinery.EXTENSION_SUFFIXES[0].split(".")[1]
243 return f"dev.{ext}"
244
245 def venv_path(self, appname: str) -> Path:
246 """Return the path for the app's virtual environment.
247
248 :param app: The app config
249 :returns: Path where the venv should be located
250 """
251 return self.base_path / ".briefcase" / appname / self.venv_name
252
253 def __call__(
254 self,
255 appname: str | None = None,
256 update_requirements: bool | None = False,
257 run_app: bool | None = True,
258 test_mode: bool | None = False,
259 isolated: bool | None = True,
260 passthrough: list[str] | None = None,
261 **options,
262 ):
263 # Which app should we run? If there's only one defined
264 # in pyproject.toml, then we can use it as a default;
265 # otherwise look for a -a/--app option.
266 if len(self.apps) == 1:
267 app = next(iter(self.apps.values()))
268 elif appname:
269 try:
270 app = self.apps[appname]
271 except KeyError as e:
272 raise BriefcaseCommandError(
273 f"Project doesn't define an application named '{appname}'"
274 ) from e
275
276 else:
277 # Multiple apps, and no explicit --app was provided.
278 # If --no-input was passed, do not prompt - raise error.
279 if not self.console.input_enabled:
280 raise BriefcaseCommandError(
281 "Project specifies more than one application; "
282 "use --app to specify which one to start."
283 )
284
285 # Build mapping for {app_name: formal_name} for selection menu.
286 app_options = {
287 app_name: app_config.formal_name
288 for app_name, app_config in self.apps.items()
289 }
290
291 # Default app is the first listed in the config file
292 default_app_name = next(iter(self.apps.keys()))
293
294 # Display interactive menu to select the app
295 selected_app_name = self.console.selection_question(
296 description="Start dev app",
297 intro=(
298 "Your project defines multiple applications. "
299 "Which application would you like to start (in dev mode)?"
300 ),
301 options=app_options,
302 default=default_app_name,
303 )
304
305 # Use the selected app
306 app = self.apps[selected_app_name]
307
308 # Confirm host compatibility, that all required tools are available,
309 # and that the app configuration is finalized.
310 self.finalize(
311 apps=[app],
312 test_mode=test_mode,
313 )
314
315 self.verify_app(app)
316
317 if not run_app:
318 # If we are not running the app, it means we should update requirements.
319 update_requirements = True
320
321 if isolated:
322 self.console.info("Activating dev environment...", prefix=app.app_name)
323
324 with self.tools.virtual_environment.create(
325 venv_path=self.venv_path(app.app_name),
326 isolated=isolated,
327 recreate=update_requirements,
328 ) as venv:
329 if venv.created:
330 self.console.info("Installing requirements...", prefix=app.app_name)
331 try:
332 self.install_dev_requirements(app, venv, **options)
333 except Exception:
334 # If any problem occurs during installing requirements, remove the
335 # venv; it will need to be re-created on the next run.
336 venv.clean()
337 raise
338
339 write_dist_info(
340 app,
341 self.app_module_path(app).parent / app.dist_info_name,
342 )
343
344 if run_app:
345 if app.test_mode:
346 self.console.info(
347 "Running test suite in dev environment...", prefix=app.app_name
348 )
349 else:
350 self.console.info("Starting in dev mode...", prefix=app.app_name)
351 return self.run_dev_app(
352 app,
353 env=self.get_environment(app),
354 venv=venv,
355 passthrough=[] if passthrough is None else passthrough,
356 **options,
357 )
358
359
360 def _is_archive(filename):
361 """Determine if the file is an archive file.
362
363 :param filename: The path to check
364 :returns: True if the file is an archive.
365 """
366 return any(
367 filename.endswith(ext)
368 for ext in [".tar.gz", ".tar.bz2", ".tar", ".zip", ".whl"]
369 )