import dataclasses import subprocess from failure import Failure from larv_review.rules import HistoryChange HISTORY = "docs/comprehension-history.md" @dataclasses.dataclass(frozen=True) class Repository: """The checkout the tool runs in: its top folder, and the default branch's ref after a fetch, `origin/` with a remote.""" top: str default: str 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 repository() -> Repository | Failure: top = git("rev-parse", "--show-toplevel") if isinstance(top, Failure): return top remotes = git("remote") if isinstance(remotes, Failure): return remotes if "origin" in remotes.split(): if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure): return fetched default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") if isinstance(default, Failure): return Failure(f"origin names no default branch; set it with `git remote set-head origin --auto`: {default.reason}") return Repository(top.strip(), default.strip()) for branch in ("main", "master"): if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): return Repository(top.strip(), branch) return Failure("no origin remote, and no main or master branch to take as the default branch") def file_at(revision: str, path: str) -> str | Failure: """A file's text at a revision, empty where the revision does not hold it.""" if isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}:{path}"), Failure): return "" return git("show", f"{revision}:{path}") 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.""" 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) after = file_at(commit, HISTORY) if isinstance(before, Failure): return before 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.""" tag = git("describe", "--tags", "--abbrev=0", "--match", "v*", default) count = git("rev-list", "--count", default if isinstance(tag, Failure) else f"{tag.strip()}..{default}") return count if isinstance(count, Failure) else int(count) > 0