from __future__ import annotations import os import subprocess import tempfile import unittest from unittest.mock import patch AUTHOR = { "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.org", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.org", } def git(cwd: str, *args: str) -> str: """ Args: cwd: the repository to run in. args: the git arguments; signing stays off and AUTHOR applies. Returns: The stripped standard output. """ return subprocess.run( ["git", "-c", "commit.gpgsign=false", *args], cwd=cwd, env={**os.environ, **AUTHOR}, check=True, capture_output=True, text=True, ).stdout.strip() def isolated_root(case: unittest.TestCase, env: dict[str, str]) -> str: """ Args: case: the test whose cleanups remove the directory and restore the working directory and environment. env: variables set over the environment, from which every GIT_* variable is dropped. Returns: The realpath of a fresh temporary directory, now the working directory, whose empty `home` child is HOME. """ scratch = tempfile.TemporaryDirectory() case.addCleanup(scratch.cleanup) root = os.path.realpath(scratch.name) case.addCleanup(os.chdir, os.getcwd()) os.chdir(root) home = os.path.join(root, "home") os.makedirs(home) kept = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} environ = patch.dict(os.environ, {**kept, **env, "HOME": home}, clear=True) environ.start() case.addCleanup(environ.stop) return root