From 433dd2d3dd3c0f4b7ddb0516097db1dc25694cf4 Mon Sep 17 00:00:00 2001 From: Zeglius <33781398+Zeglius@users.noreply.github.com> Date: Sun, 4 Aug 2024 17:09:32 +0200 Subject: [PATCH] docs: add git lib to mdbook toolset --- docs/preprocessors/libs/__init__.py | 1 + docs/preprocessors/libs/git.py | 41 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 docs/preprocessors/libs/__init__.py create mode 100644 docs/preprocessors/libs/git.py diff --git a/docs/preprocessors/libs/__init__.py b/docs/preprocessors/libs/__init__.py new file mode 100644 index 00000000..8f54386d --- /dev/null +++ b/docs/preprocessors/libs/__init__.py @@ -0,0 +1 @@ +__all__ = ["git"] diff --git a/docs/preprocessors/libs/git.py b/docs/preprocessors/libs/git.py new file mode 100644 index 00000000..2ff476eb --- /dev/null +++ b/docs/preprocessors/libs/git.py @@ -0,0 +1,41 @@ +from collections import namedtuple +import os +from pathlib import Path, PurePath +import shlex +import subprocess + + +class Git: + """Use git commands in mdbook preprocessors""" + + def __init__(self, cwd: PurePath | str) -> None: + self._cwd = Path(cwd) + self._environ = os.environ.copy() + self._environ["LC_ALL"] = "C" + + class CommandOutput(namedtuple("CommandOutput", ["stdout", "stderr"])): + def __str__(self) -> str: + return self.stdout + + def _git(self, commands: list[str] | str) -> CommandOutput: + """Run a git command + + Args: + commands (list[str] | str): commands and args passed to git. + + Returns: + CommandOutput: Tuple containing `stdout` and `stderr` + """ + if type(commands) is str: + commands = shlex.split(commands) + proc = subprocess.run( + ["git", *commands], + capture_output=True, + text=True, + env=self._environ, + cwd=self._cwd, + ) + return self.CommandOutput(stdout=proc.stdout, stderr=proc.stderr) + + def log(self, *args: str) -> CommandOutput: + return self._git(["log", *args])