ci(workflow): 检出抽成脚本、预览先核对报告、提交范围以 Git 为准

检出:协议按 GITHUB_SERVER_URL 原样保留并断言不降级(https 不许变 http)、URL 不放凭据、把事件 before 也取下来。预览:发布前调 ci_report.verify(),有问题一个 publish 请求都不发(旧写法只读 overall+SHA,缺项报告会先发出去)。范围:push 用 before..after、新分支用 after --not --remotes,声明与范围不一致/空范围/浅克隆缺 before/列表提交不在检出里全部拒绝,手工运行只核 HEAD 并写明。合并必需 context 改由 .gitea/required-contexts.txt 声明,不再用观察到的状态。
This commit is contained in:
姚章浩
2026-10-12 11:15:18 +08:00
parent 88da069e1f
commit 9a178675f6
6 changed files with 933 additions and 140 deletions
+10
View File
@@ -0,0 +1,10 @@
# 合并前必须在 PR 头提交上 success 的 status context(**明确策略**,一行一个,`#` 后是注释)。
#
# 这份文件是"要求哪些检查"的唯一来源:
# · scripts/adopt-existing.py 的 --merge-pr 只认它(或显式 --require-context),
# **不接受"体检时观察到哪些状态"** —— 那等于把"要求什么"交给当时碰巧报过的状态;
# · 文件为空 / 只有注释 ⇒ 视为没有策略 ⇒ 拒绝合并(空不等于"没有要求")。
#
# 目前本仓只有 .gitea/workflows/build.yml 一个作业,它的 status context 实测就是下面这条:
# run #15(push, main, 5f3a71ca)combined=success,context 'build / build (push)' = success
build / build (push)
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env bash
# 检出:固定到**事件的完整 SHA**,协议按服务端给的来(不许静默降级成 http),URL 里不放凭据。
#
# 为什么要单独成一个脚本(而不是写在 workflow 的 `run:` 里):
# workflow 里的 shell 没法在本地跑,也就没法给它补负例 —— 而"协议被降级""remote 里带了令牌"
# 这两件事恰恰是**只有真跑一遍才看得出来**的。
#
# 用法:
# .gitea/scripts/ci_checkout.sh # CI 里跑(读下面的环境变量)
# .gitea/scripts/ci_checkout.sh --print-remote # 只打印将要使用的 remote(本地测协议用,不联网)
#
# 环境变量(CI 提供):
# GITHUB_SERVER_URL / GITHUB_REPOSITORY / GITHUB_REF_NAME / GITHUB_SHA
# GITHUB_TOKEN(步骤级注入)/ GITHUB_WORKSPACE / GITHUB_EVENT_PATH(用来取 before)
set -uo pipefail
SRV="${GITHUB_SERVER_URL:-http://192.168.50.223:3000}"
WS="${GITHUB_WORKSPACE:-$(pwd)}"
BR="${GITHUB_REF_NAME:-${GITHUB_REF:-}}"
BR="${BR#refs/heads/}"
EVENT_SHA="${GITHUB_SHA:-}"
# ── ① 协议:**保留服务端给的协议**,并显式禁止 https → http 的降级 ──────────────
case "$SRV" in
https://*|http://*) ;;
*) echo "❌ GITHUB_SERVER_URL 的协议不认识:${SRV:0:40}"; exit 1 ;;
esac
case "$SRV" in
*[[:space:]]*) echo "❌ GITHUB_SERVER_URL 里有空白字符"; exit 1 ;;
esac
case "$SRV" in https://*) WANT_SCHEME="https" ;; *) WANT_SCHEME="http" ;; esac
REMOTE="${SRV%/}/${GITHUB_REPOSITORY}.git"
case "$REMOTE" in https://*) GOT_SCHEME="https" ;; http://*) GOT_SCHEME="http" ;; *) GOT_SCHEME="?" ;; esac
if [ "$GOT_SCHEME" != "$WANT_SCHEME" ]; then
echo "❌ remote 的协议被降级了:拼出来是 $GOT_SCHEME,服务端给的是 $WANT_SCHEME"
exit 1
fi
# 凭据一律走 credential helper(URL 内嵌凭据会进 ps / 配置 / 日志)
case "$REMOTE" in *@*) echo "❌ remote URL 里带上了凭据"; exit 1 ;; esac
if [ "${1:-}" = "--print-remote" ]; then
echo "$REMOTE"
exit 0
fi
[ -n "$EVENT_SHA" ] || { echo "❌ 没有 GITHUB_SHA:检出必须固定到事件的完整 SHA"; exit 1; }
cd "$WS" || exit 1
rm -rf ./* .git 2>/dev/null || true
git init -q .
git remote add origin "$REMOTE"
[ -n "${GITHUB_TOKEN:-}" ] || { echo "❌ 没有拿到读仓库用的令牌(GITHUB_TOKEN 为空)"; exit 1; }
gitauth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$GITHUB_TOKEN"; }; f' "$@"; }
gitauth fetch -q --depth 50 origin "$BR"
git checkout -q -B "$BR" FETCH_HEAD
if [ "$(git rev-parse HEAD)" != "$EVENT_SHA" ]; then
echo "⚠️ 分支 $BR 的 HEAD 已经不等于事件 SHA(有人在之后又推了一次)—— 改按精确 SHA 取"
gitauth fetch -q --depth 50 origin "$EVENT_SHA" && git checkout -q --detach FETCH_HEAD \
|| { echo "❌ 取不到事件 SHA $EVENT_SHA"; exit 1; }
fi
GOT="$(git rev-parse HEAD)"
if [ "$GOT" != "$EVENT_SHA" ]; then
echo "❌ 检出 SHA 与事件 SHA 不一致:实际 $GOT / 事件 $EVENT_SHA"
echo " (门禁的 identity 项会再拦一次;这里先失败,避免拿错误的代码下结论)"
exit 1
fi
# ── ② 把 before 也取下来:否则"本次推送范围 before..after"在浅克隆里算不出来 ──
# 不取的话,范围校验要么报错要么静默收缩 —— 两种都不是"检查过本次改动"。
BEFORE=""
if [ -n "${GITHUB_EVENT_PATH:-}" ] && [ -f "${GITHUB_EVENT_PATH}" ]; then
BEFORE="$(python3 -c 'import json,os,sys
try:
d = json.load(open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8"))
print(d.get("before") or "")
except Exception:
print("")' 2>/dev/null || echo "")"
fi
if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ]; then
if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
echo "✅ 事件 before ${BEFORE:0:12} 已在克隆里(本次推送范围可直接算)"
else
gitauth fetch -q --depth 50 origin "$BEFORE" 2>/dev/null \
&& echo "✅ 已补取事件 before ${BEFORE:0:12}(本次推送范围可算)" \
|| echo "⚠️ 取不到事件 before ${BEFORE:0:12}:范围校验会明确失败,不会静默收缩"
fi
else
echo "(事件里没有 before / before 为全 0:新分支推送或手工运行,范围按 after 判)"
fi
# 令牌不该出现在 remote 配置里:顺手断言一次(防有人改回去)
if git remote get-url origin | grep -q '@'; then
echo "❌ remote URL 里带上了凭据:$(git remote get-url origin | sed 's#//.*@#//***@#')"
exit 1
fi
git rev-list --count FETCH_HEAD > "${WS}/.ci-commits-count" 2>/dev/null || echo 1 > "${WS}/.ci-commits-count"
: > "${WS}/.ci-preview-url"
echo "✅ 已检出 ${GITHUB_REPOSITORY} 分支 $BR @ ${GOT:0:12}(== 事件完整 SHA,协议 $GOT_SCHEME)"
git log -1 --format=' %h %an %s'
echo "CI_COMMITS_COUNT_FILE=${WS}/.ci-commits-count" >> "${GITHUB_ENV:-/dev/null}"
+350 -34
View File
@@ -3,19 +3,39 @@
规则与本机 ~/.githooks/commit-msg 完全一致,防止 --no-verify 绕过。
放行:Merge / Revert " / fixup! / squash! / amend! 开头的自动生成提交。
**校验范围必须是"本次这一批"**,按优先级取,取不到就报错 —— 不回退成"最近 N 条":
1. `CI_COMMIT_RANGE=A..B`(显式指定,调试/重放用);
2. Gitea 事件负载:`commits[]`(推送事件自带本次推送的每一条);
并且核对负载里的 `after` 与当前 HEAD 一致 —— 不一致说明事件与检出不是同一批;
3. 本地:`git log --not --remotes`(还没推到任何远端的提交 = 本次要推的范围);
本地**一个远端都没有**时,明确只核 HEAD(`--not --remotes` 在那种情况下会退化成整部历史,
连 Initial commit 都算进来 —— 那不是"本次改动")。
为什么不能退化成 `git log -n 5`:那个范围和"本次改动"没有任何关系。
典型假红/假绿两种情况都会发生 —— 五条里混进一条历史坏记录(假红,且红在别人头上),
或者本次推的第 6 条以后有坏记录(假绿,直接放过去)。两种都不是"检查",是噪声。
用法:
python3 .gitea/scripts/ci_gate.py # 按上面的优先级取范围
python3 .gitea/scripts/ci_gate.py --range HEAD~1..HEAD # 显式指定
python3 .gitea/scripts/ci_gate.py --self-test # 反向自检(临时仓库,四种范围)
"""
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
TYPES = "feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert"
RE = re.compile(r"^(?:" + TYPES + r")(?:\([a-zA-Z0-9._/-]+\))?!?: .{3,}$")
ALLOW = re.compile(r'^(?:Merge |Revert "|fixup! |squash! |amend! )')
HELP = """
\u274c 提交信息不合规,已拦截。
❌ 提交信息不合规,已拦截。
规范 : <类型>(<范围>): <简短描述>
类型 : feat 新功能 | fix 修缺陷 | docs 文档 | style 格式(不改逻辑)
@@ -25,35 +45,19 @@ HELP = """
fix(parser): 修复表格解析越界导致的 500
docs: 补充 OSS 短签名接口说明
要点 : 类型小写、冒号后一个空格、描述 \u22653 字符
标题 \u226472 字符、结尾不加句号
要点 : 类型小写、冒号后一个空格、描述 ≥3 字符
标题 ≤72 字符、结尾不加句号
破坏性变更类型后加 !,正文写 BREAKING CHANGE:
详见 : docs/提交规范.md
"""
def collect():
"""优先用 Gitea 事件负载里的本次推送提交,取不到则退回 git log。"""
msgs = []
ev = os.environ.get("GITHUB_EVENT_PATH") or ""
if ev and os.path.exists(ev):
try:
with open(ev, encoding="utf-8") as fh:
d = json.load(fh)
for c in (d.get("commits") or []):
m = (c.get("message") or "").strip()
if m:
msgs.append(m)
except Exception as e:
print(" 事件负载解析失败(%s),回退到 git log" % e)
if not msgs:
out = subprocess.run(["git", "log", "-n", "5", "--format=%B%x00"],
capture_output=True, text=True).stdout
msgs = [x.strip() for x in out.split("\x00") if x.strip()]
return msgs
def git(*args, cwd=None):
p = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
return p.returncode, p.stdout, p.stderr
def subject_of(m):
def subject_of(m: str) -> str:
for line in m.splitlines():
s = line.strip()
if not s or s.startswith("#"):
@@ -62,7 +66,7 @@ def subject_of(m):
return ""
def judge(subj):
def judge(subj: str) -> str:
if not subj:
return "空提交信息"
if ALLOW.match(subj):
@@ -76,29 +80,341 @@ def judge(subj):
return ""
def main():
msgs = collect()
def _range_commits(spec: str, cwd=None):
# spec 可能是一个 rev 范围(A..B),也可能是带开关的写法(--not --remotes)——
# 必须拆成多个参数,整串当**一个** argv 会被 git 判成"未能识别的参数"(实测踩过)。
rc, out, err = git("log", "--format=%H%x00%B%x00%x00", *shlex.split(spec), cwd=cwd)
if rc != 0:
return None, f"范围 {spec} 取不到提交:{(err or out).strip()[:200]}"
msgs = [x for x in out.split("\x00\x00") if x.strip()]
out_msgs = []
for chunk in msgs:
parts = chunk.split("\x00", 1)
out_msgs.append({"sha": parts[0].strip(), "message": parts[1] if len(parts) > 1 else ""})
return out_msgs, ""
def _payload(env):
"""读事件负载。返回 (payload, 错误)。错误非空 ⇒ 范围无法确定。"""
ev = (env.get("GITHUB_EVENT_PATH") or "").strip()
if not ev or not os.path.exists(ev):
return {}, ""
try:
with open(ev, encoding="utf-8") as fh:
d = json.load(fh)
except Exception as e:
return None, f"事件负载解析失败({e})—— 范围无法确定,不许放行"
if not isinstance(d, dict):
return None, "事件负载不是 JSON 对象 —— 范围无法确定,不许放行"
return d, ""
def resolve_scope(explicit="", env=None, cwd=None):
"""返回 (提交列表, 来源说明, 错误)。错误非空 ⇒ 不许放行。
**范围以 Git 为准,不拿事件负载里那一串当依据**:负载可能是截断的(实测声明 6 条、
列表只给 1 条),而且负载来自事件、代码来自检出,两者本来就可能不是同一批。
"""
env = env if env is not None else os.environ
in_ci = bool(env.get("GITHUB_ACTIONS"))
zero = "0" * 40
spec = (explicit or env.get("CI_COMMIT_RANGE", "") or "").strip()
if spec:
commits, err = _range_commits(spec, cwd)
if err:
return [], "", err
if not commits and in_ci:
return [], f"显式范围 {spec}", (f"显式范围 {spec} 为空 —— 空范围没有可核的提交,"
f"在 CI 里必须显式拒绝,不许静默通过")
return commits, f"显式范围 {spec}", ""
d, err = _payload(env)
if err:
return [], "", err
event = str(d.get("event_name") or env.get("GITHUB_EVENT_NAME") or "").strip()
after = str(d.get("after") or env.get("GITHUB_SHA") or "").strip()
before = str(d.get("before") or "").strip()
listed = [{"sha": str(c.get("id") or c.get("sha") or ""), "message": str(c.get("message") or "")}
for c in (d.get("commits") or []) if isinstance(c, dict)]
declared_raw = d.get("total_commits")
for label, v in (("before", before), ("after", after)):
if v and not set(v) <= set("0123456789abcdef"):
return [], "", f"事件负载的 {label} 不是 SHA:{v[:20]!r}"
if after and after != zero:
rc, head, _ = git("rev-parse", "HEAD", cwd=cwd)
head = head.strip()
if rc != 0 or head != after:
return [], "", (f"事件负载 after={after[:12]} 与当前 HEAD={head[:12]} 不一致 —— "
f"事件与检出不是同一批,范围无法确定")
# ── ① 推送事件:before..after 是权威范围 ─────────────────────────────
if before and after and after != zero:
if before == zero:
spec2 = f"{after} --not --remotes" # 新分支:远端没有这个分支的历史
src = "新分支推送(before 为全 0)⇒ 范围 = after 之后未被远端覆盖的提交"
else:
spec2 = f"{before}..{after}"
src = f"事件 Git 范围 {before[:12]}..{after[:12]}"
commits, gerr = _range_commits(spec2, cwd)
if gerr:
return [], src, (
f"{gerr}。若这是浅克隆(CI 检出默认 `--depth 50`),before 可能根本不在克隆里 —— "
f"**范围不全就是漏查**,不许放行:提高 fetch 深度,或用 --range 显式指定。")
if not commits:
return [], src, ("本次推送的 Git 范围是空的(before == after?)—— 空范围没有可核的提交,"
"不许静默通过")
if declared_raw not in (None, ""):
try:
declared = int(declared_raw)
except (TypeError, ValueError):
return [], src, f"事件负载 total_commits 不是整数:{declared_raw!r}"
if declared != len(commits):
return [], src, (
f"事件声明 {declared} 条提交,但 Git 范围算出 {len(commits)} 条"
f"(负载列表给了 {len(listed)} 条)—— 两边的'本次范围'对不上,"
f"谁也不能采信,不许放行")
if declared != len(listed):
src += (f"(⚠️ 事件列表被截断:声明 {declared} 条、列表只给 {len(listed)} 条"
f" ⇒ 以 Git 范围为准)")
else:
src += "(与事件列表一致)"
elif len(listed) != len(commits):
src += (f"(⚠️ 事件列表 {len(listed)} 条、Git 范围 {len(commits)} 条"
f" ⇒ 以 Git 范围为准)")
return commits, src, ""
# ── ② 负载里有 commits 但没有 before:用列表,但**没有 Git 范围可交叉核对**,要写明 ──
if listed and not before:
bad = [c["sha"][:12] for c in listed
if not c["sha"] or git("cat-file", "-e", c["sha"], cwd=cwd)[0] != 0]
if bad:
return [], "", (f"事件列表里的提交在检出里不存在:{bad[:3]} —— "
f"事件与检出不是同一批,范围无法确定")
if declared_raw not in (None, ""):
try:
declared = int(declared_raw)
except (TypeError, ValueError):
return [], "", f"事件负载 total_commits 不是整数:{declared_raw!r}"
if declared != len(listed):
return [], "", (f"事件声明 {declared} 条提交、列表只给 {len(listed)} 条,"
f"而这次又没有 before 可以算 Git 范围 —— 列表被截断且无法交叉核对,"
f"不许拿截断后的列表去核")
return listed, ("事件列表 commits[](**没有 before,无法用 Git 范围交叉核对**)"
"—— 已逐条确认这些提交在检出里存在"), ""
# ── ② 手工运行 / 没有 before:与远端默认分支比,比不出来就只核 HEAD(写明)──
if in_ci or event == "workflow_dispatch" or after:
base = ""
rc, out, _ = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd)
if rc == 0 and out.strip():
base = out.strip()
else:
_, out2, _ = git("for-each-ref", "--format=%(refname:short)", "refs/remotes/origin", cwd=cwd)
cand = [l.strip() for l in out2.splitlines() if l.strip().endswith(("/main", "/master"))]
base = cand[0] if cand else ""
if base:
commits, gerr = _range_commits(f"{base}..HEAD", cwd)
if gerr:
return [], "", gerr
if commits:
return commits, f"手工运行:取 {base}..HEAD(与远端默认分支比)", ""
note = f"手工运行:{base}..HEAD 为空(HEAD 与远端默认分支一致)"
else:
note = "手工运行:取不到远端默认分支(refs/remotes/origin 里没有 main/master)"
rc, head, _ = git("rev-parse", "HEAD", cwd=cwd)
head = head.strip()
if rc != 0 or not head:
return [], "", note + ",而且取不到 HEAD —— 范围无法确定"
rc2, body, _ = git("log", "-1", "--format=%B", cwd=cwd)
return ([{"sha": head, "message": body}],
note + " ⇒ **只核 HEAD 这一条提交**(已写明:这次比不出范围,不是'最近 N 条')", "")
# ── ③ 本地(无事件负载):未推到远端的提交 ───────────────────────────
# ⚠️ 先看有没有远端引用:**一个远端都没有**时,`--not --remotes` 会退化成"整部历史"
# (连 Initial commit 都算进来)—— 那不是"本次改动",而是一条历史坏记录就能让本地门禁常红。
# 这种情况明确只核 HEAD,并写明(要核更多用 --range)。
_, refs, _ = git("for-each-ref", "--format=%(refname)", "refs/remotes", cwd=cwd)
if not refs.strip():
if in_ci:
return [], "", ("在 CI 里既没有事件范围,也没有任何远端引用可以比 —— "
"范围无法确定,不许静默通过")
rc, head, _ = git("rev-parse", "HEAD", cwd=cwd)
head = head.strip()
if rc != 0 or not head:
return [], "", "本地:没有任何远端引用,也取不到 HEAD —— 范围无法确定"
_, body, _ = git("log", "-1", "--format=%B", cwd=cwd)
return ([{"sha": head, "message": body}],
"本地:没有可比远端(refs/remotes 为空)⇒ **只核 HEAD 这一条提交**"
"(要核更多请用 --range A..B)", "")
commits, err = _range_commits("HEAD --not --remotes", cwd)
if err:
return [], "", err
if commits:
return commits, "本地:范围 = 还没推到远端的提交(git log HEAD --not --remotes)", ""
if in_ci:
return [], "", ("在 CI 里范围为空(既没有事件范围,也没有未推送的提交)—— "
"空范围没有可核的提交,不许静默通过")
return [], "本地:本次范围为空(没有未推送的提交)", ""
def main(argv):
ap = argparse.ArgumentParser(add_help=True)
ap.add_argument("--range", default="")
ap.add_argument("--self-test", action="store_true")
args = ap.parse_args(argv)
if args.self_test:
return self_test()
commits, source, err = resolve_scope(explicit=args.range)
if err:
print(f"❌ 提交校验范围无法确定:{err}", file=sys.stderr)
print(" 处理:用 --range A..B 显式指定,或确认事件负载/远端引用可用。"
"(不会退化成'最近 N 条'—— 那个范围与本次改动无关)", file=sys.stderr)
return 1
print(f"校验范围:{source}|{len(commits)} 条提交")
bad = []
print("待校验提交 %d 条:" % len(msgs))
for m in msgs:
subj = subject_of(m)
for c in commits:
subj = subject_of(c["message"])
why = judge(subj)
if why:
bad.append((subj, why))
print(" \u274c [%s] %s" % (why, subj))
print(" ❌ [%s] %s" % (why, subj))
else:
print(" \u2705 %s" % subj)
print(" ✅ %s" % subj)
try:
with open("/tmp/ci-gate-status", "w") as fh:
fh.write("failure" if bad else "success")
except Exception:
except OSError:
pass
if bad:
print(HELP)
return 1
print("\u2705 提交信息全部合规")
print("✅ 本次范围的提交信息全部合规")
return 0
def self_test() -> int:
"""在临时仓库里造"range 准不准",四种情形都要符合预期。"""
problems = []
with tempfile.TemporaryDirectory() as d:
env = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@t"}
base = {**os.environ, **env}
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=d, env=base, check=True)
# 夹具仓库里**不装**本机提交钩子(core.hooksPath 指到一个空目录):
# 这里要构造一条"违规提交"来验证闸门的范围取法,而本机钩子会先把它拦掉。
# 这不是绕过门禁 —— 沙箱仓本来就没有钩子,而且这条提交永远不会离开临时目录。
empty_hooks = os.path.join(d, "no-hooks")
os.makedirs(empty_hooks, exist_ok=True)
base["GIT_CONFIG_COUNT"] = "1"
base["GIT_CONFIG_KEY_0"] = "core.hooksPath"
base["GIT_CONFIG_VALUE_0"] = empty_hooks
def commit(msg):
subprocess.run(["git", "commit", "-q", "--allow-empty", "-F", "-"], cwd=d, env=base,
input=msg, text=True, check=True)
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=d, capture_output=True,
text=True).stdout.strip()
good1 = commit("feat(a): 第一条合规\n")
bad = commit("update stuff\n") # 违规,但在历史里
good2 = commit("fix(b): 第三条合规\n")
# ① 范围只含最后一条(干净):即使历史里有违规也不许红 —— 证明不是"最近 N 条"
commits, src, err = resolve_scope(explicit=f"{bad}..{good2}", cwd=d)
if err or len(commits) != 1:
problems.append(f"显式范围没有取到恰好 1 条:{err or len(commits)}")
elif any(judge(subject_of(c["message"])) for c in commits):
problems.append("范围只含合规提交,却判成不合规")
# ② 范围含那条违规:必须红(good1..HEAD 覆盖 bad 与 good2)
commits, src, err = resolve_scope(explicit=f"{good1}..HEAD", cwd=d)
flagged = [c for c in commits if judge(subject_of(c["message"]))]
if err or len(commits) != 2 or len(flagged) != 1:
problems.append(f"范围含违规提交时没有恰好判出 1 条:{err or (len(commits), len(flagged))}")
# ③ 本地无事件负载:按"未推到远端的提交"取,且**不是**固定条数
os.environ.pop("GITHUB_EVENT_PATH", None)
os.environ.pop("CI_COMMIT_RANGE", None)
commits, src, err = resolve_scope(env={}, cwd=d)
if err or len(commits) != 1 or "最近" in src:
problems.append(f"无事件负载、无远端时没有按'只核 HEAD'取:{err or (len(commits), src)}")
# ④ 事件负载的 after 与 HEAD 不一致 ⇒ 报错,不许蒙
evf = os.path.join(d, "event.json")
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"after": "f" * 40, "commits": [{"id": good2, "message": "fix(b): 第三条合规"}]}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf}, cwd=d)
if not err:
problems.append("事件 after 与 HEAD 不一致时竟然没有报错")
# ⑤ 事件负载正常(after == HEAD)⇒ 用负载里的 commits
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"after": good2, "commits": [{"id": good2, "message": "fix(b): 第三条合规"}]}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf}, cwd=d)
if err or len(commits) != 1 or "commits[]" not in src:
problems.append(f"事件负载正常时没有按 commits[] 取:{err or (len(commits), src)}")
# ⑫ 本地一个远端都没有 ⇒ 只核 HEAD,并写明(不许退化成"整部历史")
commits, src, err = resolve_scope(env={}, cwd=d)
if err or len(commits) != 1 or "只核 HEAD" not in src:
problems.append(f"没有远端引用时没有退成'只核 HEAD 并写明':{err or (len(commits), src)}")
# ⑥ 负载声明 6 条、列表只给 1 条、Git 范围 2 条 ⇒ 对不上,必须报错(不许采信被截断的列表)
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"before": good1, "after": good2, "total_commits": 6,
"commits": [{"id": good2, "message": "fix(b): 第三条合规"}]}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf, "GITHUB_ACTIONS": "true"}, cwd=d)
if not err:
problems.append("事件声明 6 条、Git 范围 2 条时竟然没有报错(接受了被截断的列表)")
# ⑦ 声明 2 条、列表 1 条、Git 范围 2 条 ⇒ 用 Git 范围,并在来源里写明"列表被截断"
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"before": good1, "after": good2, "total_commits": 2,
"commits": [{"id": good2, "message": "fix(b): 第三条合规"}]}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf, "GITHUB_ACTIONS": "true"}, cwd=d)
if err or len(commits) != 2 or "截断" not in src:
problems.append(f"列表被截断但 Git 范围可用时没有以 Git 为准:{err or (len(commits), src)}")
# ⑧ 空范围(before == after)⇒ CI 里必须显式拒绝
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"before": good2, "after": good2, "total_commits": 0, "commits": []}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf, "GITHUB_ACTIONS": "true"}, cwd=d)
if not err:
problems.append("空范围(before == after)竟然没有报错")
# ⑨ 新分支推送(before 全 0)⇒ 用 after --not --remotes 取
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"before": "0" * 40, "after": good2, "total_commits": 3, "commits": []}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf, "GITHUB_ACTIONS": "true"}, cwd=d)
if err or len(commits) != 3 or "新分支" not in src:
problems.append(f"新分支推送没有按 after --not --remotes 取:{err or (len(commits), src)}")
# ⑩ 手工运行(没有事件负载、也没有远端可比)⇒ 只核 HEAD,并且**写明**这一点
commits, src, err = resolve_scope(env={"GITHUB_ACTIONS": "true"}, cwd=d)
if err or len(commits) != 1 or "只核 HEAD" not in src:
problems.append(f"手工运行没有退成'只核 HEAD 并写明':{err or (len(commits), src)}")
# ⑪ 列表里的提交在检出里不存在 ⇒ 事件与检出不是同一批,必须报错
with open(evf, "w", encoding="utf-8") as fh:
json.dump({"after": good2, "commits": [{"id": "d" * 40, "message": "fix(b): 第三条合规"}]}, fh)
commits, src, err = resolve_scope(env={"GITHUB_EVENT_PATH": evf, "GITHUB_ACTIONS": "true"}, cwd=d)
if not err:
problems.append("事件列表里的提交在检出里不存在,竟然没有报错")
if problems:
print("❌ 提交闸门自检失败:", file=sys.stderr)
for p in problems:
print(f" · {p}", file=sys.stderr)
return 1
print("✅ 提交闸门自检通过:范围取法 12 个分支(显式范围 / Git 范围 before..after / "
"负载声明与列表不一致 / 列表截断仍以 Git 为准 / 空范围拒绝 / 新分支 / 无 before 的列表 / "
"列表提交不在检出里 / after 与 HEAD 核对 / 手工运行只核 HEAD 并写明 / "
"无远端只核 HEAD / 未推送提交)")
return 0
if __name__ == "__main__":
sys.exit(main())
sys.exit(main(sys.argv[1:]))
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""静态预览发布:**先核对完整报告,再发**。
为什么必须在这一步核对,而不是等后面的通知步骤:
预览是**发出去就收不回来**的(URL 会被别人打开、会被转到群里)。等到通知步骤才发现
"报告缺项 / SHA 不对 / 档案不对",那时预览早就发出去了 —— 再红也撤不回来。
所以这里的顺序是:
① 调 `ci_report.verify()`(与上报**同一份**核对逻辑,不另写一套);
② 有任何问题 ⇒ **一个 publish 请求都不发**,直接返回 0(质量结论由门禁那一步负责);
③ 全部通过 ⇒ 打包(不产生 `.` 根成员)→ 断言包里有 index.html → POST publish
→ 报告里给出的**每个地址都探测 200** 才算发布成功。
用法:
python3 .gitea/scripts/ci_preview.py # 真发(CI 用)
python3 .gitea/scripts/ci_preview.py --check-only # 只核对报告,不发
python3 .gitea/scripts/ci_preview.py --self-test # 判定路径自检
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(ROOT / "scripts"))
import ci_report # noqa: E402 (与上报共用同一份核对逻辑)
ARTIFACT_CANDIDATES = ["web/dist", "dist", "build", "out", "public", "web/build", "frontend/dist"]
BRIDGE_CANDIDATES = ["http://172.17.0.1:8899", "http://192.168.50.134:8899", "http://100.92.49.78:8899"]
def find_artifact_dir() -> Path | None:
for rel in ARTIFACT_CANDIDATES:
d = ROOT / rel
if (d / "index.html").is_file():
return d
return None
def pack(web: Path, dest: Path) -> tuple[bool, str]:
"""打包成 tar.gz。⚠️ 不要产生 `.` 根成员(那会让预览 404 而流水线显示成功)。"""
names = []
with tarfile.open(dest, "w:gz") as tf:
for p in sorted(web.rglob("*")):
rel = p.relative_to(web)
if rel.parts and rel.parts[0] in (".", ".."):
continue
tf.add(p, arcname=str(rel))
names.append(str(rel))
if "index.html" not in names:
return False, f"包里没有 index.html(成员 {names[:5]}…)—— 发出去也是 404 的预览"
if any(n.startswith("./") or n == "." for n in names):
return False, f"包里出现了 `.` 根成员:{[n for n in names if n.startswith('./')][:3]}"
return True, f"{len(names)} 个成员"
def resolve_bridge(explicit: str = "") -> str:
cands = [explicit] + BRIDGE_CANDIDATES
for c in cands:
if not c:
continue
try:
with urllib.request.urlopen(c.rstrip("/") + "/healthz", timeout=5) as r:
if r.status == 200:
return c.rstrip("/")
except (urllib.error.URLError, OSError):
continue
return ""
def probe(url: str, timeout: int = 10) -> int:
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status
except urllib.error.HTTPError as e:
return e.code
except (urllib.error.URLError, OSError):
return 0
def publish(base: str, repo: str, sha: str, token: str, blob: bytes) -> tuple[int, dict]:
req = urllib.request.Request(
f"{base}/api/ci/publish?repo={repo}&sha={sha}", data=blob, method="POST",
headers={"X-CI-Token": token, "Content-Type": "application/gzip"})
try:
with urllib.request.urlopen(req, timeout=90) as r:
return r.status, json.loads(r.read().decode() or "{}")
except urllib.error.HTTPError as e:
return e.code, {"_error": e.read().decode()[:200]}
except (urllib.error.URLError, OSError) as e:
return 0, {"_error": str(e)}
def self_test() -> int:
"""打包器的判定:`.` 根成员必须被发现(不然就是"预览 404 而流水线绿")。"""
problems = []
with tempfile.TemporaryDirectory() as d:
web = Path(d) / "dist"
(web / "assets").mkdir(parents=True)
(web / "index.html").write_text("<html></html>", encoding="utf-8")
(web / "assets" / "a.js").write_text("x", encoding="utf-8")
ok, why = pack(web, Path(d) / "good.tgz")
if not ok:
problems.append(f"正常产物打包失败:{why}")
empty = Path(d) / "empty"
empty.mkdir()
ok, why = pack(empty, Path(d) / "bad.tgz")
if ok:
problems.append("空产物目录竟然打包成功(没有 index.html 也算过)")
if problems:
print("❌ 预览脚本自检失败:", file=sys.stderr)
for p in problems:
print(f" · {p}", file=sys.stderr)
return 1
print("✅ 预览脚本自检通过:正常产物可打包;空产物/缺 index.html 被拒")
return 0
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("--check-only", action="store_true")
ap.add_argument("--self-test", action="store_true")
args = ap.parse_args(argv)
if args.self_test:
return self_test()
if ci_report.GATE_ERROR:
print(f"❌ 核对不了报告({ci_report.GATE_ERROR})⇒ 不发预览", file=sys.stderr)
return 2
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
in_ci = bool(os.environ.get("GITHUB_ACTIONS"))
expect_sha = (os.environ.get("GITHUB_SHA") or "").strip()
recomputed, problems, notes = ci_report.verify(rep, expect_sha, in_ci)
print(f"── 发布前核对 ── 重算总体 {recomputed}|报告自称 {rep.get('overall_status')}"
f"|档案 {rep.get('profile')}|run_mode {rep.get('run_mode')}")
for n in notes:
print(f" · {n}")
if problems:
# 关键:**一个字节都不发**。预览发出去了就收不回来。
for p in problems:
print(f" ❌ {p}", file=sys.stderr)
print("❌ 报告核对不通过 ⇒ **不发出任何 publish 请求**", file=sys.stderr)
return 0
if args.check_only:
print("✅ 核对通过(--check-only:不发)")
return 0
web = find_artifact_dir()
if web is None:
print("未发现静态网页产物目录 ⇒ 不发预览(这是配置问题,不是通过)")
return 0
sha = str(rep.get("commit_sha") or "")
with tempfile.TemporaryDirectory() as d:
tar = Path(d) / "preview.tgz"
ok, why = pack(web, tar)
if not ok:
print(f"❌ 打包不通过:{why} ⇒ 不发", file=sys.stderr)
return 0
blob = tar.read_bytes()
print(f" 打包完成:{why}({len(blob)} 字节,目录 {web.relative_to(ROOT)})")
base = resolve_bridge(os.environ.get("CI_BRIDGE_RESOLVED") or os.environ.get("BRIDGE_URL") or "")
if not base:
print("❌ 没有可达的 ci-bridge ⇒ 不发预览(打包成功不等于预览发出去了)", file=sys.stderr)
return 0
code, body = publish(base, rep.get("repository") or os.environ.get("GITHUB_REPOSITORY", ""),
sha, os.environ.get("BRIDGE_TOKEN", ""), blob)
print(f" publish HTTP {code} {json.dumps(body, ensure_ascii=False)[:200]}")
if code != 200:
print(f"❌ 发布接口返回 {code} ⇒ 不发这条预览", file=sys.stderr)
return 0
for key in ("url", "url_tailscale"):
url = str(body.get(key) or "")
if not url:
print(f" ⚠️ 报告里 {key} 为空")
continue
st = probe(url)
print(f" 预览探测 {key}: {url} → {st}")
if st != 200:
print(f"❌ {url} 不是 200(通知里给出打不开的链接等于没给)", file=sys.stderr)
return 0
if key == "url":
(ROOT / ".ci-preview-url").write_text(url + "\n", encoding="utf-8")
print("✅ 预览已发布,且报告里的每个地址都 200")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Executable → Regular
+211 -28
View File
@@ -1,27 +1,33 @@
#!/usr/bin/env python3
"""把门禁报告上报给主机侧 ci-bridge(bridge 负责落报告页 + 推微信)。
"""核对门禁报告并上报 ci-bridge(bridge 负责落报告页 + 推微信)。
三条纪律(正本 §4.6):
1. **通知不改变质量结论**:通知发不出去,跑出来的质量结果还是那个结果 ——
所以本脚本"只报不改",退出码只表达一件事:**汇总本身是否可用**。
2. **汇总不可用不能报绿**:读不到 / 解析不了 `ci-report.json` ⇒ 非 0 退出。
它意味着"这次运行的质量无从判定",而不是"没问题"。
3. 通知结果**单独标注**(`notification_status`),落进报告文件与上报体里,
不靠"有没有收到微信"来判断。
**不只看 `overall_status` 一个字段** —— 那是"信一句没有任何依据的结论"。上报前先独立核对:
兼容性:沿用 bridge 既有字段(repo/sha/branch/actor/status/commit_subject/commit_count/
duration_s/preview_url/log/steps),另加结构化字段(checks[]、overall_status、policy_revision…)。
bridge 只渲染它认识的键,多出来的键不影响它 —— 因此**不需要改 bridge**。
1. 清单一致性:报告里的 `manifest` 必须与实现里的 `CHECK_MANIFEST` 逐项相同;
2. 完整清单核对:报告必须**恰好一次**覆盖清单里在本档案下必需的每一项 ——
缺项 / 重复项 / 清单之外的项,都算不通过;
3. 逐项状态重算总体:只有"必需项全部 success"才算 success,并与报告自称的
`overall_status` 对照;**两者不一致 ⇒ 汇总不可信**;
4. 归属:`commit_sha` 必须是**完整 40 位 SHA**,且(CI 上)等于事件 SHA;
5. 档案:CI 里必须是 `ci` 档案(`local` 档案下 identity 不要求,等于把身份核对关掉);
6. 运行模式:`only`(只跑了子集)的报告**不能**当作 CI 证据。
退出码只表达一件事:**这次运行的质量能否判定**。
· 报告读不到 / 核对不过 ⇒ 非 0(无从判定,绝不能报绿);
· 报告核对通过、结论是 failure ⇒ 0(作业在门禁那一步已经红了,这里不重复判)。
通知发不出去也只标注,不改结论。
用法:
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 # 只打印
python3 .gitea/scripts/ci_report.py --report ci-report.json --no-post
python3 .gitea/scripts/ci_report.py --self-test # 核对逻辑的反向自检
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import urllib.error
@@ -30,6 +36,20 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent.parent
# 清单与汇总逻辑**只应有一份**:直接 import 本仓的门禁实现(scripts/ci_checks.py),
# 而不是在这里再写一遍核对规则 —— 两份规则迟早会漂移,而漂移的表现是"门禁绿、上报却放行"。
GATE_PATH = ROOT / "scripts" / "ci_checks.py"
try:
sys.path.insert(0, str(ROOT / "scripts"))
import ci_checks # type: ignore # noqa: E402
from ci_checks import CHECK_MANIFEST, FULL_SHA, SUCCESS # noqa: E402
aggregate = ci_checks.aggregate
GATE_ERROR = ""
except Exception as _e: # 缺文件 / 语法错 / 导入期异常
CHECK_MANIFEST, FULL_SHA, SUCCESS = {}, re.compile(r"^$"), "success"
aggregate = None
GATE_ERROR = f"{GATE_PATH} 不可用:{_e}"
# bridge 的 status 只认 success/failure/cancelled,它的"失败步骤"判定是
# `status not in (success, skipped)`;把 not_run 归到 failure 是**保守**方向:
# 未运行绝不能被渲染成"通过"。
@@ -52,62 +72,225 @@ def git(*args: str) -> str:
return ""
def verify(rep: dict, expect_sha: str, in_ci: bool) -> tuple[str, list[str], list[str]]:
"""独立核对报告。返回 (重算的总体, 问题, 提示)。纯函数,--self-test 直接打它。"""
problems: list[str] = []
notes: list[str] = []
if rep.get("schema") != "ci-report/1":
problems.append(f"报告 schema 不是 ci-report/1:{rep.get('schema')!r}")
profile = rep.get("profile")
if profile not in ("local", "ci"):
problems.append(f"报告档案非法:{profile!r}")
elif in_ci and profile != "ci":
problems.append(f"运行环境是 CI,但报告档案是 {profile!r} —— local 档案下 identity 不要求,"
f"等于把身份核对关掉")
if rep.get("run_mode") != "full":
problems.append(f"报告的 run_mode 是 {rep.get('run_mode')!r} —— 只跑了子集的报告不能当 CI 证据")
sha = str(rep.get("commit_sha") or "")
if not FULL_SHA.match(sha):
problems.append(f"报告的 commit_sha 不是完整 40 位 SHA:{sha[:20]!r}")
elif expect_sha and sha != expect_sha:
problems.append(f"报告的 commit_sha {sha[:12]} != 事件 SHA {expect_sha[:12]} —— 归属对不上")
event_sha = str(rep.get("event_sha") or "")
if event_sha and not FULL_SHA.match(event_sha):
problems.append(f"报告的 event_sha 不是完整 40 位:{event_sha[:20]!r}")
elif event_sha and sha and event_sha != sha:
problems.append(f"报告里 event_sha {event_sha[:12]} 与 commit_sha {sha[:12]} 不一致")
manifest = rep.get("manifest")
if not isinstance(manifest, dict) or not manifest:
problems.append("报告里没有 manifest —— 没有清单就无法核对'必需项齐不齐'")
else:
mine = {cid: list(req) for cid, req in CHECK_MANIFEST.items()}
if {cid: list(req) for cid, req in manifest.items()} != mine:
diff = sorted(set(mine) ^ set(manifest)) or [
cid for cid in mine if list(manifest.get(cid) or []) != mine[cid]]
problems.append(f"报告里的清单与实现不一致(差异:{diff[:6]})—— 有一次读完的结论不能作数")
checks = rep.get("checks")
if not isinstance(checks, list):
problems.append("报告的 checks 不是数组")
checks = []
# 用**报告自带的清单**(已确认与实现一致)重算,而不是信 overall_status
declared = {cid: tuple(req) for cid, req in (manifest or {}).items()} or CHECK_MANIFEST
recomputed, agg_problems = aggregate(checks, profile if profile in ("local", "ci") else "ci", declared)
problems += agg_problems
claimed = rep.get("overall_status")
if recomputed != claimed and claimed != "not_run_only":
problems.append(f"报告自称 overall_status={claimed!r},按清单逐项重算是 {recomputed!r} —— "
f"汇总与清单不一致,不能采信")
elif claimed == "not_run_only":
problems.append("报告的 overall_status 是 not_run_only(只跑了子集)—— 不能作为 CI 证据")
if not problems:
notes.append(f"核对通过:{len(checks)} 项、档案 {profile}、SHA {sha[:12]}、"
f"总体 {recomputed}(与报告自称一致)")
return recomputed, problems, notes
def self_test() -> int:
if GATE_ERROR:
# 模板目录里没有 scripts/ci_checks.py(实现随项目走),所以自检跑不了 ——
# 明说,而不是拿一份空清单去跑出一堆莫名其妙的结论。
print(f"❌ 自检跑不了:{GATE_ERROR}", file=sys.stderr)
print(" 本脚本的核对逻辑依赖本仓的 scripts/ci_checks.py;请在项目仓里跑 --self-test。",
file=sys.stderr)
return 2
sha = "a" * 40
other = "b" * 40
good_checks = [{"id": cid, "status": SUCCESS, "reason": "", "required_in": list(req),
"duration_s": 1} for cid, req in CHECK_MANIFEST.items()]
# 自检里的"挑一项"要**动态取**清单里的第一项:硬编码某个 id(例如 tests-go)在模板仓/新工程里
# 根本不存在,自检会因为"找不到那一项"而自作聪明地通过或失败。
first_id = sorted(CHECK_MANIFEST)[0]
good = {
"schema": "ci-report/1", "profile": "ci", "run_mode": "full", "commit_sha": sha,
"event_sha": sha, "manifest": {c: list(r) for c, r in CHECK_MANIFEST.items()},
"checks": good_checks, "overall_status": SUCCESS,
}
cases = [
("合规报告 ⇒ 通过", good, sha, True, 0),
("短 SHA ⇒ 不过", {**good, "commit_sha": sha[:12], "event_sha": ""}, sha, True, 1),
("归错提交 ⇒ 不过", {**good, "commit_sha": other, "event_sha": other}, sha, True, 1),
# 下面这些会同时命中两条判据(例如"缺项"既触发清单核对,又让报告自称的 success 与重算不符),
# 所以期望 2 条 —— 两条都要报出来,不能只报一条就被掩盖。
("缺一项必需检查 ⇒ 不过(缺项 + 自称与重算不符)",
{**good, "checks": [c for c in good_checks if c["id"] != first_id]}, sha, True, 2),
("重复一项 ⇒ 不过(重复 + 自称与重算不符)",
{**good, "checks": good_checks + [good_checks[0]]}, sha, True, 2),
("清单之外的项 ⇒ 不过(未知项 + 自称与重算不符)",
{**good, "checks": good_checks + [{"id": "zz", "status": SUCCESS, "reason": ""}]}, sha, True, 2),
("清单被改过 ⇒ 不过(清单漂移 + 未知项 + 自称不符)",
{**good, "manifest": {k: list(v) for k, v in CHECK_MANIFEST.items() if k != "format"}}, sha, True, 3),
("自称成功但某项 failure ⇒ 不过(逐项 + 自称不符)",
{**good, "overall_status": SUCCESS,
"checks": [{**c, "status": "failure"} if c["id"] == first_id else c for c in good_checks]},
sha, True, 2),
("CI 里用 local 档案 ⇒ 不过", {**good, "profile": "local"}, sha, True, 1),
("只跑子集的报告 ⇒ 不过(run_mode + 结论不可用)",
{**good, "overall_status": "not_run_only", "run_mode": "only"}, sha, True, 2),
("没有 manifest ⇒ 不过", {k: v for k, v in good.items() if k != "manifest"}, sha, True, 1),
]
problems = []
for name, rep, expect, in_ci, want in cases:
_, got, _ = verify(rep, expect, in_ci)
if len(got) != want:
problems.append(f"{name}:期望 {want} 个问题,实际 {len(got)} 个 {got}")
if problems:
print("❌ 上报核对自检失败:", file=sys.stderr)
for p in problems:
print(f" · {p}", file=sys.stderr)
return 1
print(f"✅ 上报核对自检通过:{len(cases)} 个分支(短 SHA / 归错提交 / 缺项 / 重复 / 未知项 / "
f"清单漂移 / 自称成功 / 档案不符 / 子集报告 / 无清单 全部拦下)")
return 0
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")
ap.add_argument("--verify-only", action="store_true",
help="只核对报告、不发上报(预览发布前用;退出码=0 通过 / 1 不通过 / 2 核不了)")
ap.add_argument("--self-test", action="store_true")
args = ap.parse_args(argv)
if args.self_test:
return self_test()
if GATE_ERROR:
print(f"❌ 核对不了报告:{GATE_ERROR}", file=sys.stderr)
print(" 本脚本需要本仓的权威门禁实现(scripts/ci_checks.py)来做清单核对;"
"找不到就不能给出任何结论。", file=sys.stderr)
return 2 if args.verify_only else 1
in_ci = bool(os.environ.get("GITHUB_ACTIONS"))
expect_sha = (os.environ.get("GITHUB_SHA") or "").strip()
rpath = Path(args.report)
if not rpath.is_file():
print(f"❌ 读不到门禁报告 {rpath} —— 这次运行的质量无从判定,不能报绿", file=sys.stderr)
return 1
return 2 if args.verify_only else 1
try:
rep = json.loads(rpath.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
print(f"❌ 门禁报告解析失败({e})—— 不能报绿", file=sys.stderr)
return 1
return 2 if args.verify_only else 1
if not isinstance(rep, dict):
print("❌ 门禁报告不是 JSON 对象 —— 不能报绿", file=sys.stderr)
return 2 if args.verify_only else 1
overall = rep.get("overall_status") or "unknown"
if args.verify_only:
# 预览发布前的这一道:只回答"这份报告能不能采信",**不做任何网络请求**。
recomputed, vp, vn = verify(rep, expect_sha, in_ci)
print(f"── 发布前核对 —— 重算总体 {recomputed}|报告自称 {rep.get('overall_status')}"
f"|档案 {rep.get('profile')}|run_mode {rep.get('run_mode')}|"
f"SHA {(rep.get('commit_sha') or '')[:12]}")
for n in vn:
print(f" · {n}")
for p in vp:
print(f" ❌ {p}", file=sys.stderr)
print("✅ 报告可以采信" if not vp else "❌ 报告不可采信", file=sys.stderr if vp else sys.stdout)
return 1 if vp else 0
recomputed, problems, notes = verify(rep, expect_sha, in_ci)
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")
overall = "failure" if problems else recomputed
print(f"── 门禁结果 ── 总体 {overall}(策略 {rep.get('policy_revision')},档案 {rep.get('profile')})")
print(f"── 门禁报告核对 ── 档案 {rep.get('profile')}|"
f"提交 {(rep.get('commit_sha') or '')[:12]}|重算总体 {recomputed}"
f"{'' if not problems else '(核对不通过)'}")
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]}")
print(f" {mark} {c.get('id',''):<18} {str(c.get('status')):<8} {str(c.get('reason') or '')[:100]}")
for n in notes:
print(f" · {n}")
for p in problems:
print(f" ❌ {p}", file=sys.stderr)
# 质量**无法判定**(报告缺失/核对不过)时,不能给出任何"成功"结论
if problems:
print("❌ 汇总不可信/不完整 ⇒ 不能报绿(作业这次不算通过)", file=sys.stderr)
payload = {
# —— bridge 既有字段(保持兼容,不改 bridge)——
"repo": rep.get("repository") or os.environ.get("GITHUB_REPOSITORY", "unknown/unknown"),
"sha": sha,
"sha": rep.get("commit_sha") or "",
"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,
"--count", "HEAD~1..HEAD"),
"duration_s": rep.get("duration_s", "?"),
"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"),
"steps": [{"name": c.get("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,
"claimed_overall_status": rep.get("overall_status"),
"recomputed_overall_status": recomputed,
"profile": rep.get("profile"),
"event": rep.get("event"),
"run_mode": rep.get("run_mode"),
"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,
"manifest": rep.get("manifest"),
"problems": (rep.get("problems") or []) + problems,
"verification": {"ok": not problems, "problems": problems, "notes": notes,
"expected_sha": expect_sha, "reported_sha": rep.get("commit_sha")},
"notification_status": "not_attempted",
"deployed": False, # 本 workflow 只做 CI:没有部署,报告里也这么写
}
@@ -115,7 +298,7 @@ def main(argv: list[str]) -> int:
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
return 1 if problems else 0
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(base + "/api/ci/report", data=data, method="POST",
@@ -135,7 +318,7 @@ def main(argv: list[str]) -> int:
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
return 1 if problems else 0
if __name__ == "__main__":
+54 -78
View File
@@ -5,6 +5,14 @@ name: build
# ⚠️ 本 workflow **只做 CI,不做 CD**:这里没有 deploy:test / deploy-production,
# 也不启动 compose。部署是各项目自己的事(正本 §8:通用 CI 默认不生成部署作业)。
#
# ⚠️ 凭据处理(三条硬规矩):
# 1. **不把令牌写进 remote URL**:URL 里的凭据会落进 .git/config,还会出现在任何打印 remote
# 的地方;这里用 credential helper(只在那一次 git 调用里生效)。
# 2. **不把密钥放在 workflow 级 env**:那等于把 bridge 令牌发给每一个步骤(包括跑待测代码的
# 步骤)。谁需要谁在自己的步骤上声明 —— 见「静态预览」「上报 ci-bridge」。
# 3. **不用写权限的令牌**:检出只用 GITHUB_TOKEN(只读),不请求任何写操作。
# `permissions:` 在 Gitea 1.26.2 上按实例支持情况而定(不支持时会被忽略)。
#
# 实测结论(勿随意改动):
# 1. 不用任何第三方 action(本 runner 的 github_mirror 为空,取 action 会随机红)
# 2. 必须自己 clone —— Runner 不会自动检出代码,工作区初始为空(trap-6)
@@ -20,12 +28,12 @@ on:
workflow_dispatch:
env:
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LANG: C.UTF-8
LC_ALL: C.UTF-8
permissions:
contents: read
# 同一 ref 的新推送取消旧的运行。本 workflow 不含部署,取消它不会动任何线上东西;
# 生产部署是另一个 workflow,那种必须 cancel-in-progress: false —— 取消不是回滚。
concurrency:
@@ -37,37 +45,19 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- name: 检出代码(固定到事件完整 SHA)
- name: 检出代码(固定到事件完整 SHA;协议不降级;URL 不放凭据)
env:
GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -uo pipefail
SRV="${GITHUB_SERVER_URL:-http://192.168.50.223:3000}"
HP="${SRV#*://}"
BR="${GITHUB_REF_NAME:-${GITHUB_REF#refs/heads/}}"
EVENT_SHA="${GITHUB_SHA}"
cd "${GITHUB_WORKSPACE:-$(pwd)}"
rm -rf ./* .git 2>/dev/null || true
git init -q .
git remote add origin "http://x-access-token:${GIT_TOKEN}@${HP}/${GITHUB_REPOSITORY}.git"
# 先按分支浅取,再**核对**是不是事件那一个;不一致就改按精确 SHA 取
git fetch -q --depth 50 origin "$BR"
git checkout -q -B "$BR" FETCH_HEAD
if [ "$(git rev-parse HEAD)" != "$EVENT_SHA" ]; then
echo "⚠️ 分支 $BR 的 HEAD 已经不等于事件 SHA(有人在之后又推了一次)—— 改按精确 SHA 取"
git fetch -q --depth 50 origin "$EVENT_SHA" && git checkout -q --detach FETCH_HEAD \
|| { echo "❌ 取不到事件 SHA $EVENT_SHA"; exit 1; }
fi
GOT="$(git rev-parse HEAD)"
if [ "$GOT" != "$EVENT_SHA" ]; then
echo "❌ 检出 SHA 与事件 SHA 不一致:实际 $GOT / 事件 $EVENT_SHA"
echo " (门禁的 identity 项会再拦一次;这里先失败,避免拿错误的代码下结论)"
exit 1
fi
git rev-list --count FETCH_HEAD > "${GITHUB_WORKSPACE}/.ci-commits-count" 2>/dev/null \
|| echo 1 > "${GITHUB_WORKSPACE}/.ci-commits-count"
: > "${GITHUB_WORKSPACE}/.ci-preview-url"
echo "✅ 已检出 ${GITHUB_REPOSITORY} 分支 $BR @ ${GOT:0:12}(== 事件完整 SHA)"
git log -1 --format=' %h %an %s'
echo "CI_COMMITS_COUNT_FILE=${GITHUB_WORKSPACE}/.ci-commits-count" >> "$GITHUB_ENV"
# 检出逻辑单独成脚本(.gitea/scripts/ci_checkout.sh),这样它能被本地负例打到:
# ① 协议按 GITHUB_SERVER_URL 原样保留,**禁止 https 降级成 http**;
# ② remote URL 里不放凭据(凭据只走 credential helper);
# ③ 检出必须等于事件的**完整 SHA**;
# ④ 顺带把事件的 before 也取下来 —— 否则"本次推送范围 before..after"
# 在浅克隆里算不出来,范围校验只能要么报错要么静默收缩。
GITHUB_TOKEN="${GIT_TOKEN:-}" GITHUB_ENV="${GITHUB_ENV:-/dev/null}" \
bash .gitea/scripts/ci_checkout.sh
- name: 环境与工具链(缺什么一次性报全)
run: |
@@ -98,6 +88,17 @@ jobs:
fi
echo "工具链: $(go version) | node $(node -v) | npm $(npm -v) | $(python3 -V)"
- name: 断言门禁入口存在(缺了就是红,不许静默跳过)
run: |
set -uo pipefail
if [ ! -f scripts/ci_checks.py ]; then
echo "❌ 找不到权威门禁入口 scripts/ci_checks.py"
echo " 门禁入口是本仓唯一的检查实现;缺了就不能跑 —— 不接受'没有入口所以跳过'。"
exit 1
fi
make -n verify | head -3
echo "✅ 门禁入口就位:make verify"
- name: 权威门禁(make verify = scripts/ci_checks.py)
run: |
set +e; set +o pipefail
@@ -106,57 +107,30 @@ jobs:
echo "门禁退出码=$rc"
exit "$rc"
- name: 静态预览(只在全部必需检查通过后发布)
- name: 静态预览(**先核对完整报告**;核对不过一个 publish 请求都不发)
if: always()
env:
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
CI_REPORT: ${{ github.workspace }}/ci-report.json
run: |
set +e; set +o pipefail
REPORT="${GITHUB_WORKSPACE}/ci-report.json"
: > "${GITHUB_WORKSPACE}/.ci-preview-url"
OVERALL="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1])).get('overall_status','missing'))" "$REPORT" 2>/dev/null || echo unavailable)"
R_SHA="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1])).get('commit_sha',''))" "$REPORT" 2>/dev/null || echo '')"
if [ "$OVERALL" != "success" ]; then
echo "门禁总体=$OVERALL ⇒ 不发布预览(预览必须在全部必需检查通过之后)"
exit 0
fi
if [ -n "$R_SHA" ] && [ "$R_SHA" != "$GITHUB_SHA" ]; then
echo "❌ 报告里的 commit_sha $R_SHA != 事件 SHA $GITHUB_SHA ⇒ 不发布(发别人的产物就是错的产物)"
exit 0
fi
WEB=""
for d in web/dist dist build out public web/build frontend/dist; do
if [ -f "$d/index.html" ]; then WEB="$d"; break; fi
done
if [ -z "$WEB" ]; then echo "未发现静态网页产物目录(这是配置问题,不是通过)"; exit 0; fi
if [ -z "$(ls -A "$WEB" 2>/dev/null)" ]; then echo "产物目录为空,跳过预览发布"; exit 0; fi
TAR=/tmp/ci-web.tgz
# ⚠️ 不要产生 `.` 根成员(tar -C dir . 会写 `.` 与 `./x`):先 cd 再用通配展开(trap-9)
( cd "$WEB" && { shopt -s dotglob; tar -czf "$TAR" *; } ) || { echo "打包失败"; exit 0; }
if ! tar -tzf "$TAR" | grep -qx 'index.html'; then
echo "❌ 包里没有 index.html ⇒ 发出去也是个 404 的预览,不发"; exit 0
fi
B="${BRIDGE_URL:-}"
for cand in "$B" "http://172.17.0.1:8899" "http://192.168.50.134:8899" "http://100.92.49.78:8899"; do
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
done
if [ -z "$B" ]; then echo "❌ 没有可达的 ci-bridge ⇒ 不发预览(打包成功不等于预览发出去了)"; exit 0; fi
CODE="$(curl -sS -m 90 -o /tmp/ci-pub.json -w '%{http_code}' -X POST \
"$B/api/ci/publish?repo=${GITHUB_REPOSITORY}&sha=${GITHUB_SHA}" \
-H "X-CI-Token: ${BRIDGE_TOKEN}" -H 'Content-Type: application/gzip' \
--data-binary @"$TAR")"
echo "publish HTTP $CODE $(cat /tmp/ci-pub.json)"
[ "$CODE" = "200" ] || { echo "❌ 发布接口返回 $CODE ⇒ 不发这条预览"; exit 0; }
for key in url url_tailscale; do
U="$(python3 -c "import json,sys;print(json.load(open('/tmp/ci-pub.json')).get(sys.argv[1],''))" "$key")"
[ -n "$U" ] || { echo "⚠️ 报告里 $key 为空"; continue; }
C="$(curl -s -o /dev/null -w '%{http_code}' -m 10 "$U")"
echo "预览探测 $key: $U → $C"
[ "$C" = "200" ] || { echo "❌ $U 不是 200(通知里给出打不开的链接等于没给)"; exit 0; }
[ "$key" = "url" ] && echo "$U" > "${GITHUB_WORKSPACE}/.ci-preview-url"
done
echo "✅ 预览已发布,且报告里的每个地址都 200"
# 顺序钉死在这里:ci_preview.py 内部**先**调 ci_report.verify()(与上报步骤
# 同一份核对逻辑:清单齐不齐 / 重复 / 未知项 / 完整 SHA / 档案 / 运行模式),
# 有任何问题就一个 publish 请求都不发。
# 旧写法只读 overall_status + SHA,缺项报告会**先发出去**、等到通知步骤才发现 ——
# 预览发出去收不回来(URL 会被打开、会被转群),那时再红也撤不回来。
python3 .gitea/scripts/ci_preview.py
rc=$?
[ "$rc" = "0" ] || echo "❌ 预览步骤非 0($rc):报告核对不过或读不到报告"
exit "$rc"
- name: 上报 ci-bridge(通知失败不改变质量结果)
- name: 上报 ci-bridge(核对报告 + 通知失败不改变质量结果)
if: always()
env:
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
run: |
set +e; set +o pipefail
B="${BRIDGE_URL:-}"
@@ -164,9 +138,11 @@ jobs:
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
done
echo "使用 ci-bridge: ${B:-(不可达)}"
# 这一步**先独立核对报告**(清单齐不齐 / 完整 SHA / 档案 / 自称是否与重算一致),
# 再上报;核对不过 ⇒ 非 0(质量无从判定,绝不能报绿)。
CI_BRIDGE_RESOLVED="$B" python3 .gitea/scripts/ci_report.py
rc=$?
if [ "$rc" -ne 0 ]; then
echo "❌ 上报脚本非 0 退出:它只在'汇总本身不可用'时这样 —— 这次运行的质量无从判定"
echo "❌ 上报脚本非 0 退出:报告核对不过或读不到 —— 这次运行的质量无从判定"
fi
exit "$rc"