Debian Codegraph @

src/briefcase/commands/run.py

raw
1 from __future__ import annotations
2
3 import re
4 import subprocess
5 from abc import abstractmethod
6 from contextlib import suppress
7 from pathlib import Path
8
9 from briefcase.config import AppConfig
10 from briefcase.debuggers.base import (
11 AppPackagesPathMappings,
12 AppPathMappings,
13 )
14 from briefcase.exceptions import BriefcaseCommandError, BriefcaseTestSuiteFailure
15 from briefcase.integrations.subprocess import StopStreaming
16
17 from .base import BaseCommand, full_options
18
19
20 class LogFilter:
21 DEFAULT_EXIT_REGEX = r"^>>>>>>>>>> EXIT (?P<returncode>.*) <<<<<<<<<<$"
22
23 def __init__(
24 self,
25 log_popen,
26 clean_filter,
27 clean_output,
28 exit_filter,
29 ):
30 """Create a filter for a log stream.
31
32 :param log_popen: The Popen object for the stream producing the logs.
33 :param clean_filter: A function that will filter a line of logs, returning a
34 "clean" line without any log system preamble.
35 :param clean_output: Should the output displayed to the user be the "clean"
36 output? (Default: True).
37 :param exit_filter: A function that will operate on a string containing the last
38 10 lines of "clean" (i.e., preamble filtered) logs, returning the integer
39 exit status of the process if an exit condition has been detected, or None
40 if the log stream should continue.
41 """
42 self.log_popen = log_popen
43 self.returncode = None
44 self.clean_filter = clean_filter
45 self.clean_output = clean_output
46
47 self.recent_history = []
48 self.exit_filter = exit_filter
49
50 def __call__(self, line):
51 """Filter a single line of a log.
52
53 :param line: A single line of raw system log content, including the newline.
54 """
55 # Compute the clean line
56 if self.clean_filter:
57 filtered = self.clean_filter(line)
58
59 # If the clean filter says the line can be dumped, return without yielding
60 if filtered is None:
61 return
62
63 # If there's a cleaned line, we can determine if it should be
64 # included in analysis
65 clean_line, included = filtered
66 else:
67 # If we don't perform cleaning, we assume all content is potentially
68 # Python and should be included in analysis
69 clean_line = line
70 included = True
71
72 # If we're not using clean output, use the raw line for display.
73 if self.clean_output:
74 display_line = clean_line
75 else:
76 display_line = line
77
78 # If the line is Python content, append the new line, then clip the
79 # recent history to the most recent 10 clean lines, and build a single
80 # string that is the tail of the recent clean lines.
81 if included:
82 self.recent_history.append(clean_line)
83 self.recent_history = self.recent_history[-10:]
84 tail = "\n".join(self.recent_history)
85
86 # Look for the exit condition in the tail
87 if self.exit_filter:
88 self.returncode = self.exit_filter(tail)
89 if self.returncode is not None:
90 # This returncode is captured from output from the app and does not
91 # necessarily mean the app has already exited. However, once
92 # StopStreaming is raised, the output streamer sends a signal to
93 # the app to exit immediately and that may result in the app
94 # exiting with a non-zero returncode. Therefore, wait for the app
95 # to close normally before raising StopStreaming.
96 with suppress(subprocess.TimeoutExpired):
97 self.log_popen.wait(timeout=3)
98 raise StopStreaming()
99
100 # Return the display line
101 yield display_line
102
103 @staticmethod
104 def test_filter(pattern):
105 """A factory method for producing filter functions.
106
107 :param pattern: The multiline regex pattern that identifies content of interest
108 in a log (e.g., success/failure conditions)
109 :returns: A log filter function that returns True if the pattern was found
110 """
111
112 def filter_func(recent):
113 match = filter_func.regex.search(recent)
114 if match:
115 try:
116 return int(match.groupdict()["returncode"])
117 except KeyError:
118 # No returncode group in regex
119 return -998
120 except ValueError:
121 # Non-integer return code content
122 return -999
123 return None
124
125 # Annotate the function with the regex that will be used in the function.
126 filter_func.regex = re.compile(pattern, flags=re.MULTILINE)
127 return filter_func
128
129
130 class RunAppMixin:
131 """A mixin that captures the logic of starting an app and streaming the app logs."""
132
133 allows_passthrough = True
134
135 def _stream_app_logs(
136 self,
137 app: AppConfig,
138 popen,
139 clean_filter=None,
140 clean_output=False,
141 stop_func=lambda: False,
142 log_stream=False,
143 ):
144 """Stream the application's logs, monitoring for exit conditions.
145
146 Catches and cleans up after any Ctrl-C interrupts.
147
148 :param app: The app to be launched
149 :param popen: The Popen object for the stream we are monitoring; this Popen
150 process will be closed after log streaming completes.
151 :param clean_filter: The log cleaning filter to use; see ``LogFilter``
152 for details.
153 :param clean_output: Should the cleaned output be presented to the user?
154 :param stop_func: (Optional) A function that will be invoked to determine
155 if the log stream should be terminated.
156 :param log_stream: Is this a log stream, rather than a literal app stream?
157 On some platforms (especially mobile), we monitor a log stream,
158 rather that the output of the app itself. If this case, the cleanup
159 process is different, as the reported exit status of the popen object
160 is of the log, not the app itself.
161 """
162 try:
163 exit_filter = LogFilter.test_filter(
164 getattr(app, "exit_regex", LogFilter.DEFAULT_EXIT_REGEX)
165 )
166
167 log_filter = LogFilter(
168 popen,
169 clean_filter=clean_filter,
170 clean_output=clean_output,
171 exit_filter=exit_filter,
172 )
173
174 # Start streaming logs for the app.
175 self.console.info("=" * 75)
176 with popen:
177 self.tools.subprocess.stream_output(
178 label="log stream" if log_stream else app.app_name,
179 popen_process=popen,
180 stop_func=stop_func,
181 filter_func=log_filter,
182 )
183
184 # If we're in test mode, and log streaming ends,
185 # check for the status of the test suite.
186 if app.test_mode:
187 if log_filter.returncode == 0:
188 self.console.info("Test suite passed!", prefix=app.app_name)
189 else:
190 if log_filter.returncode is None:
191 raise BriefcaseCommandError(
192 "Test suite didn't report a result."
193 )
194 else:
195 self.console.error("Test suite failed!", prefix=app.app_name)
196 raise BriefcaseTestSuiteFailure()
197 elif log_stream:
198 # If we're monitoring a log stream, and the log stream reported a
199 # non-zero exit code, surface that error to the user.
200 if log_filter.returncode is not None and log_filter.returncode != 0:
201 raise BriefcaseCommandError(f"Problem running app {app.app_name}.")
202 else:
203 # If we're monitoring an actual app (not just a log stream),
204 # and the app didn't exit cleanly, surface the error to the user.
205 if popen.poll() != 0:
206 raise BriefcaseCommandError(f"Problem running app {app.app_name}.")
207
208 except KeyboardInterrupt:
209 pass # Catch CTRL-C to exit normally
210
211
212 class RunCommand(RunAppMixin, BaseCommand):
213 command = "run"
214 description = "Run an app."
215
216 def add_options(self, parser):
217 parser.add_argument(
218 "-a",
219 "--app",
220 dest="appname",
221 help="The app to run",
222 )
223
224 self._add_update_options(parser, context_label=" before running")
225 self._add_test_options(parser, context_label="Run")
226
227 if self.supports_debugger:
228 self._add_debug_options(parser, context_label="Run", run_cmd=True)
229
230 def debugger_app_path_mappings(self, app: AppConfig) -> AppPathMappings:
231 """Get the path mappings for the app code.
232
233 :param app: The config object for the app
234 :returns: The path mappings for the app code
235 """
236 device_subfolders = []
237 host_folders = []
238 for src in app.all_sources():
239 original = Path(self.base_path / src)
240 device_subfolders.append(original.name)
241 host_folders.append(f"{original.absolute()}")
242 return AppPathMappings(
243 device_sys_path_regex="app$",
244 device_subfolders=device_subfolders,
245 host_folders=host_folders,
246 )
247
248 def debugger_app_packages_path_mapping(
249 self,
250 app: AppConfig,
251 ) -> AppPackagesPathMappings:
252 """Get the path mappings for the app packages.
253
254 :param app: The config object for the app
255 :returns: The path mappings for the app packages
256 """
257 # When developing an app on your host system for your host system, no path
258 # mapping is required. The paths are automatically found.
259 return None
260
261 def _prepare_app_kwargs(
262 self,
263 app: AppConfig,
264 ):
265 """Prepare the kwargs for running an app as a log stream.
266
267 This won't be used by every backend; but it's a sufficiently common default that
268 it's been factored out.
269
270 :param app: The app to be launched
271 :returns: A dictionary of additional arguments to pass to the Popen
272 """
273 args = {}
274 env = {}
275
276 # If we're in debug mode, put BRIEFCASE_DEBUG into the environment
277 if self.console.is_debug:
278 env["BRIEFCASE_DEBUG"] = "1"
279
280 # If we're in remote debug mode, save the remote debugger config
281 if app.debugger:
282 env["BRIEFCASE_DEBUGGER"] = app.debugger.get_env_config(self, app)
283
284 if app.test_mode:
285 # In test mode, set a BRIEFCASE_MAIN_MODULE environment variable
286 # to override the module at startup
287 env["BRIEFCASE_MAIN_MODULE"] = app.main_module()
288 self.console.info("Starting test_suite...", prefix=app.app_name)
289 else:
290 self.console.info("Starting app...", prefix=app.app_name)
291
292 # If we need any environment variables, add them to the arguments.
293 if env:
294 args["env"] = env
295
296 return args
297
298 @abstractmethod
299 def run_app(
300 self,
301 app: AppConfig,
302 *,
303 passthrough: list[str],
304 **options,
305 ) -> dict | None:
306 """Start an application.
307
308 :param app: The application to start
309 :param passthrough: Any passthrough arguments
310 """
311
312 def __call__(
313 self,
314 appname: str | None = None,
315 update: bool = False,
316 update_requirements: bool = False,
317 update_resources: bool = False,
318 update_support: bool = False,
319 update_stub: bool = False,
320 no_update: bool = False,
321 test_mode: bool = False,
322 debugger: str | None = None,
323 debugger_host: str | None = None,
324 debugger_port: int | None = None,
325 passthrough: list[str] | None = None,
326 **options,
327 ) -> dict | None:
328 # Which app should we run? If there's only one defined
329 # in pyproject.toml, then we can use it as a default;
330 # otherwise look for a -a/--app option.
331 if len(self.apps) == 1:
332 app = next(iter(self.apps.values()))
333 elif appname:
334 try:
335 app = self.apps[appname]
336 except KeyError as e:
337 raise BriefcaseCommandError(
338 f"Project doesn't define an application named '{appname}'"
339 ) from e
340 else:
341 # Multiple apps, and no explicit --app was provided.
342 # If --no-input was passed, do not prompt - raise error.
343 if not self.console.input_enabled:
344 raise BriefcaseCommandError(
345 "Project specifies more than one application; "
346 "use --app to specify which one to start."
347 )
348
349 # Build mapping for {app_name: formal_name} for selection menu.
350 app_options = {
351 app_name: app_config.formal_name
352 for app_name, app_config in self.apps.items()
353 }
354
355 # Default app is the first listed in the config file
356 default_app_name = next(iter(self.apps.keys()))
357
358 # Display interactive menu to select the app
359 selected_app_name = self.console.selection_question(
360 description="Start app",
361 intro=(
362 "Your project defines multiple applications. "
363 "Which application would you like to start?"
364 ),
365 options=app_options,
366 default=default_app_name,
367 )
368
369 # Use the selected app
370 app = self.apps[selected_app_name]
371
372 # Confirm host compatibility, that all required tools are available,
373 # and that the app configuration is finalized.
374 self.finalize(
375 apps=[app],
376 test_mode=test_mode,
377 debugger=debugger,
378 debugger_host=debugger_host,
379 debugger_port=debugger_port,
380 )
381
382 template_file = self.bundle_path(app)
383 exec_file = self.binary_executable_path(app)
384 if (
385 (not template_file.exists()) # App hasn't been created
386 or update # An explicit update has been requested
387 or update_requirements # An explicit requirements update has been requested
388 or update_resources # An explicit resource update has been requested
389 or update_support # An explicit support file update has been requested
390 or update_stub # An explicit stub binary update has been requested
391 or (not exec_file.exists()) # Executable binary doesn't exist yet
392 or (app.test_mode and not no_update) # Test mode, but updates are enabled
393 ):
394 state = self.build_command(
395 app,
396 update=update,
397 update_requirements=update_requirements,
398 update_resources=update_resources,
399 update_support=update_support,
400 update_stub=update_stub,
401 no_update=no_update,
402 **options,
403 )
404 else:
405 state = None
406
407 self.verify_app(app)
408
409 if app.external_package_path:
410 raise BriefcaseCommandError(
411 f"{app.app_name!r} is declared as an external app. External apps "
412 "(apps defining 'external_package_path') cannot be run."
413 )
414
415 state = self.run_app(
416 app,
417 passthrough=[] if passthrough is None else passthrough,
418 **full_options(state, options),
419 )
420
421 return state