From 46cd30e4f9b236f8dd02acfa7307cf322c86c0df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Mon, 12 Oct 2026 00:10:51 +0800 Subject: [PATCH] =?UTF-8?q?ci(workflow):=20=E5=8D=95=E4=BD=9C=E4=B8=9A=20+?= =?UTF-8?q?=20=E5=9B=BA=E5=AE=9A=E4=BA=8B=E4=BB=B6=E5=AE=8C=E6=95=B4=20SHA?= =?UTF-8?q?=20+=20=E9=A2=84=E8=A7=88=E9=97=A8=E7=A6=81=20+=20=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E6=97=81=E8=B7=AF=EF=BC=9B=E5=88=A0=E6=8E=89=E5=81=87?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E7=9A=84=E9=83=A8=E7=BD=B2=E5=8D=A0=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来的 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(不能报绿)。部署未涉及,本仓**未部署**。 --- .gitea/scripts/ci_report.py | 162 +++++++++++++++++-------- .gitea/workflows/build.yml | 233 +++++++++++++++++------------------- 2 files changed, 222 insertions(+), 173 deletions(-) diff --git a/.gitea/scripts/ci_report.py b/.gitea/scripts/ci_report.py index 42dcd5d..01bf3ca 100755 --- a/.gitea/scripts/ci_report.py +++ b/.gitea/scripts/ci_report.py @@ -1,82 +1,142 @@ #!/usr/bin/env python3 -"""把 CI 结果上报给主机侧 ci-bridge(bridge 负责落报告页 + 推微信)。""" +"""把门禁报告上报给主机侧 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, default=""): +def rd(path: str, default: str = "") -> str: try: - with open(path, encoding="utf-8") as fh: - return fh.read().strip() - except Exception: + return Path(path).read_text(encoding="utf-8").strip() + except OSError: return default -def git(*args): +def git(*args: str) -> str: try: - return subprocess.run(["git"] + list(args), capture_output=True, + return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True).stdout.strip() - except Exception: + except OSError: return "" -def main(): - repo = os.environ.get("GITHUB_REPOSITORY", "unknown/unknown") - sha = rd("/tmp/ci-sha") or git("rev-parse", "HEAD") - branch = os.environ.get("GITHUB_REF_NAME") or \ - os.environ.get("GITHUB_REF", "").replace("refs/heads/", "") - gate = rd("/tmp/ci-gate-status", "skipped") - build = rd("/tmp/ci-build-status", "failure") - status = "success" if (gate == "success" and build == "success") else "failure" - - log = rd("/tmp/ci-build-tail") - if gate != "success": - log = "提交信息规范校验未通过\n" + log +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: - count = int(rd("/tmp/ci-commits-count", "1") or 1) - except Exception: - count = 1 + rep = json.loads(rpath.read_text(encoding="utf-8")) + except json.JSONDecodeError as e: + print(f"❌ 门禁报告解析失败({e})—— 不能报绿", file=sys.stderr) + return 1 - rep = { - "repo": repo, + 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": branch, + "branch": rep.get("branch") or os.environ.get("GITHUB_REF_NAME", ""), "actor": os.environ.get("GITHUB_ACTOR", ""), - "status": status, + "workflow": os.environ.get("GITHUB_WORKFLOW", "build"), + "status": BRIDGE_STATUS.get(overall, "failure"), "commit_subject": git("log", "-1", "--format=%s"), - "commit_count": count, - "duration_s": rd("/tmp/ci-duration", "?"), - "preview_url": rd("/tmp/ci-preview-url"), - "log": log[-3500:], - "steps": [ - {"name": "提交信息规范校验", "status": gate}, - {"name": "编译与自检", "status": build}, - ], + "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:没有部署,报告里也这么写 } - if rep["preview_url"]: - print("\U0001F310 网页预览: %s" % rep["preview_url"]) - print("结果: %s | 构建: %s | 提交闸门: %s | 耗时: %ss" - % (status, build, gate, rep["duration_s"])) - base = os.environ.get("CI_BRIDGE_RESOLVED", "").rstrip("/") - if not base: - print("跳过上报:未找到可达的 ci-bridge") + 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(rep, 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", "")}) + + 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: - print("\u2705 已上报 ci-bridge:", resp.read().decode()[:300]) - except Exception as e: - print("\u274c 上报 ci-bridge 失败:", e) + 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()) + raise SystemExit(main(sys.argv[1:])) \ No newline at end of file diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 77efea3..3aeeb32 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -1,13 +1,18 @@ name: build -# 提交 -> 本机 Runner 编译 -> 微信通知 + 网页预览 +# 提交 → 本机 Runner 跑**唯一权威门禁**(make verify)→ 全部必需检查通过才发预览 → 通知 +# +# ⚠️ 本 workflow **只做 CI,不做 CD**:这里没有 deploy:test / deploy-production, +# 也不启动 compose。部署是各项目自己的事(正本 §8:通用 CI 默认不生成部署作业)。 +# # 实测结论(勿随意改动): -# 1. 不用任何第三方 action(作业容器不联网拉 action,全用镜像自带工具) -# 2. 必须自己 clone —— Runner 不会自动检出代码,工作区初始为空 -# 3. act 以 `bash -e -o pipefail` 执行每步 -> 禁止 `cmd | head` 这种会 SIGPIPE 提前退出的管道 +# 1. 不用任何第三方 action(本 runner 的 github_mirror 为空,取 action 会随机红) +# 2. 必须自己 clone —— Runner 不会自动检出代码,工作区初始为空(trap-6) +# 3. act 以 `bash -e -o pipefail` 执行每步 → 禁止 `cmd | head` 这种会 SIGPIPE 提前退出的管道 # 4. 工具链来自主机只读挂载 /opt/citools(go/uv),缓存写 /opt/citools-cache # 5. bridge 从容器内走 docker 网关 172.17.0.1:8899(实测可达) -# 6. 校验/上报逻辑放在 .gitea/scripts/ 下的脚本里,YAML 只负责调用(避免 YAML 里嵌深缩进代码) +# 6. 校验逻辑放仓内脚本(scripts/ci_checks.py + .gitea/scripts/*.py),YAML 只负责调用 +# 7. 检出固定到**事件完整 SHA**,不是"当时那个分支 HEAD"(分支随时会前进) on: push: branches: @@ -18,7 +23,11 @@ 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 +# 同一 ref 的新推送取消旧的运行。本 workflow 不含部署,取消它不会动任何线上东西; +# 生产部署是另一个 workflow,那种必须 cancel-in-progress: false —— 取消不是回滚。 concurrency: group: build-${{ github.ref }} cancel-in-progress: true @@ -28,156 +37,136 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 40 steps: - - name: 检出代码 + - name: 检出代码(固定到事件完整 SHA) 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 - git rev-parse HEAD > /tmp/ci-sha - date +%s > /tmp/ci-start - : > /tmp/ci-preview-url - echo skipped > /tmp/ci-build-status - git rev-list --count FETCH_HEAD > /tmp/ci-commits-count 2>/dev/null || echo 1 > /tmp/ci-commits-count - echo "已检出 ${GITHUB_REPOSITORY} 分支 ${BR}" + 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" - - name: 提交信息规范校验 - run: python3 .gitea/scripts/ci_gate.py + - name: 环境与工具链(缺什么一次性报全) + run: | + set -uo pipefail + { + echo "PATH=/opt/citools/go/bin:/opt/citools/bin:$PATH" + echo "GOCACHE=/opt/citools-cache/gocache" + echo "GOMODCACHE=/opt/citools-cache/gomod" + echo "GOPATH=/opt/citools-cache/gopath" + echo "UV_CACHE_DIR=/opt/citools-cache/uv" + echo "GOPROXY=https://goproxy.cn,direct" + echo "GOTOOLCHAIN=local" + echo "npm_config_cache=/opt/citools-cache/npm" + echo "CI_GATE_LOG=${GITHUB_WORKSPACE}/ci-gate.log" + echo "CI_REPORT=${GITHUB_WORKSPACE}/ci-report.json" + } >> "$GITHUB_ENV" + mkdir -p /opt/citools-cache/gocache /opt/citools-cache/gomod /opt/citools-cache/gopath \ + /opt/citools-cache/uv /opt/citools-cache/npm 2>/dev/null || true + export PATH="/opt/citools/go/bin:/opt/citools/bin:$PATH" + miss="" + for t in make python3 node npm go gofmt git curl tar sha256sum; do + command -v "$t" >/dev/null 2>&1 || miss="$miss $t" + done + if [ -n "$miss" ]; then + echo "❌ 作业镜像里缺工具:$miss" + echo " 处理:补镜像/挂载,或把该检查从清单里删掉并写明理由 —— 不允许运行时静默跳过。" + exit 1 + fi + echo "工具链: $(go version) | node $(node -v) | npm $(npm -v) | $(python3 -V)" - - name: 编译与自检 + - name: 权威门禁(make verify = scripts/ci_checks.py) run: | set +e; set +o pipefail - LOG=/tmp/ci-build.log; : > "$LOG" - run() { echo "-- $* --"; "$@" 2>&1 | tee -a "$LOG"; return "${PIPESTATUS[0]}"; } - runin(){ local d="$1"; shift; echo "-- ($d) $* --"; ( cd "$d" && "$@" ) 2>&1 | tee -a "$LOG"; return "${PIPESTATUS[0]}"; } + make verify 2>&1 | tee "${GITHUB_WORKSPACE}/ci-gate.log" + rc=${PIPESTATUS[0]} # pipefail 已关,用 PIPESTATUS 取真退出码 + echo "门禁退出码=$rc" + exit "$rc" - export PATH=/opt/citools/go/bin:/opt/citools/bin:$PATH - export GOCACHE=/opt/citools-cache/gocache GOMODCACHE=/opt/citools-cache/gomod UV_CACHE_DIR=/opt/citools-cache/uv - export GOPROXY=https://goproxy.cn,direct GOTOOLCHAIN=local GOFLAGS=-mod=mod GOPATH=/opt/citools-cache/gopath - mkdir -p "$GOCACHE" "$GOMODCACHE" "$UV_CACHE_DIR" "$GOPATH" 2>/dev/null - - echo "工具链: $(go version 2>&1) | $(uv --version 2>&1) | $(node -v 2>&1) | $(python3 -V 2>&1)" - fail=0; ran="" - - if [ -f go.mod ]; then - ran="$ran go" - run go build ./... || fail=1 - run go vet ./... || fail=1 - run go test ./... || fail=1 - fi - - if [ -f pyproject.toml ] || [ -f requirements.txt ] || [ -f setup.py ]; then - ran="$ran python" - if grep -qE '^check:' Makefile 2>/dev/null; then - run make UV=uv check || fail=1 - else - run uv sync || fail=1 - run uv run pytest -q || fail=1 - fi - fi - - WEBPKG="" - for p in package.json web/package.json frontend/package.json ui/package.json; do - if [ -f "$p" ]; then WEBPKG="$p"; break; fi - done - if [ -n "$WEBPKG" ]; then - ran="$ran node" - D="$(dirname "$WEBPKG")" - if [ -f "$D/package-lock.json" ]; then - runin "$D" npm ci || fail=1 - else - runin "$D" npm install || fail=1 - fi - if grep -q '"build"[[:space:]]*:' "$WEBPKG" 2>/dev/null; then - runin "$D" npm run build || fail=1 - fi - fi - - if [ -z "$ran" ] && [ -f Makefile ]; then - ran="$ran make" - run make || fail=1 - fi - if [ -z "$ran" ]; then - echo "未识别到构建入口(go.mod / pyproject.toml / package.json / Makefile 都没有),跳过编译" - fi - - if [ "$fail" -eq 0 ]; then echo success > /tmp/ci-build-status; else echo failure > /tmp/ci-build-status; fi - tail -c 4000 "$LOG" > /tmp/ci-build-tail - echo "构建结果: $(cat /tmp/ci-build-status)(识别:$ran)" - [ "$fail" -eq 0 ] || exit 1 - - - name: 版本与变更记录契约 - run: | - set -eu - export PATH=/opt/citools/go/bin:/opt/citools/bin:$PATH - export GOCACHE=/opt/citools-cache/gocache GOMODCACHE=/opt/citools-cache/gomod GOPATH=/opt/citools-cache/gopath - export GOPROXY=https://goproxy.cn,direct GOTOOLCHAIN=local GOFLAGS=-mod=mod - - # ① 变更记录结构:每个已发布版本都必须有「改了什么」「怎么验收」两节 - python3 scripts/check_changelog.py - - # ② 版本号的唯一来源 - V="$(python3 scripts/version.py)" - echo "CHANGELOG 顶部版本: $V" - - # ③ 契约:注入进二进制的号必须等于它 - OUT="$(go test -ldflags "-X knowledge-governance/internal/version.Number=$V" \ - -run TestNumberMatchesChangelog -v ./internal/version/... 2>&1)" - printf '%s\n' "$OUT" - - # ⚠️ 被跳过的断言等于没有断言:这里显式断言它真的 PASS 了。 - # 用 case 而不是 `echo | grep -q` —— 后者在 pipefail 下会被 SIGPIPE - # 谎报失败(docs/agents/traps.md trap-7)。 - case "$OUT" in - *"--- PASS: TestNumberMatchesChangelog"*) echo "✅ 版本契约成立:注入的版本 == CHANGELOG 顶部" ;; - *) echo "❌ 版本契约没有真正执行(被跳过或没跑到)—— 缺 -ldflags,或 CHANGELOG 解析失败"; exit 1 ;; - esac - - - name: 发布网页预览 + - name: 静态预览(只在全部必需检查通过后发布) if: always() run: | set +e; set +o pipefail - : > /tmp/ci-preview-url - if [ "$(cat /tmp/ci-build-status 2>/dev/null)" != "success" ]; then - echo "构建未成功,跳过预览发布"; exit 0 + 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 - tar -czf /tmp/ci-web.tgz -C "$WEB" . || { echo "打包失败"; exit 0; } + 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 + if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi done - SHA="$(cat /tmp/ci-sha)" - echo "发布预览到 $B(产物目录 $WEB)" - curl -sS -m 90 -X POST "$B/api/ci/publish?repo=${GITHUB_REPOSITORY}&sha=${SHA}" -H "X-CI-Token: ${BRIDGE_TOKEN}" -H 'Content-Type: application/gzip' --data-binary @/tmp/ci-web.tgz -o /tmp/ci-pub.json - cat /tmp/ci-pub.json; echo - URL="$(python3 -c "import json;print(json.load(open('/tmp/ci-pub.json')).get('url',''))" 2>/dev/null)" - if [ -n "$URL" ]; then echo "$URL" > /tmp/ci-preview-url; echo "网页预览: $URL"; fi + 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" - - name: 通知微信 + - name: 上报 ci-bridge(通知失败不改变质量结果) if: always() run: | set +e; set +o pipefail 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 + if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi done - echo "使用 ci-bridge: $B" - S=$(date +%s); T=$(cat /tmp/ci-start 2>/dev/null); [ -n "$T" ] || T=$S - echo $((S - T)) > /tmp/ci-duration + echo "使用 ci-bridge: ${B:-(不可达)}" CI_BRIDGE_RESOLVED="$B" python3 .gitea/scripts/ci_report.py + rc=$? + if [ "$rc" -ne 0 ]; then + echo "❌ 上报脚本非 0 退出:它只在'汇总本身不可用'时这样 —— 这次运行的质量无从判定" + fi + exit "$rc" \ No newline at end of file