95 lines
4.0 KiB
Python
95 lines
4.0 KiB
Python
import re
|
|
import subprocess
|
|
|
|
from failure import Failure
|
|
from comprehension_history import HISTORY, HistoryChange
|
|
|
|
|
|
def git(*args: str) -> str | Failure:
|
|
try:
|
|
ran = subprocess.run(["git", *args], capture_output=True, text=True)
|
|
except (OSError, ValueError) as failure:
|
|
return Failure(f"git could not start: {failure}")
|
|
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
|
|
|
|
|
def top() -> str | Failure:
|
|
found = git("rev-parse", "--show-toplevel")
|
|
return found if isinstance(found, Failure) else found.strip()
|
|
|
|
|
|
def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure:
|
|
"""The default branch's ref, `origin/<branch>` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so."""
|
|
remotes = git("remote")
|
|
if isinstance(remotes, Failure):
|
|
return remotes
|
|
if "origin" in remotes.split():
|
|
fetch = git("fetch", "--quiet", "origin")
|
|
if isinstance(fetch, Failure) and not stale_ok:
|
|
return fetch
|
|
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
|
|
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
|
|
named = default.strip() if not isinstance(default, Failure) else origin_head()
|
|
return named if isinstance(named, Failure) else (named, note)
|
|
for branch in ("main", "master"):
|
|
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
|
|
return branch, None
|
|
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
|
|
|
|
|
def origin_head() -> str | Failure:
|
|
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
|
|
listed = git("ls-remote", "--symref", "origin", "HEAD")
|
|
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 commit_exists(commit: str) -> bool:
|
|
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure)
|
|
|
|
|
|
def file_at(revision: str, path: str) -> str | Failure:
|
|
"""A file's text at a revision, 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):
|
|
return ""
|
|
listed = git("ls-tree", "--name-only", revision, "--", path)
|
|
if isinstance(listed, Failure):
|
|
return listed
|
|
return git("show", f"{revision}:{path}") if listed.strip() else ""
|
|
|
|
|
|
def history_changes(default: str) -> list[HistoryChange] | Failure:
|
|
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
|
|
shallow = git("rev-parse", "--is-shallow-repository")
|
|
if isinstance(shallow, Failure):
|
|
return shallow
|
|
if shallow.strip() == "true":
|
|
return Failure("a shallow clone lacks the commits the base search reads; run `git fetch --unshallow origin`")
|
|
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
|
|
if isinstance(commits, Failure):
|
|
return commits
|
|
changes = []
|
|
for commit in commits.split():
|
|
before = file_at(f"{commit}^1", HISTORY)
|
|
if isinstance(before, Failure):
|
|
return before
|
|
after = file_at(commit, HISTORY)
|
|
if isinstance(after, Failure):
|
|
return after
|
|
changes.append(HistoryChange(commit, before, after))
|
|
return changes
|
|
|
|
|
|
def landed_since_release(default: str) -> bool | Failure:
|
|
"""Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none."""
|
|
# Sorts v1.0.0-rc.1 below v1.0.0.
|
|
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname")
|
|
if isinstance(tags, Failure):
|
|
return tags
|
|
newest = tags.split()[:1]
|
|
count = git("rev-list", "--count", f"{newest[0]}..{default}" if newest else default)
|
|
return count if isinstance(count, Failure) else int(count) > 0
|