builder_peppermint_void/builder/core/command_runner.py
2025-04-25 12:38:42 +00:00

60 lines
2.1 KiB
Python

# -*- coding: utf-8 -*-
"""
SPDX-FileCopyrightText: 2023-2025 PeppermintOS Team
(peppermintosteam@proton.me)
SPDX-License-Identifier: GPL-3.0-or-later
This module provides a function for running commands, with support for chroot environments.
It includes functionality to execute shell commands and log their output.
Credits:
- PeppermintOS Team (peppermintosteam@proton.me) - Development and maintenance of the project.
License:
This code is distributed under the GNU General Public License version 3 or later (GPL-3.0-or-later).
For more details, please refer to the LICENSE file included in the project or visit:
https://www.gnu.org/licenses/gpl-3.0.html
"""
import os
import sys
import subprocess
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
try:
from builder.configs import logger_config
except ImportError as e:
print(f"Error importing necessary modules: {e}. Ensure your environment is set up correctly.")
sys.exit(1)
logger = logger_config.setup_logger('command_runner')
def run_command(command, env=None):
"""Executes a command and logs the output, allowing to pass environment variables."""
try:
if isinstance(command, list):
cmd_str = ' '.join(command)
else:
cmd_str = command
logger.info(f"=> Executing command: {cmd_str}")
process = subprocess.run(command, capture_output=True, text=True, check=True, env=env)
if process.stdout:
logger.debug(f"STDOUT:\n{process.stdout}")
if process.stderr:
logger.debug(f"STDERR:\n{process.stderr}")
return process
except subprocess.CalledProcessError as e:
logger.error(f"Error executing command: {cmd_str}")
logger.error(f"Retcode: {e.returncode}")
logger.error(f"STDOUT:\n{e.stdout}")
logger.error(f"STDERR:\n{e.stderr}")
raise
except FileNotFoundError as e:
logger.error(f"Error: Command not found: {command[0] if isinstance(command, list) else command}")
logger.error(f"Details: {e}")
raise