Files
claude-config/bin/git_cli/git_repo.py
T

141 lines
7.4 KiB
Python

"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.
Every tool in bin/ starts git through `git` here."""
import functools
import os
import re
import subprocess
import typing
from failure import Failure
# A -c outranks the checkout's own config. Each transport gets its own line, since a config's protocol.<name>.allow outranks protocol.allow.
GUARD_SETTINGS = [
"core.fsmonitor=false",
"log.showSignature=false",
"protocol.allow=never",
"protocol.ext.allow=never",
"protocol.file.allow=never",
"protocol.git.allow=never",
"protocol.http.allow=never",
"protocol.https.allow=never",
"protocol.ssh.allow=never",
]
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict", env: typing.Mapping[str, str] | None = None) -> str | Failure:
"""What git printed, run in cwd, else in the current directory.
A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.
errors "replace" reads each byte that is not UTF-8 as U+FFFD instead of failing. It is for output, such as a diff, whose file text the caller skips.
env is the environment git runs in, else this process's.
guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program.
"""
command = " ".join(args)
guards = [option for setting in GUARD_SETTINGS for option in ("-c", setting)] if guarded else []
# GIT_NO_LAZY_FETCH needs git 2.44.
child_env = {**(os.environ if env is None else env), "GIT_NO_LAZY_FETCH": "1"} if guarded else env
try:
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", errors=errors, env=child_env, timeout=timeout)
except UnicodeDecodeError as failure:
return Failure(f"git {command} printed text that is not UTF-8: {failure}")
except (OSError, ValueError) as failure:
return Failure(f"git {command} could not start: {failure}")
except subprocess.TimeoutExpired:
return Failure(f"git {command}: stopped after {timeout} s")
return ran.stdout if ran.returncode == 0 else Failure(f"git {command}: {ran.stderr.strip()}")
class Git(typing.Protocol):
"""Runs git as `git` does: git itself, Effects.git, or a functools.partial of either that binds the checkout."""
def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure: ...
def top(run: Git = git) -> str | Failure:
found = run("rev-parse", "--show-toplevel")
return found if isinstance(found, Failure) else found.strip()
def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, str | None] | Failure:
"""The default branch's ref, as default_ref names it after a fetch where the checkout has an origin remote, and a note on why origin reads as last fetched. With stale_ok, a failed fetch reads origin as last fetched, and the note says so. A call to origin still running after timeout seconds fails."""
remotes = git("remote")
if isinstance(remotes, Failure):
return remotes
fetch = git("fetch", "--quiet", "origin", timeout=timeout) if "origin" in remotes.split() else ""
if isinstance(fetch, Failure) and not stale_ok:
return fetch
ref = default_ref(timeout=timeout)
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
return ref if isinstance(ref, Failure) else (ref, note)
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
remotes = run("remote", cwd=cwd, guarded=guarded)
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
if not isinstance(recorded, Failure):
return recorded.strip()
return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout, run)
for branch in ("main", "master"):
if not isinstance(run("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure):
return branch
return Failure("no origin remote, and no main or master branch to take as the default branch")
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
--first-parent leaves out the commits a merge brought in, such as those of a default branch newer than the one the checkout last fetched."""
titles = git("log", "--first-parent", "--format=%s", f"{default}..HEAD", cwd=cwd, timeout=timeout, guarded=guarded)
return titles if isinstance(titles, Failure) else titles.splitlines()
def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failure:
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
listed = run("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
if isinstance(listed, Failure):
return listed
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
return f"origin/{named.group(1)}"
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
def commits_since(tag: str | None, branch: str, cwd: str | None = None, run: Git = git) -> int | Failure:
"""How many commits branch holds after tag, or holds in all where tag is None; read in cwd, else in the current directory."""
count = run("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
return count if isinstance(count, Failure) else int(count)
def commit_exists(commit: str, cwd: str | None = None, run: Git = git) -> bool:
return not isinstance(run("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
def file_at(revision: str, path: str, cwd: str | None = None, run: Git = git) -> str | Failure:
"""A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
if not commit_exists(revision, cwd, run):
return ""
return text_at(revision, path, functools.partial(run, cwd=cwd))
def text_at(revision: str, path: str, run: Git) -> str | Failure:
"""A file's text at a commit, as run reads it; empty where the commit holds no such file. ls-tree reads path from the directory run runs in, and show from the checkout's top."""
listed = run("ls-tree", "--name-only", revision, "--", path)
if isinstance(listed, Failure):
return listed
return run("show", f"{revision}:{path}") if listed.strip() else ""
def full_history() -> Failure | None:
"""Why the checkout lacks the history a tool reads, None when it holds it all."""
shallow = git("rev-parse", "--is-shallow-repository")
if isinstance(shallow, Failure):
return shallow
return Failure("a shallow clone lacks the full history; run `git fetch --unshallow origin`") if shallow.strip() == "true" else None