From 8086f09bde5d7d6c564dcc3f1cd63867101691c7 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:00:12 -0700 Subject: [PATCH] CI for high PR volume: Ubuntu content gate first, Windows build only for code changes; merge_ready.py; PR template --- .github/pull_request_template.md | 16 ++++ .github/workflows/ci.yml | 41 ++++++++++- .gitignore | 1 + scripts/check_content.py | 122 +++++++++++++++++++++++++++++++ scripts/merge_ready.py | 108 +++++++++++++++++++++++++++ 5 files changed, 287 insertions(+), 1 deletion(-) create mode 100644 .github/pull_request_template.md create mode 100644 scripts/check_content.py create mode 100644 scripts/merge_ready.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..518fd9e --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,16 @@ +## What this changes + + + +## How it was tested + +- [ ] `scripts/test.ps1` passes locally +- GPU and driver: +- Title run, if any: + +## Checklist + +- [ ] No game material: no executables, archives, shaders in any form, assets, or logs quoting them +- [ ] No keys, decryption or DRM workarounds +- [ ] Nothing in the code goes online +- [ ] AI-assisted: yes / no diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb..ee1058a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,23 +8,62 @@ # The runner has no System32\xgameruntime.dll (Gaming Services) and only the Microsoft Basic # Render Driver (4-lane waves): the launcher warns about both, which that test treats as a # failure. It still runs in `scripts/test.ps1` on a PC. +# +# Bathyal: a content gate runs first on Ubuntu (seconds). It refuses game material, binaries, files over 1 MiB, +# title names and network crates (scripts/check_content.py), and decides whether the change touches code. The +# Windows build only runs when the gate passes and the change is more than docs, so a docs-only pull request +# costs no Windows runner time. Both jobs report a status, so either can be a required check. name: CI on: push: branches: [main] pull_request: + merge_group: permissions: contents: read concurrency: - group: ci-${{ github.ref }} + group: ci-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: + gate: + name: Content gate + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + code: ${{ steps.scope.outputs.code }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Content check + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + python3 -I scripts/check_content.py --base "origin/${{ github.base_ref }}" + else + python3 -I scripts/check_content.py + fi + + - name: Does the change touch code? + id: scope + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then echo "code=true" >> "$GITHUB_OUTPUT"; exit 0; fi + files=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD") + if echo "$files" | grep -q -v -E '\.md$|^docs/|^\.github/ISSUE_TEMPLATE/|^\.github/pull_request_template\.md$|^LICENSE$'; then + echo "code=true" >> "$GITHUB_OUTPUT" + else + echo "code=false" >> "$GITHUB_OUTPUT" + fi + echo "changed files: $(echo "$files" | wc -l)" + windows: name: Build and test (Windows, no GPU) + needs: gate + if: needs.gate.outputs.code == 'true' runs-on: windows-2025 timeout-minutes: 45 env: diff --git a/.gitignore b/.gitignore index ea8c4bf..3b18855 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +merge_ready.log diff --git a/scripts/check_content.py b/scripts/check_content.py new file mode 100644 index 0000000..171fd91 --- /dev/null +++ b/scripts/check_content.py @@ -0,0 +1,122 @@ +"""Content gate for pull requests: fails when a change adds what this repository must never hold. + +Run by CI on the files a pull request changes (python -I scripts/check_content.py --base origin/main), or by hand +on the whole tree (no --base). Standard library only. Exit 0 = clean, 1 = findings (one line each), 2 = usage. + +Checks, on added or modified files only: + - binaries: Windows PE (MZ ... PE), ELF, and archive/media containers by magic, wherever they are named; + - file types that are game material here: .exe .dll .rpf .xvd .bk2 .awc .dxbc .dxil .spv .ytd .ydr .pak ...; + - any file over 1 MiB, outside the allow list below; + - commercial title names in text (the project writes "a newer retail title"); + - new HTTP/TLS/telemetry crates in Cargo.lock (the code must not go online). +""" +import argparse +import os +import re +import subprocess +import sys + +MAX_BYTES = 1 << 20 +# Synthetic fixtures that are allowed to be binary (tests build them by hand). Paths relative to the root. +ALLOWED_BINARY_PREFIXES = ("tests/data/testgame/",) +BANNED_EXTENSIONS = { + ".exe", ".dll", ".sys", ".rpf", ".xvd", ".xvc", ".msixvc", ".appx", ".bk2", ".bik", ".awc", ".xma", ".dxbc", + ".dxil", ".spv", ".cso", ".ytd", ".ydr", ".ydd", ".yft", ".ybn", ".ymap", ".ytyp", ".pak", ".pdb", +} +MAGIC = [ + (b"MZ", "Windows executable (MZ)"), + (b"\x7fELF", "ELF executable"), + (b"RPF", "RPF archive"), + (b"DXBC", "DXBC shader container"), + (b"\x03\x02\x23\x07", "SPIR-V module"), + (b"BIK", "Bink video"), + (b"KB2", "Bink 2 video"), + (b"PK\x03\x04", "ZIP archive"), + (b"7z\xbc\xaf\x27\x1c", "7-Zip archive"), + (b"Rar!", "RAR archive"), +] +TITLE_NAMES = re.compile( + r"grand\s+theft\s+auto|\bgta\s*(?:v|vi|5|6|online)\b|rockstar\s+games|\bcyberleek\b|game_scarlett_master", + re.IGNORECASE) +NETWORK_CRATES = { + "reqwest", "ureq", "hyper", "curl", "curl-sys", "isahc", "attohttpc", "surf", "native-tls", "rustls", + "openssl", "openssl-sys", "tungstenite", "tokio-tungstenite", "sentry", "opentelemetry", "h2", "quinn", +} +TEXT_EXTENSIONS = {".rs", ".md", ".toml", ".py", ".ps1", ".yml", ".yaml", ".txt", ".json", ".hlsl", ".cfg", ".bat", + ".cmd", ".sh", ".lock"} +SELF = "scripts/check_content.py" + + +def git(*args: str) -> str: + return subprocess.run(["git", *args], check=True, capture_output=True, text=True).stdout + + +def changed_files(base: str) -> list[str]: + out = git("diff", "--name-only", "--diff-filter=AMR", "-z", f"{base}...HEAD") + return [p for p in out.split("\0") if p] + + +def all_files() -> list[str]: + return [p for p in git("ls-files", "-z").split("\0") if p] + + +def crates(lock_text: str) -> set[str]: + return set(re.findall(r'^name = "([^"]+)"', lock_text, re.MULTILINE)) + + +def check_file(path: str) -> list[str]: + findings = [] + if not os.path.isfile(path): + return findings + rel = path.replace("\\", "/") + allowed_binary = rel.startswith(ALLOWED_BINARY_PREFIXES) + ext = os.path.splitext(rel)[1].lower() + size = os.path.getsize(path) + if ext in BANNED_EXTENSIONS and not allowed_binary: + findings.append(f"{rel}: file type {ext} is not allowed in this repository") + if size > MAX_BYTES and not allowed_binary: + findings.append(f"{rel}: {size} bytes, over the {MAX_BYTES}-byte limit") + with open(path, "rb") as f: + head = f.read(4096) + if not allowed_binary: + for magic, what in MAGIC: + if head.startswith(magic): + if magic == b"MZ" and b"PE\0\0" not in head: + continue + findings.append(f"{rel}: looks like a {what}") + break + if ext in TEXT_EXTENSIONS and rel != SELF and size <= 4 * MAX_BYTES: + with open(path, encoding="utf-8", errors="replace") as f: + for number, line in enumerate(f, 1): + m = TITLE_NAMES.search(line) + if m: + findings.append(f"{rel}:{number}: names a commercial title ({m.group(0)!r}); " + "write \"a newer retail title\"") + return findings + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--base", help="compare against this ref (merge base); without it the whole tree is checked") + a = ap.parse_args() + files = changed_files(a.base) if a.base else all_files() + findings = [] + for path in files: + findings.extend(check_file(path)) + if a.base and "Cargo.lock" in files: + try: + before = crates(git("show", f"{a.base}:Cargo.lock")) + except subprocess.CalledProcessError: + before = set() + with open("Cargo.lock", encoding="utf-8") as f: + added = crates(f.read()) - before + for name in sorted(added & NETWORK_CRATES): + findings.append(f"Cargo.lock: adds network crate {name!r}; the code must not go online") + for line in findings: + print(line) + print(f"check_content: {len(files)} files checked, {len(findings)} findings") + return 1 if findings else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/merge_ready.py b/scripts/merge_ready.py new file mode 100644 index 0000000..f56aa61 --- /dev/null +++ b/scripts/merge_ready.py @@ -0,0 +1,108 @@ +"""Lists and merges pull requests that are ready: open, not draft, mergeable, every check passed or skipped, +no review asking for changes. Needs the GitHub CLI (gh) logged in with write access. Standard library only. + + python -I scripts/merge_ready.py # dry run: the ready list and why the rest wait + python -I scripts/merge_ready.py --merge 50 # squash-merge up to 50 ready PRs, oldest first + python -I scripts/merge_ready.py --merge 50 --approved # only PRs with an approving review + +A PR whose merge fails (a conflict that appeared after an earlier merge) is skipped and reported; the run goes on. +Every decision goes to merge_ready.log (append) as one line: time, PR, action, reason. +""" +import argparse +import datetime +import json +import subprocess +import sys +import time + +OK_STATES = {"SUCCESS", "SKIPPED", "NEUTRAL"} +FIELDS = "number,title,author,isDraft,mergeable,reviewDecision,statusCheckRollup,baseRefName,createdAt,labels" + + +def gh(*args: str) -> str: + return subprocess.run(["gh", *args], check=True, capture_output=True, text=True).stdout + + +def check_state(pr: dict) -> tuple[bool, str]: + checks = pr.get("statusCheckRollup") or [] + if not checks: + return False, "no checks yet" + for c in checks: + state = (c.get("conclusion") or c.get("state") or c.get("status") or "").upper() + name = c.get("name") or c.get("context") or "?" + if state in ("", "PENDING", "QUEUED", "IN_PROGRESS", "EXPECTED", "WAITING", "ACTION_REQUIRED"): + return False, f"check {name} {state.lower() or 'pending'}" + if state not in OK_STATES: + return False, f"check {name} {state.lower()}" + return True, "checks green" + + +def readiness(pr: dict, base: str, approved_only: bool) -> tuple[bool, str]: + if pr["baseRefName"] != base: + return False, f"targets {pr['baseRefName']}" + if pr["isDraft"]: + return False, "draft" + if any(l["name"] in ("do-not-merge", "blocked") for l in pr.get("labels") or []): + return False, "labelled do-not-merge" + if pr["mergeable"] != "MERGEABLE": + return False, f"mergeable={pr['mergeable'].lower()}" + if pr["reviewDecision"] == "CHANGES_REQUESTED": + return False, "changes requested" + if approved_only and pr["reviewDecision"] != "APPROVED": + return False, "not approved" + return check_state(pr) + + +def log(line: str) -> None: + stamp = datetime.datetime.now().isoformat(timespec="seconds") + with open("merge_ready.log", "a", encoding="utf-8") as f: + f.write(f"{stamp} {line}\n") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--repo", default="T-Crypt/bathyal") + ap.add_argument("--base", default="main") + ap.add_argument("--merge", type=int, default=0, metavar="N", help="merge up to N ready PRs (default: dry run)") + ap.add_argument("--approved", action="store_true", help="only PRs with an approving review") + ap.add_argument("--limit", type=int, default=2000, help="open PRs to read") + ap.add_argument("--pause", type=float, default=2.0, help="seconds between merges (API rate)") + a = ap.parse_args() + + prs = json.loads(gh("pr", "list", "-R", a.repo, "--state", "open", "--limit", str(a.limit), "--json", FIELDS)) + prs.sort(key=lambda p: p["createdAt"]) + ready, waiting = [], {} + for pr in prs: + ok, why = readiness(pr, a.base, a.approved) + if ok: + ready.append(pr) + else: + waiting.setdefault(why.split(" ")[0] if why.startswith("check") else why, []).append(pr["number"]) + print(f"{len(prs)} open, {len(ready)} ready") + for why, nums in sorted(waiting.items(), key=lambda kv: -len(kv[1])): + print(f" waiting ({why}): {len(nums)} e.g. #{', #'.join(map(str, nums[:5]))}") + if not a.merge: + for pr in ready[:20]: + print(f" ready #{pr['number']} {pr['author']['login']}: {pr['title'][:80]}") + return 0 + + merged, failed = 0, 0 + for pr in ready[: a.merge]: + n = str(pr["number"]) + try: + gh("pr", "merge", n, "-R", a.repo, "--squash") + merged += 1 + log(f"#{n} merged ({pr['author']['login']}: {pr['title'][:80]})") + print(f"merged #{n}") + except subprocess.CalledProcessError as e: + failed += 1 + reason = (e.stderr or "").strip().splitlines()[-1:] or ["unknown"] + log(f"#{n} skipped: {reason[0][:160]}") + print(f"skipped #{n}: {reason[0][:160]}") + time.sleep(a.pause) + print(f"merged {merged}, skipped {failed}") + return 0 + + +if __name__ == "__main__": + sys.exit(main())