"""Review a temporary Git diff with deterministic local checks and validate review output."""
from hashlib import sha256
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
def review_payload(body, number):
if not body.strip():
return None
return {"pull_number": number, "event": "COMMENT", "body": body.strip()}
def main():
git = shutil.which("git")
codex = shutil.which("codex.exe") or shutil.which("codex")
if not git or not codex:
raise SystemExit("Install Git and Codex CLI and add both to PATH.")
cases = []
def check(name, data, operation, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name="github_" + name, input=data, operation=operation, expected=expected, actual=actual))
with TemporaryDirectory(prefix="mbsky-codex-github-") as temporary:
base = Path(temporary)
repo = base / "repo"
profile = base / "codex"
repo.mkdir()
profile.mkdir()
env = {key: value for key, value in os.environ.items() if not key.startswith(("GIT_", "CODEX_"))}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, CODEX_HOME=str(profile))
def run(binary, *args):
return subprocess.run([binary, *args], cwd=repo, env=env, capture_output=True,
encoding="utf8", timeout=15)
def git_run(*args):
result = run(git, *args)
result.check_returncode()
return result.stdout.strip()
def put(name, text):
path = repo / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(text.encode())
git_run("init", "--quiet", "--template=", "--initial-branch=base")
git_run("config", "user.email", "lesson@example.invalid")
git_run("config", "user.name", "Tutorial Lab")
git_run("config", "core.autocrlf", "false")
git_run("config", "commit.gpgsign", "false")
put("AGENTS.md", "## Code Review Rules\nFlag logs containing [synthetic-email].\n")
put("billing/AGENTS.md", "## Code Review Rules\nRequire a positive quantity.\n")
put("billing/orders.py", "def validate(quantity):\n return quantity > 0\n")
put("catalog/filter.py", "def matches(rows):\n return bool(rows)\n")
git_run("add", ".")
git_run("commit", "--quiet", "-m", "Baseline")
git_run("switch", "--quiet", "-c", "review")
put("billing/orders.py", "def validate(quantity):\n print('[synthetic-email]')\n return quantity >= 0\n")
put("catalog/filter.py", "def matches(rows):\n return len(rows) > 0\n")
git_run("add", ".")
git_run("commit", "--quiet", "-m", "Simulated PR")
changed = git_run("diff", "--name-only", "base...HEAD").splitlines()
check("changed", "base...HEAD", "Run git diff for the simulated PR",
["billing/orders.py", "catalog/filter.py"], changed)
def guides(path):
relative = Path(path)
folders = [repo / parent for parent in reversed(relative.parents)]
return sorted((folder / "AGENTS.md").relative_to(repo).as_posix()
for folder in folders if (folder / "AGENTS.md").is_file())
check("scope", changed, "Resolve nearby guide files in the site's exercise",
{"billing/orders.py": ["AGENTS.md", "billing/AGENTS.md"], "catalog/filter.py": ["AGENTS.md"]},
{path: guides(path) for path in changed})
findings = []
for path in changed:
diff = git_run("diff", "--unified=0", "base...HEAD", "--", path)
added = [line[1:] for line in diff.splitlines() if line.startswith("+") and not line.startswith("+++")]
if "AGENTS.md" in guides(path):
findings.extend([path, "synthetic_email_logged"] for line in added if "[synthetic-email]" in line)
if "billing/AGENTS.md" in guides(path):
findings.extend([path, "zero_quantity_accepted"] for line in added if "quantity >= 0" in line)
check("findings", changed, "Apply two deterministic checks to actual additions in the local Git diff",
[["billing/orders.py", "synthetic_email_logged"], ["billing/orders.py", "zero_quantity_accepted"]], findings)
orders = run(sys.executable, "-I", "-B", "-c",
"import json, runpy; validate = runpy.run_path('billing/orders.py')['validate']; "
"print(json.dumps([validate(n) for n in (0, -1, 1)]))")
orders.check_returncode()
output = orders.stdout.splitlines()
check("boundary", [0, -1, 1], "Execute the locally authored fixture and observe data and validation results",
[True, False, True], json.loads(output[-1]))
check("log", "[synthetic-email]", "Check captured output of the independent billing fixture",
3, sum(line == "[synthetic-email]" for line in output))
report = "Zero quantity passes. Change the test to quantity > 0."
check("report", {"number": 42, "report": report}, "Build the body of a review as local data",
{"pull_number": 42, "event": "COMMENT", "body": report}, review_payload(report, 42))
check("empty_report", " ", "Check the blank artifact branch", True, review_payload(" ", 42) is None)
help_result = run(codex, "exec", "--help")
help_result.check_returncode()
flags = [bool(re.search(pattern, help_result.stdout)) for pattern in
(r"(?m)^\s+-o, --output-last-message\s+<FILE>", r"(?m)^\s+(?:-\w, )?--output\s+<")]
check("flags", ["--output-last-message", "--output"], "Inspect exact option names in installed CLI help",
[True, False], flags)
version = run(codex, "--version")
version.check_returncode()
print(json.dumps(dict(version={"python": sys.version.split()[0], "codex": version.stdout.strip(),
"git": git_run("--version")}, codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(), cases=cases)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。
入口文件:projects/codex-github/github_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
github_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a105.zip