# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The one place in this repository that starts a subprocess. Deliberately one place. Ruff's ``ALL`` set flags every ``subprocess`` call with ``S603`` ("check for execution of untrusted input") and there is no code-level answer to it: exiftool is a binary, and the pure-Python EXIF libraries handle neither HEIC nor MP4, which is most of what the album ingests. So the rule is suppressed exactly once, for this file, in ``pyproject.toml`` -- a scoped and reviewable entry rather than an inline per-line suppression, which this repository's own pre-commit hook blocks outright, and which would be free to spread file by file. Everything that needs an external tool imports ``run`` from here. If a second file ever calls ``subprocess`` directly, the gate fails and says so, which is the property the single entry buys. ``run`` never raises and never lets a caller mistake failure for success: a non-zero exit, a missing binary and a timeout all come back as ``ok=False``, because the one thing this must not do is look like it worked. An exit code that lied is what put ffmpeg in this codebase's history. """ from __future__ import annotations import logging import subprocess from dataclasses import dataclass from typing import TYPE_CHECKING, Final if TYPE_CHECKING: from collections.abc import Sequence logger = logging.getLogger(__name__) # Long enough for exiftool to rewrite a phone video's container, short enough # that a wedged binary cannot hold a command handler open indefinitely. DEFAULT_TIMEOUT: Final = 60.0 @dataclass(frozen=True, slots=True) class Result: """What one external command did, with failure spelled out rather than raised.""" ok: bool stdout: str stderr: str def run(command: Sequence[str], *, timeout: float = DEFAULT_TIMEOUT) -> Result: """Run one external command and report what happened. Args: command: The argv, already split. Never a shell string: nothing here interpolates into a shell, and every element is built by the caller rather than taken from a message. timeout: Seconds before the command is killed and reported failed. Returns: The command's output, and whether it actually succeeded. """ try: completed = subprocess.run( list(command), capture_output=True, text=True, timeout=timeout, check=False, ) except (OSError, subprocess.SubprocessError) as error: # A missing binary, a permissions problem, or a timeout. The command # is logged, never its output: exiftool prints tag values on failure. logger.warning("could not run %s: %s", command[0], error) return Result(ok=False, stdout="", stderr=str(error)) if completed.returncode != 0: logger.warning( "%s exited %d: %s", command[0], completed.returncode, completed.stderr.strip() ) return Result(ok=False, stdout=completed.stdout, stderr=completed.stderr) return Result(ok=True, stdout=completed.stdout, stderr=completed.stderr)