Debian Codegraph @

src/briefcase/integrations/subprocess.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import json
5 import operator
6 import os
7 import queue
8 import shlex
9 import subprocess
10 import sys
11 import threading
12 import time
13 from collections.abc import Callable, Iterator, Mapping, Sequence
14 from functools import wraps
15 from pathlib import Path
16 from subprocess import CompletedProcess
17 from typing import TypeVar
18
19 import psutil
20
21 from briefcase.config import AppConfig
22 from briefcase.console import Console, LogLevel
23 from briefcase.exceptions import CommandOutputParseError, ParseError
24 from briefcase.integrations.base import Tool, ToolCache
25
26 SubprocessArgT = str | Path
27 SubprocessArgsT = Sequence[SubprocessArgT]
28 JsonT = Mapping[str, "JsonT"] | Sequence["JsonT"] | str | int | float | bool | None
29 ParserOutputT = TypeVar("ParserOutputT")
30
31
32 class StopStreaming(Exception):
33 """Raised by streaming filters to terminate the stream."""
34
35
36 def ensure_str(text: str | bytes) -> str:
37 """Returns input text as a string."""
38 return text.decode() if isinstance(text, bytes) else str(text)
39
40
41 def json_parser(json_output: str) -> JsonT:
42 """Wrapper to parse command output as JSON via parse_output.
43
44 :param json_output: command output to parse as JSON
45 """
46 try:
47 return json.loads(json_output)
48 except json.JSONDecodeError as e:
49 raise ParseError(f"Failed to parse output as JSON: {e}") from e
50
51
52 def is_process_dead(pid: int) -> bool:
53 """Returns True if a PID is not assigned to a process.
54
55 Checking if a PID exists is only a semi-safe proxy to determine if a process is dead
56 since PIDs can be reused. Therefore, this function should only be used via constant
57 monitoring of a PID to identify when the process goes from existing to not existing.
58
59 :param pid: integer value to be checked if assigned as a PID.
60 :returns: True if PID does not exist; False otherwise.
61 """
62 return not psutil.pid_exists(pid)
63
64
65 def get_process_id_by_command(
66 command_list: list[str] | None = None,
67 command: str = "",
68 console: Console | None = None,
69 ) -> int | None:
70 """Find a Process ID (PID) a by its command. If multiple processes are found, then
71 the most recently created process ID is returned.
72
73 :param command_list: list of a command's fully qualified path and its arguments.
74 :param command: a partial or complete fully-qualified filepath to a command.
75 This is primarily intended for use on macOS where the `open` command
76 takes a filepath to a directory for an application; therefore, the actual
77 running process will be running a command within that directory.
78 :param console: optional console to show messages about process matching to users
79 :returns: PID if found else None
80 """
81 matching_procs = []
82 # retrieve command line, creation time, and ID for all running processes.
83 # note: psutil returns None for a process attribute if it is unavailable;
84 # this is most likely to happen for restricted or zombie processes.
85 for proc in psutil.process_iter(["cmdline", "create_time", "pid"]):
86 proc_cmdline: list[str] = proc.info["cmdline"]
87 if command_list and proc_cmdline == command_list:
88 matching_procs.append(proc.info)
89 if command and proc_cmdline and proc_cmdline[0].startswith(command):
90 matching_procs.append(proc.info)
91
92 if len(matching_procs) == 1:
93 return matching_procs[0]["pid"]
94 elif len(matching_procs) > 1:
95 # return the ID of the most recently created matching process
96 pid = sorted(matching_procs, key=operator.itemgetter("create_time"))[-1]["pid"]
97 if console:
98 console.info(
99 f"Multiple running instances of app found. "
100 f"Using most recently created app process {pid}."
101 )
102 return pid
103
104 return None
105
106
107 def ensure_console_is_safe(sub_method):
108 """Decorator for Subprocess methods to conditionally remove dynamic console elements
109 such as the Wait Bar prior to running the subprocess command.
110
111 :param sub_method: wrapped Subprocess method
112 """
113
114 @wraps(sub_method)
115 def inner(sub: Subprocess, args: SubprocessArgsT, *wrapped_args, **wrapped_kwargs):
116 """Evaluate whether conditions are met to remove any dynamic elements in the
117 console before returning control to Subprocess.
118
119 :param sub: Bound Subprocess object
120 :param args: command line to run in subprocess
121 :returns: the return value for the Subprocess method
122 """
123 # Just run the command if no dynamic elements are active
124 if not sub.tools.console.is_console_controlled:
125 return sub_method(sub, args, *wrapped_args, **wrapped_kwargs)
126
127 remove_dynamic_elements = False
128
129 # Batch (.bat) scripts on Windows.
130 # If cmd.exe is interrupted with CTRL+C while running a bat script,
131 # it may prompt the user to abort the script and dynamic elements
132 # such as the Wait Bar can hide this message from the user.
133 if sub.tools.host_os == "Windows":
134 executable = str(args[0]).strip() if args else ""
135 remove_dynamic_elements |= executable.lower().endswith(".bat")
136
137 # Release control for commands that cannot be streamed.
138 remove_dynamic_elements |= wrapped_kwargs.get("stream_output") is False
139
140 # Run subprocess command with or without console control
141 if remove_dynamic_elements:
142 with sub.tools.console.release_console_control():
143 return sub_method(sub, args, *wrapped_args, **wrapped_kwargs)
144 else:
145 return sub_method(sub, args, *wrapped_args, **wrapped_kwargs)
146
147 return inner
148
149
150 class PopenOutputStreamer(threading.Thread):
151 def __init__(
152 self,
153 label: str,
154 popen_process: subprocess.Popen,
155 console: Console,
156 capture_output: bool = False,
157 filter_func: Callable[[str], Iterator[str]] | None = None,
158 ):
159 """Thread for streaming stdout for a Popen process.
160
161 :param label: Descriptive name for process being streamed
162 :param popen_process: Popen process with stdout to stream
163 :param console: console for printing to console
164 :param capture_output: Retain process output in ``output_queue`` via a
165 ``queue.Queue`` instead of printing to console
166 :param filter_func: a callable that will be invoked on every line of output
167 that is streamed; see ``Subprocess.stream_output`` for details
168 """
169 super().__init__(name=f"{label} output streamer", daemon=True)
170
171 self.popen_process = popen_process
172 self.console = console
173 self.capture_output = capture_output
174 self.filter_func = filter_func
175
176 # arbitrarily large maxsize to prevent unbounded memory use if things go south
177 self.output_queue = queue.Queue(maxsize=10_000_000)
178 self.stop_flag = threading.Event()
179
180 def run(self):
181 """Stream output for a Popen process."""
182 try:
183 while output_line := self._readline():
184 # The stop_flag is intentionally checked both at the top and bottom of
185 # this loop; if the flag was set during the call to readline(), then
186 # processing the output is skipped altogether. And if the flag is set
187 # as a consequence of filter_func(), the streamer still exits before
188 # calling readline() again and potentially blocking indefinitely.
189 if not self.stop_flag.is_set():
190 filtered_output, stop_streaming = self._filter(output_line)
191
192 for filtered_line in filtered_output:
193 if self.capture_output:
194 self.output_queue.put_nowait(filtered_line)
195 else:
196 self.console.info(filtered_line)
197
198 if stop_streaming:
199 self.stop_flag.set()
200
201 if self.stop_flag.is_set():
202 break
203 except Exception as e:
204 self.console.error(f"Error while streaming output: {type(e).__name__}: {e}")
205 self.console.capture_stacktrace("Output thread")
206
207 def request_stop(self):
208 """Set the stop flag to cause the streamer to exit.
209
210 If the streamer is currently blocking on `readline()` because the process'
211 stdout buffer is empty, then the streamer will not exit until `readline()`
212 returns or until Briefcase exits.
213 """
214 self.stop_flag.set()
215
216 @property
217 def captured_output(self) -> str:
218 """The captured output from the process."""
219 output = []
220 while not self.output_queue.empty():
221 with contextlib.suppress(queue.Empty):
222 output.append(self.output_queue.get_nowait())
223 self.output_queue.task_done()
224 return "".join(output)
225
226 def _readline(self) -> str:
227 """Read a line of output from the process while blocking.
228
229 Calling readline() for stdout always returns at least a newline, i.e. "\n",
230 UNLESS the process is exiting or already exited; in that case, an empty string
231 is returned.
232
233 :returns: one line of output or "" if nothing more can be read from stdout
234 """
235 try:
236 return ensure_str(self.popen_process.stdout.readline())
237 except ValueError as e:
238 # Catch ValueError if stdout is unexpectedly closed; this can
239 # happen, for instance, if the user starts spamming CTRL+C.
240 if "I/O operation on closed file" in str(e):
241 self.console.warning(
242 "WARNING: stdout was unexpectedly closed while streaming output"
243 )
244 return ""
245 else:
246 raise
247
248 def _filter(self, line: str) -> tuple[list[str], bool]:
249 """Run filter function over output from process."""
250 filtered_output = []
251 stop_streaming = False
252
253 if self.filter_func is not None:
254 try:
255 for filtered_line in self.filter_func(line.strip("\n")):
256 filtered_output.append(filtered_line)
257 except StopStreaming:
258 stop_streaming = True
259 else:
260 filtered_output.append(line)
261
262 return filtered_output, stop_streaming
263
264
265 class NativeAppContext(Tool):
266 """A wrapper around subprocess for use as an app-bound tool."""
267
268 name = "app_context_subprocess"
269
270 @classmethod
271 def verify_install(cls, tools: ToolCache, app: AppConfig, **kwargs) -> Subprocess:
272 """Make subprocess available as app-bound tool."""
273 # short circuit since already verified and available
274 if hasattr(tools[app], "app_context"):
275 return tools[app].app_context
276
277 tools[app].app_context = tools.subprocess
278 return tools[app].app_context
279
280
281 class Subprocess(Tool):
282 """A wrapper around subprocess that can be used as a logging point for commands that
283 are executed."""
284
285 name = "subprocess"
286 full_name = "Subprocess"
287
288 def __init__(self, tools: ToolCache):
289 super().__init__(tools=tools)
290 self._subprocess = subprocess
291
292 def prepare(self):
293 """Perform any environment preparation required to execute processes."""
294 # This is a no-op; the native subprocess environment is ready-to-use.
295
296 @contextlib.contextmanager
297 def run_app_context(self, subprocess_kwargs: dict[str, ...]) -> dict[str, ...]:
298 """A manager to wrap subprocess calls to run a Briefcase project app.
299
300 :param subprocess_kwargs: initialized keyword arguments for subprocess calls
301 """
302 # This is a no-op; the native subprocess environment is ready-to-use.
303 yield subprocess_kwargs
304
305 def full_env(self, overrides: dict[str, str | None] | None) -> dict[str, str]:
306 """Generate the full environment in which the command will run.
307
308 If an env var in `overrides` is set to `None`, then that env var
309 will be altogether absent in the returned environment.
310
311 :param overrides: The environment passed to the subprocess call;
312 can be `None` if there are no explicit environment changes.
313 """
314 env = self.tools.os.environ.copy()
315 if overrides:
316 env.update(overrides)
317 env = {k: v for k, v in env.items() if v is not None}
318 return env
319
320 def final_kwargs(self, **kwargs) -> dict[str, str]:
321 """Convert subprocess keyword arguments into their final form.
322
323 This involves:
324 * Converting any environment overrides into a full environment
325 * Converting the `cwd` into a string
326 * Default `text` to True so all outputs are strings
327 * Convert start_new_session=True to creationflags on Windows
328 """
329 # If `env` has been provided, inject a full copy of the local
330 # environment, with the values in `env` overriding the local
331 # environment.
332 try:
333 overrides = kwargs.pop("env")
334 kwargs["env"] = self.full_env(overrides)
335 except KeyError:
336 # No explicit environment provided.
337 pass
338
339 # If `cwd` has been provided, ensure it is in string form.
340 try:
341 cwd = kwargs.pop("cwd")
342 kwargs["cwd"] = str(cwd)
343 except KeyError:
344 pass
345
346 # Default to running subprocess in "text" mode so all output is returned as
347 # strings instead of bytes. The legacy setting of `universal_newlines` is
348 # converted to `text` for calling subprocess.
349 kwargs["text"] = kwargs.pop("universal_newlines", kwargs.get("text", True))
350
351 # Enable text mode if an `encoding` or `errors` is specified; this aligns with
352 # the default behavior of subprocess.
353 kwargs["text"] |= any(kwargs.get(kw) for kw in ["encoding", "errors"])
354
355 # Configure subprocess for text mode
356 if kwargs["text"]:
357 # Ensure an appropriate encoding is specified.
358 # If an encoding isn't provided, default to the encoding that Python is
359 # using for stdout. This is for the benefit of Windows which uses cp437 for
360 # console output when the system encoding is cp1252.
361 # `sys.__stdout__` is used because Rich captures and redirects `sys.stdout`.
362 # The fallback to "UTF-8" is needed to catch the case where stdout is
363 # redirected to a non-tty (e.g. during pytest conditions).
364 kwargs.setdefault(
365 "encoding", os.device_encoding(sys.__stdout__.fileno()) or "UTF-8"
366 )
367
368 # Use relaxed output decoding by default.
369 # subprocess defaults to "strict" handling for errors arising from decoding
370 # output to Unicode. To avoid Unicode exceptions from misbehaving commands,
371 # set `errors` so output that cannot be decoded for the specified encoding
372 # are replaced with hex of the raw bytes.
373 kwargs.setdefault("errors", "backslashreplace")
374
375 # For Windows, convert start_new_session=True to creation flags
376 if self.tools.host_os == "Windows":
377 try:
378 if kwargs.pop("start_new_session") is True:
379 if "creationflags" in kwargs:
380 raise AssertionError(
381 "Subprocess called with creationflags set and "
382 "start_new_session=True.\nThis will result in "
383 "CREATE_NEW_PROCESS_GROUP and CREATE_NO_WINDOW "
384 "being merged in to the creationflags.\n\nEnsure "
385 "this is desired configuration or don't set "
386 "start_new_session=True."
387 )
388 # CREATE_NEW_PROCESS_GROUP: Promotes the new process to the root
389 # process of a new process group. This also disables CTRL+C
390 # signal handlers for all processes of the new process group.
391 # CREATE_NO_WINDOW: Creates a new console for the process but
392 # does not open a visible window for that console. This flag
393 # is used instead of DETACHED_PROCESS since the new process
394 # can spawn a new console itself (in the absence of one being
395 # available) but that console creation will also spawn a
396 # visible console window.
397 new_session_flags = (
398 self._subprocess.CREATE_NEW_PROCESS_GROUP
399 | self._subprocess.CREATE_NO_WINDOW
400 )
401 # merge these flags in to any existing flags already provided
402 kwargs["creationflags"] = (
403 kwargs.get("creationflags", 0) | new_session_flags
404 )
405 except KeyError:
406 pass
407
408 return kwargs
409
410 @classmethod
411 def verify_install(cls, tools: ToolCache, **kwargs) -> Subprocess:
412 """Make subprocess available in tool cache."""
413 # short circuit since already verified and available
414 if hasattr(tools, "subprocess"):
415 return tools.subprocess
416
417 tools.subprocess = Subprocess(tools=tools)
418 return tools.subprocess
419
420 @ensure_console_is_safe
421 def run(
422 self,
423 args: SubprocessArgsT,
424 stream_output: bool = True,
425 filter_func: Callable[[str], Iterator[str]] | None = None,
426 **kwargs,
427 ) -> CompletedProcess:
428 """A wrapper for subprocess.run().
429
430 This method implements the behavior of subprocess.run() with some notable
431 differences:
432
433 - The command's output is streamed if ``stream_output=True`` or if dynamic
434 console content such as the Wait Bar is active and I/O is not redirected.
435 - If dynamic content is not active, ``stream_output=False`` will disable
436 streaming.
437 - If the ``env`` argument is provided, the current system environment will be
438 copied, and the contents of env overwritten into that environment.
439 - The ``text`` argument is defaulted to True so all output is returned as
440 strings instead of bytes.
441
442 Output Streaming Primer
443 ~~~~~~~~~~~~~~~~~~~~~~~
444
445 What is output streaming?
446 -------------------------
447
448 When a command is invoked via ``subprocess.run()``, by default, its stdout and
449 stderr are connected directly to the console and the output is presented to the
450 user as though the command was invoked natively. When output streaming is
451 active, Briefcase reads the command's output and prints it in to the console on
452 behalf of the command.
453
454 Why is output streaming necessary?
455 ----------------------------------
456
457 Allowing commands to print directly to the console can provide superior UX since
458 it allows tools to provide their native experience to users.
459
460 However, a primary mechanism for providing support for Briefcase is asking users
461 to provide the log file when errors occur. Often, these errors are raised by
462 invoked commands; streaming the output of commands allows Briefcase to capture
463 that output and include it in the log file as well as the console.
464
465 Additionally, the content of the console can become corrupted if other processes
466 print to the console while Rich's dynamic console elements such as a Progress
467 Bar are active. Streaming such output allows Rich to maintain integrity of all
468 the console content.
469
470 How does output streaming work?
471 -------------------------------
472
473 Streaming is activated when:
474
475 1. dynamic content such as the Wait Bar is active and I/O is not redirected
476
477 2. the ``stream_output`` argument is ``True`` (as it is by default)
478
479 I/O is considered redirected when both ``stdout`` and ``stderr`` are specified
480 (e.g., when ``stdout`` and ``stderr`` are set to``subprocess.PIPE`` so the
481 output is available to the caller).
482
483 To facilitate streaming the output, ``stdout`` is set to ``subprocess.PIPE``. If
484 ``stderr`` is not specified by calling code, then it is set to
485 ``subprocess.STDOUT`` so it is interlaced with stdout output.
486
487 The process is created for the command with ``Popen``, and a separate thread is
488 started for continuously reading and printing the stdout to the console from the
489 command process. It is necessary to read from stdout in a thread because the
490 read is uninterruptible; so, a user may not be able to abort with CTRL-C.
491
492 When the process ends (or the user sends CTRL-C), a call is made to ensure the
493 command process terminates; this, in turn, ensures the thread for streaming can
494 properly exit its otherwise infinite loop. The calling code is either returned a
495 ``CompletedProcess`` object or ``CalledProcessError`` could be raised.
496
497 Output streaming ultimately strives to simulate calling ``subprocess.run()``
498 while proxying the command's output to the console.
499
500 When *not* to use output streaming?
501 -----------------------------------
502
503 When streaming is disabled, the command's output **WILL NOT** be included the
504 Briefcase log file. This makes troubleshooting difficult and should be avoided.
505 However, there are some situations where disabling streaming is unavoidable.
506
507 Some commands use their own dynamic console content such as progress bars,
508 spinners, and other animations. When such output is streamed, its quality can be
509 significantly compromised and look terrible in the console for users. If it is
510 not possible to disable such output with e.g. a flag for the command, then
511 disabling streaming may be necessary. As an example, the ``flatpak install``
512 command uses many animations.
513
514 If a command requires user input, do not use output streaming. The output
515 streaming implementation doesn't provide any facilities to send input to the
516 process and doesn't provide any special handling of stdin. Additionally, when
517 the command process prompts the user for input, that doesn't always trigger
518 ``readline()`` to return; so, the console may actually end up waiting for user
519 input before displaying a prompt to the user. As an example, accepting Android
520 SDK licenses requires user input.
521
522 :param args: args for ``subprocess.run()``
523 :param stream_output: simulate ``run()`` while streaming the output to the
524 console. Set to False if the command requires user interaction.
525 :param filter_func: If output streaming is enabled, a callable that will be
526 invoked on every line of output that is streamed. The function accepts the
527 "raw" line of input (stripped of any trailing newline); it returns a
528 generator that yields the filtered output that should be displayed to the
529 user. Can raise StopStreaming to terminate the output stream.
530 :param kwargs: keyword args for ``subprocess.run()``
531 :raises ValueError: if a filter function is provided when in non-streaming mode.
532 :returns: ``CompletedProcess`` for invoked process
533 """
534
535 # Stream the output unless the caller explicitly disables it. When a
536 # caller sets stream_output=False, then ensure_console_is_safe() will
537 # disable any dynamic console elements while the command runs.
538 if stream_output:
539 return self._run_and_stream_output(args, filter_func=filter_func, **kwargs)
540
541 # Can't filter non-streamed output.
542 if filter_func:
543 raise ValueError("Cannot apply a filter to non-streamed output.")
544
545 # Otherwise, invoke run() normally.
546 self._log_command(args)
547 self._log_cwd(kwargs.get("cwd"))
548 self._log_environment(kwargs.get("env"))
549
550 try:
551 command_result = self._subprocess.run(
552 [str(arg) for arg in args], **self.final_kwargs(**kwargs)
553 )
554 except subprocess.CalledProcessError as e:
555 self._log_return_code(e.returncode)
556 raise
557 self._log_return_code(command_result.returncode)
558
559 return command_result
560
561 def _run_and_stream_output(
562 self,
563 args: SubprocessArgsT,
564 check: bool = False,
565 filter_func: Callable[[str], Iterator[str]] | None = None,
566 **kwargs,
567 ) -> CompletedProcess:
568 """Simulate subprocess.run() while streaming output to the console.
569
570 This is useful when dynamic screen content is active or output should
571 be captured for logging.
572
573 When dynamic screen content like a Wait Bar is active, output can
574 only be printed to the screen via Console to avoid interfering
575 with and likely corrupting the updates to the dynamic screen elements.
576
577 stdout will always be piped so it can be printed to the screen;
578 however, stderr can be piped by the caller so it is available
579 to the caller in the return value...as with subprocess.run().
580
581 Note: the 'timeout' and 'input' arguments are not supported.
582 """
583 if kwargs.get("stdout") and not kwargs.get("stderr"):
584 # This is an unsupported configuration, as it's not clear where stderr
585 # output would be displayed. Either:
586 # * Redirect stderr in addition to stdout; or
587 # * Use check_output() instead of run() to capture console output
588 # without streaming.
589 raise AssertionError(
590 "Subprocess.run() was invoked while dynamic Rich content is active (or "
591 "via `stream_output`) with stdout redirected while stderr was not "
592 "redirected."
593 )
594 for arg in [arg for arg in ["timeout", "input"] if arg in kwargs]:
595 raise AssertionError(
596 f"The Subprocess.run() '{arg}' argument is not supported "
597 f"with `stream_output` or while dynamic Rich content is active."
598 )
599
600 # stdout must be piped so the output streamer can print it.
601 kwargs["stdout"] = subprocess.PIPE
602 # if stderr isn't explicitly redirected, then send it to stdout.
603 kwargs.setdefault("stderr", subprocess.STDOUT)
604 # use line-buffered output by default
605 kwargs.setdefault("bufsize", 1)
606
607 stderr = None
608 with self.Popen(args, **kwargs) as process:
609 self.stream_output(args[0], process, filter_func=filter_func)
610 if process.stderr and kwargs["stderr"] != subprocess.STDOUT:
611 stderr = process.stderr.read()
612 return_code = process.poll()
613 self._log_return_code(return_code)
614
615 if check and return_code:
616 raise subprocess.CalledProcessError(return_code, args, stderr=stderr)
617
618 return subprocess.CompletedProcess(args, return_code, stderr=stderr)
619
620 @ensure_console_is_safe
621 def check_output(self, args: SubprocessArgsT, quiet: int = 0, **kwargs) -> str:
622 """A wrapper for subprocess.check_output()
623
624 The behavior of this method is identical to subprocess.check_output(), except
625 for:
626 - If the `env` is argument provided, the current system environment will be
627 copied, and the contents of env overwritten into that environment.
628 - The `text` argument is defaulted to True so all output is returned as strings
629 instead of bytes.
630 - The `stderr` argument is defaulted to `stdout` so _all_ output is returned
631 and `stderr` isn't unexpectedly printed to the console.
632
633 :param args: commands and its arguments to run via subprocess
634 :param quiet: Should the invocation of this command be silent, and *not* appear
635 in the logs? This should almost always be 0, indicating "not quiet"; any
636 command output will be logged, and any errors will be logged *and* printed
637 to the console. A value of 1 will log all command output, but errors will be
638 logged, but *not* printed to the console. A value of 2 will *not* log any
639 command output; errors will be logged, but *not* printed to the console. A
640 value of 2 is mostly useful for calls that are called frequently to evaluate
641 the status of another process (such as calls that poll an API) so that log
642 output isn't corrupted by thousands of polling calls.
643 """
644 # if stderr isn't explicitly redirected, then send it to stdout.
645 kwargs.setdefault("stderr", subprocess.STDOUT)
646
647 if quiet < 2:
648 self._log_command(args)
649 self._log_cwd(kwargs.get("cwd"))
650 self._log_environment(kwargs.get("env"))
651
652 try:
653 cmd_output = self._subprocess.check_output(
654 [str(arg) for arg in args], **self.final_kwargs(**kwargs)
655 )
656 except subprocess.CalledProcessError as e:
657 # Subprocess errors will be logged, and also printed to console if we're at
658 # DEBUG+ log levels. However, if we're at quiet=0 *and* a non-debug log
659 # level, we need to explicitly output to the console.
660 if quiet == 0 and self.tools.console.verbosity < LogLevel.DEBUG:
661 self.output_error(e)
662 if quiet < 2:
663 self._log_output(e.output, e.stderr)
664 self._log_return_code(e.returncode)
665 raise
666
667 if quiet < 2:
668 self._log_output(cmd_output)
669 self._log_return_code(0)
670 return cmd_output
671
672 def parse_output(
673 self,
674 output_parser: Callable[[str], ParserOutputT],
675 args: SubprocessArgsT,
676 **kwargs,
677 ) -> ParserOutputT:
678 """A wrapper for check_output() where the command output is processed through
679 the supplied parser function.
680
681 If the parser fails, CommandOutputParseError is raised. The parsing function
682 should take one string argument and should raise ParseError for failure modes.
683
684 :param output_parser: a function that takes str input and returns parsed
685 content, or raises ParseError in the case of a parsing problem.
686 :param args: The arguments to pass to the subprocess
687 :param kwargs: The keyword arguments to pass to the subprocess
688 :returns: Parsed data read from the subprocess output; the exact structure of
689 that data is dependent on the output parser used.
690 """
691 cmd_output = self.check_output(args, **kwargs)
692
693 try:
694 return output_parser(cmd_output)
695 except ParseError as e:
696 error_reason = (
697 str(e)
698 or f"Failed to parse command output using '{output_parser.__name__}'"
699 )
700 self.tools.console.error()
701 self.tools.console.error("Command Output Parsing Error:")
702 self.tools.console.error(f" {error_reason}")
703 self.tools.console.error("Command:")
704 self.tools.console.error(
705 f" {' '.join(shlex.quote(str(arg)) for arg in args)}"
706 )
707 self.tools.console.error("Command Output:")
708 for line in ensure_str(cmd_output).splitlines():
709 self.tools.console.error(f" {line}")
710 raise CommandOutputParseError(error_reason) from e
711
712 def Popen(self, args: SubprocessArgsT, **kwargs) -> subprocess.Popen:
713 """A wrapper for subprocess.Popen()
714
715 The behavior of this method is identical to
716 subprocess.check_output(), except for:
717 - If the `env` argument is provided, the current system environment
718 will be copied, and the contents of env overwritten into that
719 environment.
720 - The `text` argument is defaulted to True so all output
721 is returned as strings instead of bytes.
722 """
723 self._log_command(args)
724 self._log_cwd(kwargs.get("cwd"))
725 self._log_environment(kwargs.get("env"))
726
727 return self._subprocess.Popen(
728 [str(arg) for arg in args], **self.final_kwargs(**kwargs)
729 )
730
731 def stream_output(
732 self,
733 label: str,
734 popen_process: subprocess.Popen,
735 stop_func: Callable[[], bool] = lambda: False,
736 filter_func: Callable[[str], Iterator[str]] | None = None,
737 ):
738 """Stream the output of a Popen process until the process exits. If the user
739 sends CTRL+C, the process will be terminated.
740
741 This is useful for starting a process via Popen such as tailing a log file, then
742 initiating a non-blocking process that populates that log, and finally streaming
743 the original process's output here.
744
745 :param label: A description of the content being streamed; used for to provide
746 context in logging messages.
747 :param popen_process: a running Popen process with output to print
748 :param stop_func: A Callable that returns True when output streaming should stop
749 and the popen_process should be terminated.
750 :param filter_func: A callable that will be invoked on every line of output that
751 is streamed. The function accepts the "raw" line of input (stripped of any
752 trailing newline); it returns a generator that yields the filtered output
753 that should be displayed to the user. Can raise StopStreaming to terminate
754 the output stream.
755 """
756 output_streamer = PopenOutputStreamer(
757 label=label,
758 popen_process=popen_process,
759 console=self.tools.console,
760 filter_func=filter_func,
761 )
762 try:
763 output_streamer.start()
764 # joining the thread is avoided due to demonstrated
765 # instability of thread interruption via CTRL+C (#809)
766 while not stop_func() and output_streamer.is_alive():
767 time.sleep(0.1)
768 except KeyboardInterrupt:
769 self.tools.console.info("Stopping...")
770 # allow time for CTRL+C to propagate to the child process
771 time.sleep(0.25)
772 # re-raise to exit as "Aborted by user"
773 raise
774 finally:
775 self.cleanup(label, popen_process)
776 streamer_deadline = time.time() + 3
777 while output_streamer.is_alive() and time.time() < streamer_deadline:
778 time.sleep(0.1)
779 if output_streamer.is_alive():
780 self.tools.console.error(
781 "Log stream hasn't terminated; log output may be corrupted."
782 )
783
784 def stream_output_non_blocking(
785 self,
786 label: str,
787 popen_process: Popen,
788 capture_output: bool = False,
789 filter_func: Callable[[str], Iterator[str]] | None = None,
790 ) -> PopenOutputStreamer:
791 """Stream the output of a Popen process without blocking.
792
793 This is useful for streaming or capturing the output of a process in the
794 background. In this way, the process' output can be shown to users while the
795 main thread monitors other activities; alternatively, the output of the process
796 can be captured to be retrieved later in the event of an error, for instance.
797
798 :param label: A description of the content being streamed; used for to provide
799 context in logging messages.
800 :param popen_process: A running Popen process with output to print
801 :param capture_output: Retain process output instead of printing to the console
802 :param filter_func: A callable that will be invoked on every line of output that
803 is streamed. The function accepts the "raw" line of input (stripped of any
804 trailing newline); it returns a generator that yields the filtered output
805 that should be displayed to the user. Can raise StopStreaming to terminate
806 the output stream.
807 """
808 output_streamer = PopenOutputStreamer(
809 label=label,
810 popen_process=popen_process,
811 console=self.tools.console,
812 capture_output=capture_output,
813 filter_func=filter_func,
814 )
815 output_streamer.start()
816 return output_streamer
817
818 def cleanup(self, label: str, popen_process: subprocess.Popen):
819 """Clean up after a Popen process, gracefully terminating if possible; forcibly
820 if not.
821
822 :param label: A description of the content being streamed; used for to provide
823 context in logging messages.
824 :param popen_process: The Popen instance to clean up.
825 """
826 popen_process.terminate()
827 try:
828 popen_process.wait(timeout=3)
829 except subprocess.TimeoutExpired:
830 self.tools.console.warning(f"Forcibly killing {label}...")
831 popen_process.kill()
832
833 def _console(self, msg: str = ""):
834 """Funnel for subprocess console-only logging."""
835 self.tools.console.to_console(msg, style="dim")
836
837 def _log(self, msg: str = ""):
838 """Funnel for all subprocess details logging."""
839 self.tools.console.debug(msg, preface=">>> " if msg else "")
840
841 def _log_command(self, args: SubprocessArgsT, handler=None):
842 """Log the entire console command being executed."""
843 if handler is None:
844 handler = self._log
845
846 handler()
847 handler("Running Command:")
848 handler(f" {' '.join(shlex.quote(str(arg)) for arg in args)}")
849
850 def _log_cwd(self, cwd: str | Path | None):
851 """Log the working directory for the command being executed."""
852 effective_cwd = Path.cwd() if cwd is None else cwd
853 self._log("Working Directory:")
854 self._log(f" {effective_cwd}")
855
856 def _log_environment(self, overrides: dict[str, str] | None):
857 """Log the environment variables overrides prior to command execution.
858
859 :param overrides: The explicit environment passed to the subprocess call;
860 can be `None` if there are no explicit environment changes.
861 """
862 if overrides:
863 self._log("Environment Overrides:")
864 for env_var, value in overrides.items():
865 self._log(f" {env_var}={value}")
866
867 def _log_output(self, output: str, stderr: str | None = None, handler=None):
868 """Log the output of the executed command."""
869 if handler is None:
870 handler = self._log
871
872 if output:
873 handler("Command Output:")
874 for line in ensure_str(output).splitlines():
875 handler(f" {line}")
876
877 if stderr:
878 handler("Command Error Output (stderr):")
879 for line in ensure_str(stderr).splitlines():
880 handler(f" {line}")
881
882 def _log_return_code(self, return_code: int | str, handler=None):
883 """Log the output value of the executed command."""
884 if handler is None:
885 handler = self._log
886 handler(f"Return code: {return_code}")
887 handler()
888
889 def output_error(self, exception: subprocess.CalledProcessException):
890 """Print error from a subprocess to the console.
891
892 This will output the command, output and return code to the console, but *not*
893 to the log.
894
895 :param exception: The raw exception raised by a subprocess
896 """
897 self._log_command(exception.cmd, handler=self._console)
898 self._log_output(exception.output, exception.stderr, handler=self._console)
899 self._log_return_code(exception.returncode, handler=self._console)