|
| 1 | +""" |
| 2 | +Tells whether the AI review of a branch covers its last commit, from the record the review writes to |
| 3 | +local/reviews/<branch>.md (see README.md next to this file). |
| 4 | +
|
| 5 | + check.py say whether the review is missing or behind the branch; always exit 0 |
| 6 | + check.py --strict the same, but exit 1 unless the branch is reviewed up to its last commit |
| 7 | + check.py --refresh when a rebase left the reviewed changes as they were under new commits, |
| 8 | + move the record's commit to them |
| 9 | +
|
| 10 | +As the pre-push hook it checks the branch being pushed and never blocks the push: unfinished branches |
| 11 | +are pushed to run CI. By hand it checks the branch checked out. |
| 12 | +
|
| 13 | +Only the standard library: it runs from pre-commit in a repository of any language. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import codecs |
| 20 | +import hashlib |
| 21 | +import os |
| 22 | +import re |
| 23 | +import shutil |
| 24 | +import subprocess |
| 25 | +import sys |
| 26 | +from dataclasses import dataclass |
| 27 | +from pathlib import Path |
| 28 | + |
| 29 | +RECORDS = Path("local", "reviews") |
| 30 | +COMMIT = re.compile(r"^commit:[ \t]*([0-9a-f]{7,64})[ \t]*(?=\r?$)", re.MULTILINE) |
| 31 | +# agents write the record in UTF-8; PowerShell 5.1 redirection writes UTF-16 |
| 32 | +BOMS = ((codecs.BOM_UTF16_LE, "utf-16"), (codecs.BOM_UTF16_BE, "utf-16"), (codecs.BOM_UTF8, "utf-8-sig")) |
| 33 | +# the diffs are read by this script, not a person: no colour, external diff or textconv a config may turn on |
| 34 | +PLAIN_DIFF = ("diff", "--no-color", "--no-ext-diff", "--no-textconv") |
| 35 | +HUNK_LINES = re.compile(rb"^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@") |
| 36 | +HOW = ( |
| 37 | + "run it in your agent (/review-change, $review-change; .agents/review/README.md)" |
| 38 | + " before opening or updating the pull request" |
| 39 | +) |
| 40 | + |
| 41 | +REVIEWED, BEHIND, SKIPPED = "reviewed", "behind", "skipped" |
| 42 | + |
| 43 | + |
| 44 | +@dataclass(frozen=True) |
| 45 | +class Branch: |
| 46 | + name: str |
| 47 | + head: str |
| 48 | + base: str | None |
| 49 | + top: Path |
| 50 | + |
| 51 | + |
| 52 | +@dataclass(frozen=True) |
| 53 | +class Record: |
| 54 | + path: Path |
| 55 | + text: str |
| 56 | + codec: str | None |
| 57 | + |
| 58 | + |
| 59 | +def main() -> int: |
| 60 | + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 61 | + parser.add_argument( |
| 62 | + "--strict", action="store_true", help="exit 1 unless the branch is reviewed up to its last commit" |
| 63 | + ) |
| 64 | + parser.add_argument( |
| 65 | + "--refresh", action="store_true", help="move the record's commit to the same changes under new commits" |
| 66 | + ) |
| 67 | + args = parser.parse_args() |
| 68 | + |
| 69 | + try: |
| 70 | + status, message = check(refresh=args.refresh) |
| 71 | + except Exception as error: # noqa: BLE001, RUF100 - the hook must never block a push, so a broken check only says so |
| 72 | + status, message = BEHIND, f"AI review: the check failed: {error!r}" |
| 73 | + if status == SKIPPED and not args.strict: |
| 74 | + return 0 |
| 75 | + sys.stdout.write(message + "\n") |
| 76 | + return 1 if args.strict and status != REVIEWED else 0 |
| 77 | + |
| 78 | + |
| 79 | +def check(*, refresh: bool) -> tuple[str, str]: |
| 80 | + branch, skipped = branch_to_check() |
| 81 | + if branch is None: |
| 82 | + return SKIPPED, skipped |
| 83 | + relative = RECORDS / f"{branch.name}.md" |
| 84 | + path = branch.top / relative |
| 85 | + if not path.is_file(): |
| 86 | + return BEHIND, f"AI review of {branch.name}: not run yet; {HOW}" |
| 87 | + record = Record(path, *read_record(path)) |
| 88 | + reviewed, missing = reviewed_commit(record.text, relative) |
| 89 | + if reviewed is None: |
| 90 | + return BEHIND, f"AI review of {branch.name}: {missing}; {HOW}" |
| 91 | + if reviewed == branch.head: |
| 92 | + return REVIEWED, f"AI review: {branch.name} is reviewed up to its last commit" |
| 93 | + if git("merge-base", "--is-ancestor", reviewed, branch.head) is not None: |
| 94 | + return since_review(branch, reviewed) |
| 95 | + return after_rewrite(branch, reviewed, record, refresh=refresh) |
| 96 | + |
| 97 | + |
| 98 | +def branch_to_check() -> tuple[Branch | None, str]: |
| 99 | + """The branch to check, or none and why it is skipped.""" |
| 100 | + top = git("rev-parse", "--show-toplevel") |
| 101 | + if top is None: |
| 102 | + return None, "AI review: not in a git work tree, or git is missing" |
| 103 | + name, head = pushed_branch() |
| 104 | + if name is None or head is None: |
| 105 | + return None, "AI review: no branch to check (detached HEAD)" |
| 106 | + base = base_ref() |
| 107 | + if name in default_names(base): |
| 108 | + return None, f"AI review: {name} is the default branch" |
| 109 | + return Branch(name, head, base, Path(top)), "" |
| 110 | + |
| 111 | + |
| 112 | +def reviewed_commit(text: str, relative: Path) -> tuple[str | None, str]: |
| 113 | + """The commit the record names, or none and what is wrong with the record.""" |
| 114 | + found = COMMIT.search(text) |
| 115 | + if found is None: |
| 116 | + return None, f"{relative.as_posix()} names no commit" |
| 117 | + reviewed = git("rev-parse", "--verify", "--quiet", f"{found.group(1)}^{{commit}}") |
| 118 | + if reviewed is None: |
| 119 | + return None, f"the reviewed commit {found.group(1)[:8]} is not in this clone" |
| 120 | + return reviewed, "" |
| 121 | + |
| 122 | + |
| 123 | +def since_review(branch: Branch, reviewed: str) -> tuple[str, str]: |
| 124 | + changed = branch_files_changed(reviewed, branch.head, branch.base) |
| 125 | + if not changed: |
| 126 | + return REVIEWED, f"AI review: {branch.name} is reviewed; nothing of its own changed since {reviewed[:8]}" |
| 127 | + return ( |
| 128 | + BEHIND, |
| 129 | + f"AI review of {branch.name}: {len(changed)} file(s) changed since the review at {reviewed[:8]}; {HOW}", |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | +def after_rewrite(branch: Branch, reviewed: str, record: Record, *, refresh: bool) -> tuple[str, str]: |
| 134 | + # a rebase keeps the reviewed changes under new commits: compare the changes, not the commits |
| 135 | + if branch.base is None or not same_changes(reviewed, branch.head, branch.base): |
| 136 | + return ( |
| 137 | + BEHIND, |
| 138 | + f"AI review of {branch.name}: rewritten since the review at {reviewed[:8]}, with other changes; {HOW}", |
| 139 | + ) |
| 140 | + if refresh and record.codec is not None: |
| 141 | + record.path.write_bytes(COMMIT.sub(f"commit: {branch.head}", record.text, count=1).encode(record.codec)) |
| 142 | + return ( |
| 143 | + REVIEWED, |
| 144 | + f"AI review: {branch.name} carries the reviewed changes; the record now names {branch.head[:8]}", |
| 145 | + ) |
| 146 | + return REVIEWED, f"AI review: {branch.name} carries the changes reviewed at {reviewed[:8]} under new commits" |
| 147 | + |
| 148 | + |
| 149 | +def pushed_branch() -> tuple[str | None, str | None]: |
| 150 | + local = os.environ.get("PRE_COMMIT_LOCAL_BRANCH") |
| 151 | + if local: |
| 152 | + # pre-commit's pre-push: the branch being pushed and its sha, which need not be the checked-out ones |
| 153 | + head = os.environ.get("PRE_COMMIT_TO_REF") or git("rev-parse", "--verify", "--quiet", local) |
| 154 | + if not local.startswith("refs/heads/"): |
| 155 | + # `git push origin HEAD` names no branch: it is the checked-out one when the shas agree |
| 156 | + if head is None or head != git("rev-parse", "--verify", "--quiet", "HEAD"): |
| 157 | + return None, None |
| 158 | + local = git("symbolic-ref", "--quiet", "HEAD") |
| 159 | + if not local: |
| 160 | + return None, None |
| 161 | + return local.removeprefix("refs/heads/"), head |
| 162 | + ref = git("symbolic-ref", "--quiet", "HEAD") |
| 163 | + if not ref: |
| 164 | + return None, None |
| 165 | + return ref.removeprefix("refs/heads/"), git("rev-parse", "--verify", "--quiet", ref) |
| 166 | + |
| 167 | + |
| 168 | +def base_ref() -> str | None: |
| 169 | + named = git("symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD") |
| 170 | + candidates = [named] if named else ["origin/master", "origin/main"] |
| 171 | + return next((ref for ref in candidates if git("rev-parse", "--verify", "--quiet", ref)), None) |
| 172 | + |
| 173 | + |
| 174 | +def default_names(base: str | None) -> set[str]: |
| 175 | + names = {"master", "main"} |
| 176 | + if base: |
| 177 | + names.add(base.split("/", 1)[-1]) |
| 178 | + return names |
| 179 | + |
| 180 | + |
| 181 | +def read_record(path: Path) -> tuple[str, str | None]: |
| 182 | + """The record's text and the codec to write it back with; no codec when it is not UTF-8 or UTF-16.""" |
| 183 | + raw = path.read_bytes() |
| 184 | + for bom, codec in BOMS: |
| 185 | + if raw.startswith(bom): |
| 186 | + return raw.decode(codec, errors="replace"), codec |
| 187 | + try: |
| 188 | + return raw.decode("utf-8"), "utf-8" |
| 189 | + except UnicodeDecodeError: |
| 190 | + return raw.decode("utf-8", errors="replace"), None |
| 191 | + |
| 192 | + |
| 193 | +def same_changes(reviewed: str, head: str, base: str) -> bool: |
| 194 | + before = changes_id(reviewed, base) |
| 195 | + return before is not None and before == changes_id(head, base) |
| 196 | + |
| 197 | + |
| 198 | +def changes_id(commit: str, base: str) -> str | None: |
| 199 | + fork = git("merge-base", base, commit) |
| 200 | + if fork is None: |
| 201 | + return None |
| 202 | + diff = run(*PLAIN_DIFF, fork, commit) |
| 203 | + if not diff: |
| 204 | + return None |
| 205 | + # on a new base the same changes differ only in blob ids and line numbers; whitespace and context |
| 206 | + # lines still count, so a re-indented or moved line is a change to review again |
| 207 | + lines = [HUNK_LINES.sub(b"@@", line) for line in diff.split(b"\n") if not line.startswith(b"index ")] |
| 208 | + return hashlib.sha256(b"\n".join(lines)).hexdigest() |
| 209 | + |
| 210 | + |
| 211 | +def branch_files_changed(reviewed: str, head: str, base: str | None) -> set[str]: |
| 212 | + changed = set((git(*PLAIN_DIFF, "--name-only", reviewed, head) or "").splitlines()) |
| 213 | + if base is None: |
| 214 | + return changed |
| 215 | + # a merge of the default branch brings other people's changes: only the branch's own files count |
| 216 | + own = set((git(*PLAIN_DIFF, "--name-only", f"{base}...{head}") or "").splitlines()) |
| 217 | + return changed & own |
| 218 | + |
| 219 | + |
| 220 | +def git(*args: str) -> str | None: |
| 221 | + output = run(*args) |
| 222 | + return None if output is None else output.decode("utf-8", errors="replace").strip() |
| 223 | + |
| 224 | + |
| 225 | +def run(*args: str) -> bytes | None: |
| 226 | + executable = shutil.which("git") |
| 227 | + if not executable: |
| 228 | + return None |
| 229 | + result = subprocess.run([executable, *args], capture_output=True, check=False) # noqa: S603 |
| 230 | + return result.stdout if result.returncode == 0 else None |
| 231 | + |
| 232 | + |
| 233 | +if __name__ == "__main__": |
| 234 | + sys.exit(main()) |
0 commit comments