Files
jaredandClaude Opus 5.5 f39409e62c
tests / unittest (push) Successful in 19s
feat: reusable review workflow
Callers use Civilytics/docs-review/.gitea/workflows/review.yml@v1 with secrets: inherit.
Stage 1 on every pull request; for drafter: claude, a 180-second wait and then the sandboxed
drafter; closed pull requests close their docs PR; schedule and dispatch run the monthly
pass. Tested live against Gitea 28.3 (drafter none, a misspelled drafter, claude, close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:12:57 -05:00

152 lines
5.3 KiB
Python

"""Thin subprocess wrappers over git. No operation here can force-push."""
import os
import subprocess
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review.secrets import scrub_env
# Precedes every revision taken from data, so a value like --output=/x is a revision
# name (and fails) rather than an option.
EOO = "--end-of-options"
# Repository config cannot swap in an external diff program or colour the output.
DIFF_FLAGS = ("--no-ext-diff", "--no-color")
class GitError(RuntimeError):
"""A git command failed; the message carries its stderr."""
@dataclass(frozen=True)
class Commit:
sha: str
author_email: str
parents: int
subject: str
def run(args: list[str], cwd: Path, extra_env: Mapping[str, str] | None = None) -> str:
"""Run git with args in cwd and return stdout; raise GitError with stderr.
git sees the process environment minus every secret-named variable, plus extra_env
for this one call."""
env = {**scrub_env(os.environ), **(extra_env or {})}
proc = subprocess.run(
["git", *args], cwd=cwd, env=env, capture_output=True, text=True, check=False
)
if proc.returncode != 0:
raise GitError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
return proc.stdout
def checkout_new(branch: str, rev: str, cwd: Path) -> None:
"""Create or reset branch at rev and switch to it.
git before 2.43 reads a revision after --end-of-options in checkout as a pathspec
("Cannot update paths and switch to branch"), and node:22 ships 2.39. So an
option-like branch or rev is refused here instead, and the trailing -- keeps rev a
revision."""
for value in (branch, rev):
if not value or value.startswith("-"):
raise GitError(f"refusing to check out {value!r}")
run(["checkout", "-q", "-B", branch, rev, "--"], cwd)
def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
"""Merge rev into the current branch without opening an editor."""
name, email = author
run(["-c", f"user.name={name}", "-c", f"user.email={email}",
"-c", "commit.gpgsign=false", "merge", "--no-edit", EOO, rev], cwd)
def fetch(branch: str, cwd: Path) -> None:
"""Fetch one branch from origin into FETCH_HEAD; the branch can never read as an
option."""
run(["fetch", "-q", "origin", EOO, branch], cwd)
def merge_base(a: str, b: str, cwd: Path) -> str:
return run(["merge-base", EOO, a, b], cwd).strip()
def diff(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, EOO, a, b], cwd)
def name_status(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, "-M", "--name-status", EOO, a, b], cwd)
def numstat(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, "--numstat", EOO, a, b], cwd)
def changed_worktree_files(cwd: Path) -> list[str]:
"""Paths changed in the working tree, untracked included; renames give the new path."""
out = run(["status", "--porcelain", "-z", "--untracked-files=all"], cwd)
entries = out.split("\0")
paths: list[str] = []
i = 0
while i < len(entries):
entry = entries[i]
i += 1
if len(entry) < 4:
continue
status, path = entry[:2], entry[3:]
paths.append(path)
if "R" in status or "C" in status:
i += 1 # the next field is the original path
return paths
def commits(a: str, b: str, cwd: Path) -> list[Commit]:
"""Commits in a..b, oldest first."""
out = run(["log", "--reverse", "--format=%H%x1f%ae%x1f%P%x1f%s", EOO, f"{a}..{b}"], cwd)
result = []
for line in out.splitlines():
sha, email, parents, subject = line.split("\x1f", 3)
result.append(Commit(sha, email, len(parents.split()), subject))
return result
def ls_files(cwd: Path) -> list[str]:
return [p for p in run(["ls-files"], cwd).splitlines() if p]
def commit(paths: list[str], message: str, author: tuple[str, str], cwd: Path) -> None:
name, email = author
run(["add", "--", *paths], cwd)
run(
["-c", f"user.name={name}", "-c", f"user.email={email}",
"-c", "commit.gpgsign=false", "commit", "-m", message],
cwd,
)
def header_key(server: str | None) -> str:
"""The config key for the auth header: scoped to the Gitea server when it is known,
so the header is never sent to any other host."""
if server:
return f"http.{server.rstrip('/')}/.extraHeader"
return "http.extraHeader"
def push(branch: str, cwd: Path, token: str | None, server: str | None = None) -> None:
"""Push branch to origin under an explicit refspec, never forced.
The token travels as an extraHeader set through GIT_CONFIG_* variables on this call
only, so it never reaches argv or .git/config; with server (GITHUB_SERVER_URL) the
header is scoped to that URL. A branch starting with + or - could force the push or
read as an option, so it is refused."""
if not branch or branch.startswith(("+", "-")):
raise GitError(f"refusing to push branch {branch!r}")
extra = None
if token:
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": header_key(server),
"GIT_CONFIG_VALUE_0": f"Authorization: token {token}"}
ref = f"refs/heads/{branch}"
run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra)