Coverage for src/governed_harness/runtime/git_adapter.py: 87%
35 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1from __future__ import annotations
3import subprocess # nosec B404 - git with a fixed argv, no shell
4from dataclasses import dataclass
5from pathlib import Path
8@dataclass(frozen=True)
9class GitState:
10 is_repository: bool
11 head: str | None
12 branch: str | None
13 dirty: bool
14 status: tuple[str, ...]
17class GitAdapter:
18 def __init__(self, workspace: Path) -> None:
19 self.workspace = workspace.resolve(strict=True)
21 def state(self) -> GitState:
22 if self._run("rev-parse", "--is-inside-work-tree").returncode != 0: 22 ↛ 23line 22 didn't jump to line 23 because the condition on line 22 was never true
23 return GitState(False, None, None, False, ())
24 head_result = self._run("rev-parse", "HEAD")
25 branch_result = self._run("branch", "--show-current")
26 status_result = self._run("status", "--porcelain=v1", "--untracked-files=all")
27 lines = tuple(
28 line for line in status_result.stdout.decode("utf-8", "replace").splitlines() if line
29 )
30 return GitState(
31 True,
32 head_result.stdout.decode().strip() if head_result.returncode == 0 else None,
33 branch_result.stdout.decode().strip() or None,
34 bool(lines),
35 lines,
36 )
38 def user_identity(self) -> tuple[str | None, str | None]:
39 """The ``user.name`` and ``user.email`` Git resolves for the workspace (repository,
40 global and system configuration), ``None`` for each one that is not set."""
41 values: list[str | None] = []
42 for key in ("user.name", "user.email"):
43 try:
44 result = self._run("config", "--get", key)
45 except (OSError, subprocess.SubprocessError):
46 values.append(None)
47 continue
48 text = result.stdout.decode("utf-8", "replace").strip()
49 values.append(text if result.returncode == 0 and text else None)
50 return values[0], values[1]
52 def _run(self, *args: str) -> subprocess.CompletedProcess[bytes]:
53 return subprocess.run( # nosec B603 B607 - git from PATH, argv built here, no shell
54 ["git", *args],
55 cwd=self.workspace,
56 stdin=subprocess.DEVNULL,
57 capture_output=True,
58 check=False,
59 timeout=30,
60 )