"""Run an offline GitHub event-policy exercise with temporary Git history."""
import argparse
from copy import deepcopy
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from tempfile import TemporaryDirectory
COMMENT_EVENTS = {"issue_comment", "pull_request_review_comment"}
TRUSTED_ASSOCIATIONS = {"OWNER", "MEMBER", "COLLABORATOR"}
TRIGGER = re.compile(r"(?:^|\s)/(?:opencode|oc)(?=\s|$)", re.IGNORECASE)
FIXED_PROMPTS = {
"issues": "Classify the reported inventory fault and propose a reproduction.",
"pull_request": "Inspect the change for incorrect handling of empty orders.",
"schedule": "List unresolved inventory TODOs and summarize them in the log.",
"workflow_dispatch": "Explain what the inventory check does.",
}
def plan(event, payload):
"""Resolve only a local teaching plan. Never invoke a shell from event text."""
action = payload.get("action")
if event in COMMENT_EVENTS:
comment = payload.get("comment", {})
if action != "created" or comment.get("author_association") not in TRUSTED_ASSOCIATIONS:
return None
body = comment.get("body", "")
match = TRIGGER.search(body)
if not match:
return None
prompt = (body[:match.start()] + " " + body[match.end():]).strip()
if not prompt:
return None
if event == "pull_request_review_comment":
return dict(kind="inline_review", prompt=prompt, path=comment.get("path"), line=comment.get("line"))
kind = "pull_request_discussion" if payload.get("issue", {}).get("pull_request") else "issue_discussion"
return dict(kind=kind, prompt=prompt)
if event == "issues" and action not in {"opened", "edited"}:
return None
if event == "pull_request":
pr = payload.get("pull_request", {})
if action not in {"opened", "synchronize", "reopened"}:
return None
head_repo = pr.get("head", {}).get("repo") or {}
base_repo = payload.get("repository", {}).get("full_name")
if not base_repo or head_repo.get("full_name") != base_repo:
return None
if event in FIXED_PROMPTS:
return dict(kind=event, prompt=FIXED_PROMPTS[event])
return None
def git(repo, *args):
environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0")
return subprocess.check_output(["git", *args], cwd=repo, env=environment, encoding="utf-8", timeout=8).strip()
def isolated_branch(route):
assert route["kind"] == "issue_discussion" and route["prompt"] == "fix duplicate reservation"
with TemporaryDirectory(prefix="mbsky-github-event-") as path:
repo = Path(path)
git(repo, "init", "-q", "-b", "main")
git(repo, "config", "user.name", "Inventory Fixture")
git(repo, "config", "user.email", "inventory@example.invalid")
git(repo, "config", "core.hooksPath", str(repo / "empty-hooks"))
stock = repo / "inventory.txt"
stock.write_text("reserve twice\n", encoding="utf-8")
(repo / "unrelated.txt").write_text("unchanged\n", encoding="utf-8")
git(repo, "add", "inventory.txt", "unrelated.txt")
git(repo, "commit", "-qm", "Prepare sample inventory")
git(repo, "switch", "-qc", "review/issue-37")
stock.write_text("reserve once\n", encoding="utf-8")
git(repo, "add", "inventory.txt")
git(repo, "commit", "-qm", "Fix fixture reservation")
return dict(
branch=git(repo, "branch", "--show-current"),
changed=git(repo, "diff", "--name-only", "main...HEAD").splitlines(),
original=git(repo, "show", "main:inventory.txt"),
fixed=git(repo, "show", "HEAD:inventory.txt"),
remotes=git(repo, "remote").splitlines(),
)
def examples():
issue = {"action": "created", "issue": {"number": 37},
"comment": {"author_association": "MEMBER", "body": "/opencode explain reservation 37"}}
fix = deepcopy(issue)
fix["comment"]["body"] = "/OPENCODE fix duplicate reservation"
discussion = deepcopy(issue)
discussion["issue"]["pull_request"] = {"url": "https://example.invalid/pulls/42"}
discussion["comment"]["body"] = "Check the unit conversion /oc"
inline = deepcopy(issue)
inline["comment"].update(body="/oc handle empty order here", path="src/orders.py", line=18)
outsider = deepcopy(issue)
outsider["comment"]["author_association"] = "NONE"
false_match = deepcopy(issue)
false_match["comment"]["body"] = "/ocean data"
edited = deepcopy(issue)
edited["action"] = "edited"
pr = {"action": "synchronize", "repository": {"full_name": "mbsky/inventory"},
"pull_request": {"head": {"repo": {"full_name": "mbsky/inventory"}}}}
fork = deepcopy(pr)
fork["pull_request"]["head"]["repo"]["full_name"] = "external/inventory"
unsupported = deepcopy(pr)
unsupported["action"] = "closed"
examples = [
("issue_explain", "issue_comment", issue, dict(kind="issue_discussion", prompt="explain reservation 37")),
("issue_fix", "issue_comment", fix, dict(kind="issue_discussion", prompt="fix duplicate reservation")),
("pr_discussion", "issue_comment", discussion, dict(kind="pull_request_discussion", prompt="Check the unit conversion")),
("line_comment", "pull_request_review_comment", inline,
dict(kind="inline_review", prompt="handle empty order here", path="src/orders.py", line=18)),
("outsider", "issue_comment", outsider, None),
("token_boundary", "issue_comment", false_match, None),
("edited_comment", "issue_comment", edited, None),
("pr_review", "pull_request", pr,
dict(kind="pull_request", prompt="Inspect the change for incorrect handling of empty orders.")),
("fork", "pull_request", fork, None),
("closed_pr", "pull_request", unsupported, None),
("issue_triage", "issues", {"action": "opened"},
dict(kind="issues", prompt="Classify the reported inventory fault and propose a reproduction.")),
("scheduled_task", "schedule", {},
dict(kind="schedule", prompt="List unresolved inventory TODOs and summarize them in the log.")),
("manual_dispatch", "workflow_dispatch", {},
dict(kind="workflow_dispatch", prompt="Explain what the inventory check does.")),
]
cases = []
for name, event, inputs, expected in examples:
actual = plan(event, inputs)
assert actual == expected, (name, actual)
cases.append(dict(name=name, inputs={"event": event, "payload": inputs}, expected=expected, actual=actual,
operation="读取独立事件数据并构造本站任务计划"))
actual = isolated_branch(plan("issue_comment", fix))
expected = dict(branch="review/issue-37", changed=["inventory.txt"], original="reserve twice", fixed="reserve once", remotes=[])
assert actual == expected, actual
cases.append(dict(name="git_branch", inputs={"branch": "main", "issue": 37, "file": "inventory.txt"},
expected=expected, actual=actual,
operation="用真实 Git 在临时仓库创建分支、提交及核对合并基点差异"))
return dict(cases=cases, python_version=sys.version.split()[0], git_version=git(Path.cwd(),"--version"))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--event")
parser.add_argument("--payload", type=Path)
opts = parser.parse_args()
if opts.event or opts.payload:
if not opts.event or not opts.payload:
parser.error("--event and --payload must be supplied together")
payload = json.loads(opts.payload.read_bytes())
route = plan(opts.event, payload)
result = None if route is None else {"kind": route["kind"]}
else:
result = examples()
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Python 3.12、Git 2.54、独立临时仓库和自建事件数据。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.12、Git 2.54、独立临时仓库和自建事件数据。
入口文件:projects/opencode-github/github_event.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
github_event.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.12、Git 2.54、独立临时仓库和自建事件数据。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a244.zip
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip