"""Bounded child-process execution that never leaves orphaned descendants behind.""" from __future__ import annotations import os import signal import subprocess from collections.abc import Mapping, Sequence # Git may daemonize automatic housekeeping (``gc --auto``/``maintenance --auto``) after a # fetch. A detached child escapes the timeout and is reparented to PID 1, where it becomes # a zombie if PID 1 does not reap. Housekeeping therefore runs in the foreground. GIT_FOREGROUND_CONFIG: tuple[tuple[str, str], ...] = ( ("gc.autoDetach", "false"), ("maintenance.autoDetach", "false"), ) def git_environment( base: Mapping[str, str] | None = None, extra_config: Sequence[tuple[str, str]] = (), ) -> dict[str, str]: """Return an environment that applies foreground housekeeping plus ``extra_config``.""" env = dict(os.environ if base is None else base) pairs = [*GIT_FOREGROUND_CONFIG, *extra_config] env["GIT_CONFIG_COUNT"] = str(len(pairs)) for index, (key, value) in enumerate(pairs): env[f"GIT_CONFIG_KEY_{index}"] = key env[f"GIT_CONFIG_VALUE_{index}"] = value return env def _kill_process_tree(process: subprocess.Popen[bytes]) -> None: if os.name == "posix": try: os.killpg(process.pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass else: process.kill() def run_bounded( args: Sequence[str], *, timeout: float, env: Mapping[str, str] | None = None, check: bool = True, ) -> subprocess.CompletedProcess[bytes]: """Run ``args`` in its own process group and reap it and all descendants. On timeout the whole group is killed (not only the direct child), then the child is waited for so no zombie remains. Raises the same exceptions as ``subprocess.run``. """ process = subprocess.Popen( list(args), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=None if env is None else dict(env), start_new_session=os.name == "posix", ) try: stdout, stderr = process.communicate(timeout=timeout) except subprocess.TimeoutExpired: _kill_process_tree(process) process.communicate() raise except BaseException: _kill_process_tree(process) process.wait() raise if check and process.returncode: raise subprocess.CalledProcessError(process.returncode, list(args), stdout, stderr) return subprocess.CompletedProcess(list(args), process.returncode, stdout, stderr)