xref: /aosp_15_r20/external/toolchain-utils/llvm_tools/subprocess_helpers.py (revision 760c253c1ed00ce9abd48f8546f08516e57485fe)
1# Copyright 2019 The ChromiumOS Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Helpers/wrappers for the subprocess module for migration to python3."""
6
7import subprocess
8
9
10def CheckCommand(cmd):
11    """Executes the command using Popen()."""
12    with subprocess.Popen(
13        cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8"
14    ) as cmd_obj:
15        stdout, _ = cmd_obj.communicate()
16
17    if cmd_obj.returncode:
18        print(stdout)
19        raise subprocess.CalledProcessError(cmd_obj.returncode, cmd)
20
21
22def check_output(cmd, cwd=None):
23    """Wrapper for pre-python3 subprocess.check_output()."""
24
25    return subprocess.check_output(cmd, encoding="utf-8", cwd=cwd)
26
27
28def check_call(cmd, cwd=None):
29    """Wrapper for pre-python3 subprocess.check_call()."""
30
31    subprocess.check_call(cmd, encoding="utf-8", cwd=cwd)
32
33
34# FIXME: CTRL+C does not work when executing a command inside the chroot via
35# `cros_sdk`.
36def ChrootRunCommand(
37    chroot_path,
38    cmd,
39    verbose: bool = False,
40    chroot_name: str = "chroot",
41    out_name: str = "out",
42):
43    """Runs the command inside the chroot."""
44
45    exec_chroot_cmd = [
46        "cros_sdk",
47        f"--chroot={chroot_name}",
48        f"--out-dir={out_name}",
49        "--",
50    ]
51    exec_chroot_cmd.extend(cmd)
52
53    return ExecCommandAndCaptureOutput(
54        exec_chroot_cmd, cwd=chroot_path, verbose=verbose
55    )
56
57
58def ExecCommandAndCaptureOutput(cmd, cwd=None, verbose=False):
59    """Executes the command and prints to stdout if possible."""
60
61    out = check_output(cmd, cwd=cwd).rstrip()
62
63    if verbose and out:
64        print(out)
65
66    return out
67