46cd30e4f9
原来的 build.yml 有两处硬伤: ① 检出取的是"当时的分支 HEAD"(git fetch --depth 50 origin $BR + checkout FETCH_HEAD), 事件之后若又有人推一次,跑的就是另一个提交 —— 报告里的"成功"没有对应提交。 ② 末尾那个 deploy:test 作业会打印 TODO 然后返回成功:网页上看起来部署过了,实际什么都没做。 改法: - 检出**核对**到事件完整 SHA(先按分支取,不一致就按精确 SHA 取,再取不到直接红)。 - 单作业串行:检出 → 环境与工具链(缺什么一次性报全)→ make verify → 预览 → 通知。 单作业是有意的:跨作业传状态要靠 /tmp,而那个"契约"从来没保证过。 - 预览只在报告里 overall_status==success 时发布,并且断言报告 SHA == 事件 SHA、 产物包里真的有 index.html、报告里给出的每个地址都探测到 200。 打包不再产生 `.` 根成员(原来会,症状是通知发了、预览 404)。 - 通知用 if: always(),通知失败**不改质量结论**;只有"汇总报告读不到/解析不了"才非 0。 - 依赖清单在编译前后各取一次摘要,被任何一步改写即红(防 GOFLAGS=-mod=mod 与缺锁回落)。 验证:YAML 解析通过(触发 push/workflow_dispatch、单作业 build、5 步、无部署作业); ci_report.py 对合成报告实跑:通知不可达时退出码 0 且 notification_status=failed, 报告缺失时退出码 1(不能报绿)。部署未涉及,本仓**未部署**。
142 lines
6.5 KiB
Python
Executable File
142 lines
6.5 KiB
Python
Executable File
#!/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:])) |