#!/usr/bin/env python3 """把门禁报告上报给主机侧 ci-bridge(bridge 负责落报告页 + 推微信)。 三条纪律(正本 §4.6): 1. **通知不改变质量结论**:通知发不出去,跑出来的质量结果还是那个结果 —— 所以本脚本"只报不改",退出码只表达一件事:**汇总本身是否可用**。 2. **汇总不可用不能报绿**:读不到 / 解析不了 `ci-report.json` ⇒ 非 0 退出。 它意味着"这次运行的质量无从判定",而不是"没问题"。 3. 通知结果**单独标注**(`notification_status`),落进报告文件与上报体里, 不靠"有没有收到微信"来判断。 兼容性:沿用 bridge 既有字段(repo/sha/branch/actor/status/commit_subject/commit_count/ duration_s/preview_url/log/steps),另加结构化字段(checks[]、overall_status、policy_revision…)。 bridge 只渲染它认识的键,多出来的键不影响它 —— 因此**不需要改 bridge**。 用法: CI_BRIDGE_RESOLVED=http://172.17.0.1:8899 python3 .gitea/scripts/ci_report.py python3 .gitea/scripts/ci_report.py --report ci-report.json --no-post # 只打印 """ from __future__ import annotations import argparse import json import os import subprocess import sys import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parent.parent.parent # bridge 的 status 只认 success/failure/cancelled,它的"失败步骤"判定是 # `status not in (success, skipped)`;把 not_run 归到 failure 是**保守**方向: # 未运行绝不能被渲染成"通过"。 BRIDGE_STATUS = {"success": "success", "skipped": "skipped", "failure": "failure", "not_run": "failure", "unknown": "failure"} def rd(path: str, default: str = "") -> str: try: return Path(path).read_text(encoding="utf-8").strip() except OSError: return default def git(*args: str) -> str: try: return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True).stdout.strip() except OSError: return "" def main(argv: list[str]) -> int: ap = argparse.ArgumentParser() ap.add_argument("--report", default=os.environ.get("CI_REPORT", str(ROOT / "ci-report.json"))) ap.add_argument("--no-post", action="store_true") args = ap.parse_args(argv) rpath = Path(args.report) if not rpath.is_file(): print(f"❌ 读不到门禁报告 {rpath} —— 这次运行的质量无从判定,不能报绿", file=sys.stderr) return 1 try: rep = json.loads(rpath.read_text(encoding="utf-8")) except json.JSONDecodeError as e: print(f"❌ 门禁报告解析失败({e})—— 不能报绿", file=sys.stderr) return 1 overall = rep.get("overall_status") or "unknown" checks = rep.get("checks") or [] failed = [c["id"] for c in checks if c.get("status") not in ("success", "skipped")] duration = rep.get("duration_s", "?") sha = rep.get("commit_sha") or git("rev-parse", "HEAD") print(f"── 门禁结果 ── 总体 {overall}(策略 {rep.get('policy_revision')},档案 {rep.get('profile')})") for c in checks: mark = {"success": "✅", "skipped": "⏭️"}.get(c.get("status"), "❌") print(f" {mark} {c['id']:<18} {c.get('status'):<8} {c.get('reason', '')[:100]}") payload = { # —— bridge 既有字段(保持兼容,不改 bridge)—— "repo": rep.get("repository") or os.environ.get("GITHUB_REPOSITORY", "unknown/unknown"), "sha": sha, "branch": rep.get("branch") or os.environ.get("GITHUB_REF_NAME", ""), "actor": os.environ.get("GITHUB_ACTOR", ""), "workflow": os.environ.get("GITHUB_WORKFLOW", "build"), "status": BRIDGE_STATUS.get(overall, "failure"), "commit_subject": git("log", "-1", "--format=%s"), "commit_count": rd(os.environ.get("CI_COMMITS_COUNT_FILE", ""), "") or git("rev-list", "--count", "HEAD~1..HEAD"), "duration_s": duration, "preview_url": rd(str(ROOT / ".ci-preview-url")), "log": rd(os.environ.get("CI_GATE_LOG", ""))[-3500:], "steps": [{"name": c["id"], "status": BRIDGE_STATUS.get(c.get("status"), "failure"), "duration_s": c.get("duration_s")} for c in checks], # —— 结构化字段(正本 §5 的检查报告形状)—— "schema": rep.get("schema"), "policy_revision": rep.get("policy_revision"), "overall_status": overall, "profile": rep.get("profile"), "event": rep.get("event"), "run_id": os.environ.get("GITHUB_RUN_ID", ""), "run_url": (f"{os.environ.get('GITHUB_SERVER_URL', '')}/" f"{rep.get('repository', '')}/actions/runs/{os.environ.get('GITHUB_RUN_ID', '')}" if os.environ.get("GITHUB_RUN_ID") else ""), "checks": checks, "problems": rep.get("problems") or [], "failed_checks": failed, "notification_status": "not_attempted", "deployed": False, # 本 workflow 只做 CI:没有部署,报告里也这么写 } base = (os.environ.get("CI_BRIDGE_RESOLVED") or os.environ.get("BRIDGE_URL") or "").rstrip("/") if args.no_post or not base: print(f"跳过上报(--no-post={args.no_post},bridge={base or '未找到'})") return 0 data = json.dumps(payload, ensure_ascii=False).encode("utf-8") req = urllib.request.Request(base + "/api/ci/report", data=data, method="POST", headers={"Content-Type": "application/json", "X-CI-Token": os.environ.get("BRIDGE_TOKEN", "")}) status = "failed" try: with urllib.request.urlopen(req, timeout=30) as resp: body = resp.read().decode()[:300] status = "sent" print(f"✅ 已上报 ci-bridge:{body}") except (urllib.error.URLError, OSError) as e: status = f"failed: {e}" # 通知失败**不**改变质量结论:这里只标注,不把运行判红。 print(f"❌ 上报 ci-bridge 失败(质量结论不变,仅通知失败):{e}", file=sys.stderr) payload["notification_status"] = status rep["notification_status"] = status rpath.write_text(json.dumps(rep, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))