""" Copyright (c) 2023-2024 Wind River Systems, Inc. SPDX-License-Identifier: Apache-2.0 """ import logging import os import subprocess from apt_ostree import exceptions LOG = logging.getLogger(__name__) def run_command(cmd, debug=False, stdin=None, stdout=None, stderr=None, check=True, env=None, cwd=None): """Run a command in a shell.""" _env = os.environ.copy() if env: _env.update(env) try: return subprocess.run( cmd, stdin=stdin, stdout=stdout, stderr=stderr, env=_env, cwd=cwd, check=check, ) except FileNotFoundError: msg = "%s is not found in $PATH" % cmd[0] LOG.error(msg) raise exceptions.CommandError(msg) except subprocess.CalledProcessError as e: msg = "Shell execution error: %s, Output: %s" \ % (e.returncode, e.stderr.decode("utf-8")) LOG.error(msg) raise exceptions.CommandError(msg) def run_sandbox_command( args, rootfs, stdin=None, stdout=None, stderr=None, check=True, env=None ): """Run a shell wrapped with bwrap.""" cmd = [ "bwrap", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--bind", "/tmp", "/tmp", "--bind", f"{rootfs}/boot", "/boot", "--bind", f"{rootfs}/usr", "/usr", "--bind", f"{rootfs}/etc", "/etc", "--bind", f"{rootfs}/var", "/var", "--symlink", "/usr/lib", "/lib", "--symlink", "/usr/lib64", "/lib64", "--symlink", "/usr/bin", "/bin", "--symlink", "/usr/sbin", "/sbin", "--share-net", "--die-with-parent", "--chdir", "/", ] cmd += args return run_command( cmd, stdin=stdin, stdout=stdout, stderr=stderr, check=check, env=env, ) def check_and_append_component(config_path, component): with open(config_path, 'r') as file: lines = file.readlines() for i, line in enumerate(lines): if line.startswith("Components:"): components = line.split()[1:] if component not in components: lines[i] = line.strip() + f" {component}\n" break with open(config_path, 'w') as file: file.writelines(lines) def remove_component_from_config(config_path, component): try: with open(config_path, 'r') as file: lines = file.readlines() except FileNotFoundError: msg = "The file %s does not exist." % config_path LOG.error(msg) return False updated_lines = [] component_found = False for line in lines: if line.startswith("Components:"): components = line.split()[1:] if component in components: components.remove(component) component_found = True updated_line = "Components: " + " ".join(components) + "\n" updated_lines.append(updated_line) else: updated_lines.append(line) if not component_found: msg = "Component %s not found in the configuration." % component LOG.error(msg) return False with open(config_path, 'w') as file: file.writelines(updated_lines) LOG.info("Component %s removed from %s successfully" % (component, config_path)) return True