mvp-ai's picture
download
raw
6.55 kB
#!/usr/bin/env python3
"""Publish the current repository snapshot through the GitHub Git API.
This is a fallback for environments where api.github.com is reachable but
github.com Git push/OAuth device endpoints are blocked.
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import subprocess
import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
API = "https://api.github.com"
def run_git(args: list[str]) -> str:
return subprocess.check_output(["git", *args], text=True, encoding="utf-8").strip()
def request(method: str, path: str, token: str, payload: dict | None = None) -> dict:
last_error: Exception | None = None
for attempt in range(1, 7):
data = None
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"User-Agent": "codex-harness-publisher",
"X-GitHub-Api-Version": "2022-11-28",
}
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = Request(f"{API}{path}", data=data, headers=headers, method=method)
try:
with urlopen(req, timeout=90) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
except HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
if exc.code not in {502, 503, 504}:
raise RuntimeError(
f"GitHub API {method} {path} failed: {exc.code} {body}"
) from exc
last_error = RuntimeError(
f"GitHub API {method} {path} failed: {exc.code} {body}"
)
except URLError as exc:
last_error = exc
if attempt < 6:
time.sleep(min(2**attempt, 20))
raise RuntimeError(f"GitHub API {method} {path} failed after retries: {last_error}")
def tracked_files() -> list[str]:
return [
line
for line in run_git(["ls-files"]).splitlines()
if line and not line.startswith(".harness/") and not line.startswith(".tools/")
]
def build_tree(owner: str, repo: str, token: str, files: list[str]) -> str:
tree = []
for rel in files:
path = Path(rel)
content = path.read_bytes()
blob = request(
"POST",
f"/repos/{owner}/{repo}/git/blobs",
token,
{
"content": base64.b64encode(content).decode("ascii"),
"encoding": "base64",
},
)
tree.append({"path": rel.replace(os.sep, "/"), "mode": "100644", "type": "blob", "sha": blob["sha"]})
created = request("POST", f"/repos/{owner}/{repo}/git/trees", token, {"tree": tree})
return created["sha"]
def get_ref(owner: str, repo: str, branch: str, token: str) -> dict | None:
try:
return request("GET", f"/repos/{owner}/{repo}/git/refs/heads/{branch}", token)
except RuntimeError as exc:
if "404" in str(exc) or "409" in str(exc):
return None
raise
def ensure_initialized(owner: str, repo: str, branch: str, token: str) -> dict | None:
ref = get_ref(owner, repo, branch, token)
if ref:
return ref
readme = Path("README.md")
if not readme.is_file():
raise RuntimeError("empty repository needs README.md to initialize default branch")
request(
"PUT",
f"/repos/{owner}/{repo}/contents/README.md",
token,
{
"message": "Initialize repository",
"content": base64.b64encode(readme.read_bytes()).decode("ascii"),
"branch": branch,
},
)
return get_ref(owner, repo, branch, token)
def main() -> int:
parser = argparse.ArgumentParser(description="Publish current git snapshot via GitHub API")
parser.add_argument("--owner", required=True)
parser.add_argument("--repo", required=True)
parser.add_argument("--branch", default="main")
parser.add_argument("--token-file", required=True)
parser.add_argument("--message", default="Adapt harness for Codex")
args = parser.parse_args()
token_path = Path(args.token_file)
if not token_path.is_file():
print(f"FAIL: token file not found: {token_path}", file=sys.stderr)
return 1
token = token_path.read_text(encoding="utf-8").strip()
if not token:
print("FAIL: token file is empty", file=sys.stderr)
return 1
request("GET", "/user", token)
request(
"PATCH",
f"/repos/{args.owner}/{args.repo}",
token,
{
"description": (
"Codex-native harness for staged requirement clarification, "
"Red/Blue/Judge debate, execution manifests, TDD implementation, "
"QA gates, browser/user acceptance, context budgeting, and compact "
"sub-agent handoffs."
),
"homepage": "",
"has_issues": True,
"has_projects": True,
"has_wiki": False,
},
)
files = tracked_files()
if not files:
print("FAIL: no tracked files to publish", file=sys.stderr)
return 1
print(f"Publishing {len(files)} tracked files to {args.owner}/{args.repo}:{args.branch}")
ref = ensure_initialized(args.owner, args.repo, args.branch, token)
parent_sha = ref.get("object", {}).get("sha") if ref else None
tree_sha = build_tree(args.owner, args.repo, token, files)
commit_payload = {
"message": args.message,
"tree": tree_sha,
}
if parent_sha:
commit_payload["parents"] = [parent_sha]
commit = request(
"POST",
f"/repos/{args.owner}/{args.repo}/git/commits",
token,
commit_payload,
)
ref_path = f"/repos/{args.owner}/{args.repo}/git/refs/heads/{args.branch}"
if get_ref(args.owner, args.repo, args.branch, token):
request("PATCH", ref_path, token, {"sha": commit["sha"], "force": True})
else:
request(
"POST",
f"/repos/{args.owner}/{args.repo}/git/refs",
token,
{"ref": f"refs/heads/{args.branch}", "sha": commit["sha"]},
)
print(f"PASS: published commit {commit['sha']} to https://github.com/{args.owner}/{args.repo}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

Xet Storage Details

Size:
6.55 kB
·
Xet hash:
1fbadb9e8533f34f73522e0fb55e692670f50fd7bea888d8ed676fb959df4ea3

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.