baseball-engine / tools /colab_github.py
github-actions[bot]
Automated Deploy: a19ede424a80b7b8d7f6978585141d1bb45de69c
326d3cc
Raw History Blame Contribute Delete
4.75 kB
"""Readable GitHub bootstrap, copied into the first Colab code cell by the builder."""
from pathlib import Path
from contextlib import contextmanager
import base64
import json
import os
import re
import subprocess
import sys
def _git(directory, *arguments, auth_env=None):
environment = {**os.environ, "GIT_TERMINAL_PROMPT": "0", **(auth_env or {})}
result = subprocess.run(
["git", "-C", str(directory), *arguments], text=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,
)
if result.returncode:
detail = result.stderr.strip() or result.stdout.strip() or "Git returned no error detail"
secret = (auth_env or {}).get("BATTING_GITHUB_TOKEN")
if secret:
encoded = base64.b64encode(f"x-access-token:{secret}".encode()).decode()
detail = detail.replace(secret, "[REDACTED]").replace(encoded, "[REDACTED]")
detail = re.sub(r"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+", "[REDACTED]", detail)
raise RuntimeError(f"Git failed (exit {result.returncode}):\n{detail[-4000:]}") from None
return result.stdout.strip()
@contextmanager
def _github_credentials(token, scope="https://github.com/"):
if not token:
yield {}
return
# Git reads these settings only for this subprocess; no token is stored in its URL/config.
count = int(os.environ.get("GIT_CONFIG_COUNT", "0"))
encoded = base64.b64encode(f"x-access-token:{token}".encode()).decode()
yield {
"GIT_CONFIG_COUNT": str(count + 2),
f"GIT_CONFIG_KEY_{count}": f"http.{scope}.extraHeader",
f"GIT_CONFIG_VALUE_{count}": "",
f"GIT_CONFIG_KEY_{count + 1}": f"http.{scope}.extraHeader",
f"GIT_CONFIG_VALUE_{count + 1}": f"Authorization: Basic {encoded}",
"BATTING_GITHUB_TOKEN": token,
}
def checkout_github(repository_url, revision, workspace, token=None):
"""Fetch an explicit ref and stop before replacing modified source files."""
if token is not None:
token = token.strip()
if not token:
raise ValueError("Enter a token with read access to this repository")
if not re.fullmatch(r"https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\.git)?/?", repository_url):
raise ValueError("Use an HTTPS GitHub repository URL without credentials or query parameters")
if any(part in {".", ".."} for part in repository_url.split("/")[3:]):
raise ValueError("Use an owner/repository GitHub URL")
if not revision or revision.startswith("-") or any(c.isspace() for c in revision):
raise ValueError("Set a branch, tag, or full commit SHA")
workspace = Path(workspace).resolve()
source = workspace / "source"
workspace.mkdir(parents=True, exist_ok=True)
with _github_credentials(token) as authentication:
options = ("-c", "credential.helper=") if token else ()
fresh_checkout = False
if not (source / ".git").exists():
if source.exists() and any(source.iterdir()):
raise ValueError(f"Source directory is not an empty Git checkout: {source}")
_git(workspace, *options, "clone", "--no-checkout", "--depth=1", repository_url,
str(source), auth_env=authentication)
fresh_checkout = True
if _git(source, "config", "--get", "remote.origin.url") != repository_url:
raise ValueError("Existing checkout uses a different repository; choose another workspace")
# A newly cloned --no-checkout repository has no populated index yet.
if not fresh_checkout and _git(source, "status", "--porcelain", "--untracked-files=no"):
raise ValueError("Source has local edits; save them or choose another workspace before updating")
_git(source, *options, "fetch", "--depth=1", "origin", revision, auth_env=authentication)
commit = _git(source, "rev-parse", "FETCH_HEAD^{commit}")
if re.fullmatch(r"[0-9a-fA-F]{40}", revision) and commit.lower() != revision.lower():
raise ValueError("Fetched commit does not match the requested SHA")
_git(source, "checkout", "--quiet", "--detach", commit)
required = ["baseball_batting/cli.py", "requirements-core.txt", "configs/resources.yaml"]
if not all((source / name).is_file() for name in required):
raise ValueError("Selected repository revision does not contain the batting engine")
record = {"repository_url": repository_url, "requested_revision": revision, "commit_sha": commit}
(workspace / "source_checkout.json").write_text(json.dumps(record, indent=2))
print("Engine source:", source)
print("Resolved commit:", commit, "(use this SHA as REVISION to reproduce this run)")
return source, record