162 lines
9.0 KiB
Python
162 lines
9.0 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",
|
|
]
|
|
|
|
|
|
# The key, under `branch.<a chunk's branch>` in a checkout's git config, that names the epic's working branch the chunk merges into (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).
|
|
CHUNK_BASE = "chunk-base"
|
|
|
|
|
|
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 ref the branch checked out merges into, as last fetched, read in cwd, else in the current directory. That is the default branch's: `origin/<branch>` with that remote, else the local main or master. On a chunk's branch that merges into an epic's working branch (`chunk_base`), it is `origin/<that branch>`, so each tool that measures a chunk against its base reads the chunk's own commits and not the epic's. 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():
|
|
if base := chunk_base(cwd, guarded, run):
|
|
return f"origin/{base}"
|
|
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 chunk_base(cwd: str | None = None, guarded: bool = False, run: Git = git) -> str | None:
|
|
"""The epic's working branch that the branch checked out in cwd merges into, as `record_chunk_base` recorded it; None where none is recorded, as for every branch that merges into the default branch, and on a detached HEAD."""
|
|
branch = run("symbolic-ref", "--quiet", "--short", "HEAD", cwd=cwd, guarded=guarded)
|
|
if isinstance(branch, Failure):
|
|
return None
|
|
base = run("config", "--get", f"branch.{branch.strip()}.{CHUNK_BASE}", cwd=cwd, guarded=guarded)
|
|
return None if isinstance(base, Failure) else base.strip() or None
|
|
|
|
|
|
def record_chunk_base(branch: str, base: str, cwd: str | None = None, run: Git = git) -> Failure | None:
|
|
"""Records in the checkout's git config that the chunk's branch merges into base, an epic's working branch. The branch need not exist yet, and deleting it removes the record."""
|
|
recorded = run("config", f"branch.{branch}.{CHUNK_BASE}", base, cwd=cwd)
|
|
return recorded if isinstance(recorded, Failure) else None
|
|
|
|
|
|
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
|