Coverage for src/governed_harness/delivery/vcs.py: 88%
128 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
1"""Git plumbing for delivery: read trees and blobs, recompute a ChangeSet digest between two
2revisions, and write a commit without touching the working tree.
4Every command runs without a shell, with ``GIT_TERMINAL_PROMPT=0`` and the repository's own
5configuration (including commit signing)."""
7from __future__ import annotations
9import os
10import re
11import subprocess # nosec B404 - git with a fixed argv, no shell
12from collections.abc import Mapping, Sequence
13from dataclasses import dataclass, field
14from pathlib import Path
16from governed_harness.domain.errors import HarnessError
17from governed_harness.evidence.hashing import sha256_bytes
18from governed_harness.runtime.workspace import (
19 FileState,
20 WorkspaceDiff,
21 WorkspaceSnapshot,
22 WorkspaceSnapshotter,
23 decode_text,
24)
26FALLBACK_IDENTITY = ("Governed Agent Harness", "harness@localhost.invalid")
27"""Author and committer of a harness commit in a repository without a Git identity."""
29_TIMEOUT_SECONDS = 120
30_REGULAR_MODES = frozenset({"100644", "100755"})
33class VcsError(HarnessError):
34 """A Git operation of delivery failed."""
37@dataclass(frozen=True)
38class RevisionDiff:
39 """The ChangeSet a range of commits amounts to, computed like the harness computes it."""
41 base: str
42 head: str
43 diff: WorkspaceDiff
44 special: tuple[str, ...] = ()
45 """Entries a ChangeSet cannot hold: mode-only changes, symbolic links, submodules."""
47 @property
48 def digest(self) -> str:
49 return self.diff.digest
51 @property
52 def paths(self) -> tuple[str, ...]:
53 return tuple(change.path for change in self.diff.changes)
56@dataclass
57class Git:
58 root: Path
59 env: dict[str, str] = field(default_factory=dict)
61 def run(
62 self,
63 *args: str,
64 stdin: bytes | None = None,
65 env: Mapping[str, str] | None = None,
66 check: bool = True,
67 ) -> subprocess.CompletedProcess[bytes]:
68 environment = {**os.environ, "GIT_TERMINAL_PROMPT": "0", **self.env, **(env or {})}
69 try:
70 result = subprocess.run( # nosec B603 B607 - git from PATH, argv built by the harness, no shell
71 ["git", *args],
72 cwd=self.root,
73 input=stdin,
74 stdin=None if stdin is not None else subprocess.DEVNULL,
75 capture_output=True,
76 check=False,
77 timeout=_TIMEOUT_SECONDS,
78 env=environment,
79 )
80 except (OSError, subprocess.SubprocessError) as error:
81 raise VcsError(f"git {args[0]} could not run: {error}") from error
82 if check and result.returncode != 0:
83 message = result.stderr.decode("utf-8", "replace").strip() or "no message"
84 raise VcsError(f"git {args[0]} failed ({result.returncode}): {message}")
85 return result
87 def text(
88 self, *args: str, stdin: bytes | None = None, env: Mapping[str, str] | None = None
89 ) -> str:
90 return self.run(*args, stdin=stdin, env=env).stdout.decode("utf-8", "replace").strip()
92 def is_repository(self) -> bool:
93 return self.run("rev-parse", "--is-inside-work-tree", check=False).returncode == 0
95 def resolve(self, revision: str) -> str | None:
96 result = self.run("rev-parse", "--verify", "--quiet", f"{revision}^{{commit}}", check=False)
97 value = result.stdout.decode("utf-8", "replace").strip()
98 return value if result.returncode == 0 and value else None
100 def blob(self, revision: str, path: str) -> bytes | None:
101 result = self.run("cat-file", "blob", f"{revision}:{path}", check=False)
102 return result.stdout if result.returncode == 0 else None
104 def identity_env(self) -> dict[str, str]:
105 """Author and committer variables when the repository resolves no ``user.name`` or
106 ``user.email``; empty otherwise (Git's own identity is used)."""
107 name = self.run("config", "--get", "user.name", check=False).stdout.strip()
108 email = self.run("config", "--get", "user.email", check=False).stdout.strip()
109 if name and email:
110 return {}
111 fallback_name, fallback_email = FALLBACK_IDENTITY
112 return {
113 "GIT_AUTHOR_NAME": fallback_name,
114 "GIT_AUTHOR_EMAIL": fallback_email,
115 "GIT_COMMITTER_NAME": fallback_name,
116 "GIT_COMMITTER_EMAIL": fallback_email,
117 }
119 def trailers(self, base: str, head: str) -> list[dict[str, str]]:
120 """The ``Harness-*`` trailers of every commit in ``base..head``."""
121 output = self.run(
122 "log",
123 "--format=%H%x00%(trailers:only,unfold)%x1e",
124 f"{base}..{head}",
125 ).stdout.decode("utf-8", "replace")
126 found: list[dict[str, str]] = []
127 for record in output.split("\x1e"):
128 record = record.strip("\n")
129 if not record:
130 continue
131 commit, _, block = record.partition("\x00")
132 values = {"commit": commit.strip()}
133 for line in block.splitlines():
134 key, separator, value = line.partition(":")
135 if separator and key.strip().startswith("Harness-"): 135 ↛ 133line 135 didn't jump to line 133 because the condition on line 135 was always true
136 values[key.strip()] = value.strip()
137 if len(values) > 1:
138 found.append(values)
139 return found
142_GITHUB_REMOTE = re.compile(
143 r"(?:git@github\.com:|https://(?:[^@/]+@)?github\.com/|ssh://git@github\.com/)"
144 r"(?P<owner>[A-Za-z0-9_.-]+)/(?P<name>[A-Za-z0-9_.-]+?)(?:\.git)?/?$"
145)
148def repository_from_remote(root: Path, remote: str = "origin") -> str | None:
149 """``owner/name`` of a GitHub remote, or ``None``."""
150 git = Git(root)
151 if not git.is_repository(): 151 ↛ 152line 151 didn't jump to line 152 because the condition on line 151 was never true
152 return None
153 url = git.run("remote", "get-url", remote, check=False).stdout.decode().strip()
154 match = _GITHUB_REMOTE.match(url)
155 return f"{match.group('owner')}/{match.group('name')}" if match else None
158def _entries(
159 git: Git, base: str, head: str, paths: Sequence[str]
160) -> list[tuple[str, str, str, str, str, str]]:
161 """``git diff --raw`` entries: (src mode, dst mode, src blob, dst blob, status, path)."""
162 args = ["diff", "--raw", "-z", "--no-renames", "--no-ext-diff", "--no-textconv", base, head]
163 if paths: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true
164 args += ["--", *paths]
165 data = git.run(*args).stdout.decode("utf-8", "surrogateescape")
166 parts = data.split("\x00")
167 entries = []
168 index = 0
169 while index < len(parts) - 1:
170 header = parts[index]
171 if not header.startswith(":"): 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true
172 index += 1
173 continue
174 src_mode, dst_mode, src_blob, dst_blob, status = header[1:].split(" ")[:5]
175 entries.append((src_mode, dst_mode, src_blob, dst_blob, status[:1], parts[index + 1]))
176 index += 2
177 return entries
180def revision_diff(
181 root: Path,
182 base: str,
183 head: str,
184 *,
185 paths: Sequence[str] = (),
186 env: Mapping[str, str] | None = None,
187) -> RevisionDiff:
188 """The ChangeSet diff (and digest) from ``base`` to ``head``: the same computation the
189 harness applies to the workspace, fed with the blobs of the two revisions."""
190 git = Git(root, dict(env or {}))
191 base_commit = git.resolve(base)
192 head_commit = git.resolve(head)
193 if base_commit is None: 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true
194 raise VcsError(f"unknown revision: {base}")
195 if head_commit is None: 195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true
196 raise VcsError(f"unknown revision: {head}")
197 before: dict[str, FileState] = {}
198 after: dict[str, FileState] = {}
199 special: list[str] = []
200 for src_mode, dst_mode, _src, _dst, status, path in _entries(
201 git, base_commit, head_commit, paths
202 ):
203 modes = {mode for mode in (src_mode, dst_mode) if mode != "000000"}
204 if not modes <= _REGULAR_MODES: 204 ↛ 205line 204 didn't jump to line 205 because the condition on line 204 was never true
205 special.append(f"{path} (mode {src_mode} -> {dst_mode})")
206 continue
207 if status == "M" and src_mode != dst_mode: 207 ↛ 208line 207 didn't jump to line 208 because the condition on line 207 was never true
208 special.append(f"{path} (mode {src_mode} -> {dst_mode})")
209 if src_mode != "000000":
210 data = git.blob(base_commit, path) or b""
211 before[path] = FileState(path, sha256_bytes(data), len(data), decode_text(data))
212 if dst_mode != "000000": 212 ↛ 200line 212 didn't jump to line 200 because the condition on line 212 was always true
213 data = git.blob(head_commit, path) or b""
214 after[path] = FileState(path, sha256_bytes(data), len(data), decode_text(data))
215 snapshotter = WorkspaceSnapshotter(root)
216 diff = snapshotter.diff(WorkspaceSnapshot(before, ""), WorkspaceSnapshot(after, ""))
217 return RevisionDiff(base_commit, head_commit, diff, tuple(special))