Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f1b1133ab | ||
|
|
76cc20d9d8 | ||
|
|
edb04bfdd9 | ||
|
|
982c2cdb77 | ||
|
|
86a260c646 | ||
|
|
eff273f7f2 | ||
|
|
e739f4504a |
No files matched your search
+4
-26
@@ -1,26 +1,4 @@
|
||||
# Rust 构建与本地缓存
|
||||
/target/
|
||||
/.cache/
|
||||
/dist/
|
||||
/bin/
|
||||
|
||||
# 本地 tool bundle 与测试输出
|
||||
**/*.analysis.json.tmp
|
||||
**/*.ast.json.tmp
|
||||
*.tmp
|
||||
|
||||
# 真实浏览器测试
|
||||
/tests/browser/node_modules/
|
||||
/tests/browser/artifacts/
|
||||
/tests/browser/screenshots/
|
||||
|
||||
# Python 辅助脚本(CI/测试胶水)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# 本地配置与编辑器
|
||||
.env
|
||||
.env.*
|
||||
.cargo-home/
|
||||
.DS_Store
|
||||
*.swp
|
||||
/target
|
||||
/dist
|
||||
/out
|
||||
dist/
|
||||
@@ -0,0 +1,13 @@
|
||||
# Unified Woodpecker CI for a Rust component.
|
||||
#
|
||||
# One published `marqdo-ci-rust` image (Rust 1.100, rustfmt/clippy, warm cargo
|
||||
# cache, released CLI/Bundle) is reused. No per-repository toolchain download or
|
||||
# CLI rebuild; the repository only runs its own CI entry.
|
||||
when:
|
||||
event: [push, pull_request, manual]
|
||||
|
||||
steps:
|
||||
test:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
|
||||
commands:
|
||||
- scripts/ci.sh
|
||||
@@ -0,0 +1,26 @@
|
||||
when:
|
||||
- event: [tag, manual]
|
||||
steps:
|
||||
publish:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
GITEA_PUBLISH_TOKEN:
|
||||
from_secret: gitea_publish_token
|
||||
COMPONENT_ID: web-preview
|
||||
REPOSITORY: cflmy/marqdo-web-preview
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${GITEA_PUBLISH_TOKEN:?}"
|
||||
test -n "${CI_COMMIT_TAG:?}"
|
||||
export SOURCE_SHA="${CI_COMMIT_SHA}"
|
||||
export VERSION="${CI_COMMIT_TAG#v}"
|
||||
export COMPONENT_ID=web-preview
|
||||
export REPOSITORY=cflmy/marqdo-web-preview
|
||||
sh scripts/package.sh
|
||||
ARCHIVE="dist/marqdo-web-preview-${VERSION}-source.tar.gz"
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo cflmy/marqdo-web-preview --tag "${CI_COMMIT_TAG}" --target "$SOURCE_SHA" --prerelease \
|
||||
--body "Automated source release for web-preview ${CI_COMMIT_TAG}." \
|
||||
--asset "$ARCHIVE" --asset "${ARCHIVE}.sha256" --asset dist/release-evidence.json \
|
||||
--evidence-out dist/gitea-publish-result.json
|
||||
@@ -0,0 +1,12 @@
|
||||
when:
|
||||
event: [release]
|
||||
steps:
|
||||
notify:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
environment:
|
||||
WOODPECKER_NOTIFY_TOKEN:
|
||||
from_secret: woodpecker_notify_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
python3 scripts/release/notify_root.py --hint-component web-preview --hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -1,5 +1,10 @@
|
||||
# AGENTS.md:marqdo-web-preview 维护指引
|
||||
|
||||
<!-- marqdo:repo-conventions v1 -->
|
||||
|
||||
生态级仓库开发规范:https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md
|
||||
|
||||
|
||||
本文件约束在本仓库工作的维护者与 AI Coding Agent。仓库状态为 `planned`:只有文档,
|
||||
没有实现源码、`Cargo.toml`/`Cargo.lock`、`tool.json` 实体、CI 入口或发布制品,也没有
|
||||
接入 `marqdo-ext-web` 的 gitlink。
|
||||
|
||||
Generated
+114
@@ -0,0 +1,114 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-web-design"
|
||||
version = "0.1.0"
|
||||
source = "git+https://git.cflmy.cn/cflmy/marqdo-web-design?rev=1b6607fd3cc09801b4f6eacd2fba547caa0ec637#1b6607fd3cc09801b4f6eacd2fba547caa0ec637"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-web-preview"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"marqdo-web-design",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "marqdo-web-preview"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Offline Web design preview and the unique marqdo web Tool"
|
||||
|
||||
[dependencies]
|
||||
marqdo-web-design = { git = "https://git.cflmy.cn/cflmy/marqdo-web-design", rev = "1b6607fd3cc09801b4f6eacd2fba547caa0ec637" }
|
||||
serde_json = "1"
|
||||
@@ -4,7 +4,7 @@
|
||||
`marqdo-web-design` 已经解释好的设计模型,生成不依赖服务器、可用本地浏览器直接打开的
|
||||
离线 HTML 原型,并以 `web` 命令注册为生态中唯一的 Web Tool 入口。
|
||||
|
||||
- **状态:`planned`**。本仓库目前只有文档:没有实现源码、`Cargo.toml`/`Cargo.lock`、
|
||||
- **状态:`active`**。已实现独立 executable、`tool.json`、离线预览与 `scripts/ci.sh`;
|
||||
`tool.json` 实体、`scripts/ci.sh`、CI 流水线或发布制品,也没有接入领域仓库
|
||||
`marqdo-ext-web` 的子 gitlink。本文中“将/目标”描述的是接入后必须满足的合同,不是
|
||||
已实现能力,也不是已验收结果。
|
||||
@@ -16,8 +16,8 @@
|
||||
- **上游实现**:[marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design)
|
||||
(唯一设计解释实现,Rust library;本仓库通过其公开 API 消费设计模型)。
|
||||
- **仓库远端**:`https://git.cflmy.cn/cflmy/marqdo-web-preview`。远端已创建并推送
|
||||
初始开发文档;领域 `components.toml` 已登记为 planned,开发工单也已建立;gitlink、
|
||||
独立 CI 与发布仍属于后续激活工作,当前 `planned`。
|
||||
实现/证据;领域 `components.toml` 已登记为 active 并固定 gitlink;真实浏览器/资产等
|
||||
剩余验收项在组件工单跟踪,不得把未验证项写成 PASS。
|
||||
|
||||
## 职责与禁止
|
||||
|
||||
@@ -136,3 +136,11 @@ CSP、资产校验归本仓库;表头未识别、Link 精确绑定、`not_load
|
||||
Analysis 字段或 resolver 公共合同缺陷归 CLI;作者面语义冲突或新增通用能力由
|
||||
`marqdo-ext-web` 走 ADR 并配对 Design/Preview 候选。工单模板与状态流以 Web 领域规范
|
||||
§12.2 与领域开发指南为准。
|
||||
|
||||
## 实现进展(WEB-02 首个候选)
|
||||
|
||||
- 独立 executable + `tool.json`,注册唯一 `marqdo web` 命令;消费固定 git revision 的 `marqdo-web-design` 公开 API(`Cargo.lock` 锁定),不复制 Markdown/设计解析。
|
||||
- `web check|preview|handoff`:check 输出模型摘要;preview 生成离线单文件 HTML(CSP、原型标识、场景面板、模拟按钮、重置、构建摘要);handoff 原子写 Markdown 交付。
|
||||
- 输出目录/文件默认不覆盖;staging→rename 原子发布;拒绝符号链接目标;退出码 0/1/2 与 stderr 诊断。
|
||||
- `scripts/ci.sh` 用真实 CLI 安装/运行/卸载 `web` Tool 并验证 CLI 二进制不变。
|
||||
- 未完成:真实浏览器行为与 responsive 验收、图片/本地 raster 资产、完整安全负例矩阵、超时/预算边界、WEB-05 冷安装。证据见 [docs/evidence/WEB-02-preview-candidate.md](docs/evidence/WEB-02-preview-candidate.md)。
|
||||
@@ -0,0 +1,39 @@
|
||||
# WEB-02 Preview 候选证据(离线制品 / 唯一 web Tool / 有限场景)
|
||||
|
||||
日期:2026-11-27。责任仓:`marqdo-web-preview`;工单:[marqdo-web-preview#1](https://git.cflmy.cn/cflmy/marqdo-web-preview/issues/1)(WEB-02);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
|
||||
|
||||
本文件记录 WEB-02 的**首个候选**:唯一 `marqdo web` Tool 的 check/preview/handoff 入口、离线静态预览、有限场景、CSP 与原子发布。真实浏览器行为验收、资产复制与完整安全矩阵尚未完成,未在此声明。
|
||||
|
||||
## 输入身份
|
||||
|
||||
| 对象 | 身份 |
|
||||
| --- | --- |
|
||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e...` |
|
||||
| Design 依赖 | `marqdo-web-design@1b6607fd3cc09801b4f6eacd2fba547caa0ec637`(WEB-03 handoff/图/切片)(`Cargo.lock` 固定 git rev;不是 `../design` 路径依赖) |
|
||||
| 平台 | Linux x86_64(本机验证) |
|
||||
|
||||
## 执行
|
||||
|
||||
```sh
|
||||
MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
||||
```
|
||||
|
||||
脚本真实执行:fmt/clippy → 构建 release → 生成 `tool.json` bundle → `marqdo tool install` → `marqdo web check/preview/handoff`(fixture 工程)→ 覆盖拒绝 → CLI 二进制 SHA 不变 → `tool remove web`。
|
||||
|
||||
## 已验证(PASS)
|
||||
|
||||
- **唯一入口**:`tool.json`(`command: web`)+ 独立 executable;`marqdo web check|preview|handoff ENTRY --unit ANCHOR [--root] [--out] [--theme]`。
|
||||
- **离线制品**:`preview` 生成单个 `index.html`(不启动服务、无网络请求),`file://` 可打开;CSP `default-src 'none'; style-src/script-src sha256; img-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'`。
|
||||
- **有限场景**:Design 模型中的场景面板与交互按钮渲染为内联固定脚本(CSP hash 放行);点击仅切换预渲染面板,无定时器/网络/eval;含“重置原型”。
|
||||
- **原型标识与摘要**:页首与摘要可见“原型 / 模拟”,列 root 与参与源 `sha256`;不显示完整 Analysis 或绝对路径。
|
||||
- **安全渲染**:Design 的 `ContentBlock` 文本全部 HTML 转义;raw HTML 显示为 inert 文本;不输出 `href="javascript:`、无外部 script。
|
||||
- **发布安全**:输出目录/文件必须不存在;staging 私有目录校验后原子 rename;失败清理;拒绝符号链接目标。
|
||||
- **退出码**:设计错误 1、参数/环境/IO 错误 2、成功 0;诊断写 stderr。
|
||||
- **Tool 生命周期**:真实 CLI `tool install` / 运行 / `tool remove web`;CLI 二进制 SHA 前后不变。
|
||||
|
||||
## 未验证 / 后续(不隐藏)
|
||||
|
||||
- WEB-03 交付内容由图/切片/漂移提供,Preview 已验证相对链接;真实浏览器(Playwright/file://)行为、responsive 390px 无横向溢出、按钮实际状态切换的 DOM 断言未执行;当前只有静态制品断言。
|
||||
- 图片/本地 raster 资产复制、魔数/大小校验、远端图片文本占位尚未实现(当前不渲染图片)。
|
||||
- 完整安全负例矩阵(`</script>`/Unicode/双引号 fixture、输出预算边界、超时/进程限制)未系统性覆盖。
|
||||
- 冷安装(root 生态 `web` Tool 与 WEB-05)未开始;WEB-04 生产交付试验未开始。
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# WEB-02 independent entry: real CLI, installed web Tool, offline artifact checks.
|
||||
set -eu
|
||||
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
|
||||
cd "$(dirname "$0")/.."
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --all-targets --locked -- -D warnings
|
||||
scripts/package.sh
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
export MARQDO_TOOL_HOME="$work/tool-home"
|
||||
cli_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||
"$MARQDO_BIN" tool install "$PWD/dist/marqdo-web-preview/tool.json"
|
||||
"$MARQDO_BIN" web check tests/fixture/index.mq.md --unit 工作台
|
||||
preview="$work/preview"
|
||||
"$MARQDO_BIN" web preview tests/fixture/index.mq.md --unit 工作台 --out "$preview" --theme light
|
||||
test -f "$preview/index.html"
|
||||
grep -q "Content-Security-Policy" "$preview/index.html"
|
||||
grep -q "default-src 'none'" "$preview/index.html"
|
||||
grep -q "原型 / 模拟" "$preview/index.html"
|
||||
grep -q "raw HTML as inert text" "$preview/index.html"
|
||||
grep -q "模拟保存" "$preview/index.html"
|
||||
grep -q "data-scenario" "$preview/index.html"
|
||||
! grep -q "href=\"javascript:" "$preview/index.html"
|
||||
! grep -q "<script src" "$preview/index.html"
|
||||
handoff="$work/handoff.md"
|
||||
"$MARQDO_BIN" web handoff tests/fixture/index.mq.md --unit 工作台 --out "$handoff"
|
||||
test -s "$handoff"
|
||||
grep -q "Design handoff" "$handoff"
|
||||
grep -q "components/nav.mq.md#导航" "$handoff"
|
||||
python3 - "$handoff" <<'PY'
|
||||
import pathlib, sys, re
|
||||
text = pathlib.Path(sys.argv[1]).read_text()
|
||||
assert "](" in text
|
||||
for target in re.findall(r"\]\(([^)]+)\)", text):
|
||||
assert not target.startswith("/"), target
|
||||
assert not target.startswith("file:"), target
|
||||
print("handoff links are relative")
|
||||
PY
|
||||
if "$MARQDO_BIN" web preview tests/fixture/index.mq.md --unit 工作台 --out "$preview" 2>/dev/null; then
|
||||
echo "preview overwrote an existing directory" >&2
|
||||
exit 1
|
||||
fi
|
||||
cli_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||
test "$cli_before" = "$cli_after"
|
||||
"$MARQDO_BIN" tool remove web
|
||||
echo "PASS: marqdo web Tool check/preview/handoff/remove"
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# Deterministic source archive + release-evidence.json for this component.
|
||||
#
|
||||
# Required env:
|
||||
# COMPONENT_ID catalog id (e.g. std-text)
|
||||
# REPOSITORY owner/name (e.g. cflmy/marqdo-std-text)
|
||||
# Optional:
|
||||
# VERSION without leading v (default: derived from CI_COMMIT_TAG)
|
||||
# SOURCE_SHA full commit (default: HEAD)
|
||||
# OUT_DIR default dist
|
||||
# DEPENDENCY repeatable write_evidence dependency specs via env DEP_ARGS
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
COMPONENT_ID=${COMPONENT_ID:?COMPONENT_ID is required}
|
||||
REPOSITORY=${REPOSITORY:?REPOSITORY is required}
|
||||
SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)}
|
||||
OUT_DIR=${OUT_DIR:-dist}
|
||||
TAG=${CI_COMMIT_TAG:-${TAG:-}}
|
||||
if [ -n "${VERSION:-}" ]; then
|
||||
:
|
||||
elif [ -n "$TAG" ]; then
|
||||
VERSION=${TAG#v}
|
||||
else
|
||||
echo "package.sh: set VERSION or CI_COMMIT_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
TAG=${TAG:-v$VERSION}
|
||||
|
||||
python3 "$ROOT/scripts/release/package_source.py" \
|
||||
--root "$ROOT" \
|
||||
--component-id "$COMPONENT_ID" \
|
||||
--version "$VERSION" \
|
||||
--out-dir "$OUT_DIR"
|
||||
|
||||
ARCHIVE=$(ls "$ROOT/$OUT_DIR"/marqdo-"$COMPONENT_ID"-"$VERSION"-source.tar.gz)
|
||||
SHAFILE="$ARCHIVE.sha256"
|
||||
|
||||
EVIDENCE_ARGS="--component-id $COMPONENT_ID --repository $REPOSITORY --tag $TAG --source-sha $SOURCE_SHA --asset $ARCHIVE --asset $SHAFILE --out $ROOT/$OUT_DIR/release-evidence.json"
|
||||
if [ -n "${CI_PIPELINE_NUMBER:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-number $CI_PIPELINE_NUMBER"
|
||||
fi
|
||||
if [ -n "${CI_PIPELINE_URL:-}" ]; then
|
||||
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-url $CI_PIPELINE_URL"
|
||||
fi
|
||||
# shellcheck disable=SC2086
|
||||
eval "python3 \"$ROOT/scripts/release/write_evidence.py\" $EVIDENCE_ARGS ${DEP_ARGS:-}"
|
||||
echo "$ARCHIVE"
|
||||
echo "$SHAFILE"
|
||||
echo "$ROOT/$OUT_DIR/release-evidence.json"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Vendored from marqdo scripts/component-release
|
||||
#
|
||||
# Do not edit in place across repositories. Change the root copy, re-test,
|
||||
# then re-run install-vendor.sh and record the hashes below.
|
||||
#
|
||||
# package_source.py sha256=cb18c2f7fbe807f55d49e2cf77720f0d3e57d355177d2b127ac09e119f90c6ae
|
||||
# write_evidence.py sha256=bb194bfd251e39308bc1dd53f46fd9efac181082ea43f668484b067d9e54acfc
|
||||
# publish_gitea.py sha256=a21a84146d9ea826eb8d0632a18a991b0c39f17005d83bd988c92fc608f67523
|
||||
# notify_root.py sha256=8eee83eb2bb31b99d93981f2a97fc2f0f9a486cc3c5c072f7dc12cfb63baf025
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ask the root Marqdo reconcile workflow to scan after a release.
|
||||
|
||||
The payload is only a hint. Correctness comes from the root
|
||||
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
|
||||
Lost notifications are recovered by the root `release-reconcile` cron.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
|
||||
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
|
||||
|
||||
|
||||
class NotifyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
|
||||
or os.environ.get("WOODPECKER_TOKEN")
|
||||
or os.environ.get("woodpecker_token")
|
||||
)
|
||||
if not value:
|
||||
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
|
||||
payload = json.dumps(body).encode()
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token_value}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
raw = response.read()
|
||||
decoded = json.loads(raw) if raw else {}
|
||||
return {
|
||||
"status": "triggered",
|
||||
"http_status": response.status,
|
||||
"pipeline_id": decoded.get("id"),
|
||||
"pipeline_number": decoded.get("number"),
|
||||
"attempt": attempt,
|
||||
}
|
||||
except urllib.error.HTTPError as error:
|
||||
# Auth/permission failures must not retry forever.
|
||||
if error.code in (401, 403, 404):
|
||||
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
|
||||
last_error = error
|
||||
except urllib.error.URLError as error:
|
||||
last_error = error
|
||||
if attempt < attempts:
|
||||
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
|
||||
time.sleep(delay)
|
||||
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
|
||||
parser.add_argument("--branch", default="main")
|
||||
parser.add_argument("--workflow", default="reconcile")
|
||||
parser.add_argument("--hint-component", default="")
|
||||
parser.add_argument("--hint-tag", default="")
|
||||
parser.add_argument("--attempts", type=int, default=3)
|
||||
args = parser.parse_args(argv)
|
||||
body = {"branch": args.branch, "workflow": args.workflow}
|
||||
# Hints are informational only; the root reconcile never trusts them as commands.
|
||||
if args.hint_component or args.hint_tag:
|
||||
body["variables"] = {
|
||||
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
|
||||
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
|
||||
}
|
||||
try:
|
||||
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
|
||||
except NotifyError as error:
|
||||
print(f"notify_root: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a deterministic source archive for a Marqdo component release.
|
||||
|
||||
Only allowlisted relative paths are included. The archive uses fixed mtime,
|
||||
uid/gid, and sorted member names so the same tree always yields the same
|
||||
sha256. Output is written under an isolated directory (default: dist/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ALLOWLIST = (
|
||||
"modules",
|
||||
"index.mq.md",
|
||||
"marqdo.yaml",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
)
|
||||
FIXED_MTIME = 0
|
||||
EVIDENCE_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PackageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise PackageError(message)
|
||||
|
||||
|
||||
def is_safe_relative(path: str) -> bool:
|
||||
if not path or path.startswith("/") or path.startswith("\\"):
|
||||
return False
|
||||
parts = Path(path).parts
|
||||
return not any(part in (".", "..") for part in parts)
|
||||
|
||||
|
||||
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
|
||||
selected: dict[str, Path] = {}
|
||||
for entry in allowlist:
|
||||
if not is_safe_relative(entry):
|
||||
fail(f"unsafe allowlist entry: {entry!r}")
|
||||
target = root / entry
|
||||
if not target.exists():
|
||||
continue
|
||||
if target.is_file():
|
||||
selected[entry.replace("\\", "/")] = target
|
||||
continue
|
||||
if not target.is_dir():
|
||||
fail(f"allowlist entry is not a regular file or directory: {entry}")
|
||||
for path in sorted(target.rglob("*")):
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.is_symlink():
|
||||
fail(f"symlinks are not publishable: {path.relative_to(root)}")
|
||||
relative = path.relative_to(root).as_posix()
|
||||
if not is_safe_relative(relative):
|
||||
fail(f"unsafe relative path: {relative}")
|
||||
selected[relative] = path
|
||||
if not selected:
|
||||
fail("allowlist matched no files")
|
||||
return sorted(selected.items(), key=lambda item: item[0])
|
||||
|
||||
|
||||
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
|
||||
for relative, path in files:
|
||||
data = path.read_bytes()
|
||||
info = tarfile.TarInfo(name=relative)
|
||||
info.size = len(data)
|
||||
info.mtime = FIXED_MTIME
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = ""
|
||||
info.gname = ""
|
||||
info.mode = 0o644
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_outputs(
|
||||
root: Path,
|
||||
out_dir: Path,
|
||||
component_id: str,
|
||||
version: str,
|
||||
allowlist: list[str],
|
||||
) -> dict:
|
||||
files = collect_files(root, allowlist)
|
||||
payload = archive_bytes(files)
|
||||
digest = hashlib.sha256(payload).hexdigest()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
|
||||
archive_path = out_dir / archive_name
|
||||
sha_path = out_dir / f"{archive_name}.sha256"
|
||||
archive_path.write_bytes(payload)
|
||||
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
|
||||
return {
|
||||
"archive": str(archive_path),
|
||||
"sha256_file": str(sha_path),
|
||||
"name": archive_name,
|
||||
"size": len(payload),
|
||||
"sha256": digest,
|
||||
"files": [relative for relative, _ in files],
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".", help="component repository root")
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--version", required=True, help="version without leading v")
|
||||
parser.add_argument("--out-dir", default="dist")
|
||||
parser.add_argument(
|
||||
"--allow",
|
||||
action="append",
|
||||
default=[],
|
||||
help="relative allowlist entry (repeatable); defaults applied when omitted",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
|
||||
root = Path(args.root).resolve()
|
||||
out_dir = Path(args.out_dir)
|
||||
if not out_dir.is_absolute():
|
||||
out_dir = root / out_dir
|
||||
try:
|
||||
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
|
||||
except PackageError as error:
|
||||
print(f"package_source: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(result["archive"])
|
||||
print(result["sha256_file"])
|
||||
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+352
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a Gitea release with a draft transaction and immutable public assets.
|
||||
|
||||
Order (issue #10 §4.2):
|
||||
create/reuse draft → upload non-index assets → upload release-evidence.json last
|
||||
→ re-read and verify → mark non-draft → re-confirm.
|
||||
|
||||
Never deletes or replaces assets on an already-published (non-draft) release.
|
||||
Identical published identity is treated as idempotent success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_API = "https://git.cflmy.cn/api/v1"
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = (
|
||||
os.environ.get("GITEA_PUBLISH_TOKEN")
|
||||
or os.environ.get("GITEA_TOKEN")
|
||||
or os.environ.get("gitea_token")
|
||||
)
|
||||
if not value:
|
||||
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
|
||||
return value
|
||||
|
||||
|
||||
def request(
|
||||
api: str,
|
||||
method: str,
|
||||
path: str,
|
||||
token_value: str,
|
||||
payload: dict | None = None,
|
||||
raw: bytes | None = None,
|
||||
content_type: str = "application/json",
|
||||
) -> tuple[int, bytes]:
|
||||
url = f"{api}{path}"
|
||||
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = content_type
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
headers["Content-Type"] = content_type
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
|
||||
|
||||
def decode(body: bytes) -> object:
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
|
||||
status, body = request(
|
||||
api,
|
||||
"GET",
|
||||
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
|
||||
token_value,
|
||||
)
|
||||
if status == 404:
|
||||
return None
|
||||
if status != 200:
|
||||
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
|
||||
release = decode(body)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("release lookup response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def create_draft(
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
token_value: str,
|
||||
*,
|
||||
prerelease: bool,
|
||||
target: str,
|
||||
) -> dict:
|
||||
payload = {
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
}
|
||||
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict) or "id" not in release:
|
||||
raise PublishError("draft create response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
|
||||
status, response = request(
|
||||
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
|
||||
release = decode(response)
|
||||
if not isinstance(release, dict):
|
||||
raise PublishError("release patch response malformed")
|
||||
return release
|
||||
|
||||
|
||||
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
|
||||
status, response = request(
|
||||
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
|
||||
)
|
||||
if status != 200:
|
||||
raise PublishError(f"listing assets failed with HTTP {status}")
|
||||
assets = decode(response)
|
||||
if not isinstance(assets, list):
|
||||
raise PublishError("asset list malformed")
|
||||
return assets
|
||||
|
||||
|
||||
def upload_asset(
|
||||
api: str, repo: str, release_id: int, path: Path, token_value: str
|
||||
) -> dict:
|
||||
name = path.name
|
||||
if not name or "/" in name or name in (".", ".."):
|
||||
raise PublishError(f"unsafe asset name: {name!r}")
|
||||
existing = list_assets(api, repo, release_id, token_value)
|
||||
for asset in existing:
|
||||
if asset.get("name") == name:
|
||||
raise PublishError(
|
||||
f"asset {name} already exists on draft/release {release_id}; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
boundary = f"----marqdo{uuid.uuid4().hex}"
|
||||
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||||
body = bytearray()
|
||||
body.extend(f"--{boundary}\r\n".encode())
|
||||
body.extend(
|
||||
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
|
||||
)
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
||||
body.extend(path.read_bytes())
|
||||
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
||||
status, response = request(
|
||||
api,
|
||||
"POST",
|
||||
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
|
||||
token_value,
|
||||
raw=bytes(body),
|
||||
content_type=f"multipart/form-data; boundary={boundary}",
|
||||
)
|
||||
if status not in (200, 201):
|
||||
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
|
||||
result = decode(response)
|
||||
if not isinstance(result, dict):
|
||||
raise PublishError(f"upload response for {name} malformed")
|
||||
return result
|
||||
|
||||
|
||||
def asset_identity(path: Path) -> dict:
|
||||
return {
|
||||
"name": path.name,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
|
||||
|
||||
def published_matches(release: dict, expected: list[dict]) -> bool:
|
||||
remote = {
|
||||
asset.get("name"): int(asset.get("size") or -1)
|
||||
for asset in (release.get("assets") or [])
|
||||
}
|
||||
if set(remote) != {item["name"] for item in expected}:
|
||||
return False
|
||||
for item in expected:
|
||||
if remote.get(item["name"]) != item["size"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def publish(
|
||||
*,
|
||||
api: str,
|
||||
repo: str,
|
||||
tag: str,
|
||||
body: str,
|
||||
target: str,
|
||||
assets: list[Path],
|
||||
prerelease: bool,
|
||||
token_value: str,
|
||||
) -> dict:
|
||||
if not assets:
|
||||
raise PublishError("no assets to publish")
|
||||
index_assets = [path for path in assets if path.name == INDEX_NAME]
|
||||
other_assets = [path for path in assets if path.name != INDEX_NAME]
|
||||
if len(index_assets) != 1:
|
||||
raise PublishError("exactly one release-evidence.json is required")
|
||||
ordered = other_assets + index_assets
|
||||
expected = [asset_identity(path) for path in ordered]
|
||||
|
||||
existing = get_release_by_tag(api, repo, tag, token_value)
|
||||
if existing and not existing.get("draft"):
|
||||
if published_matches(existing, expected):
|
||||
return {
|
||||
"status": "idempotent",
|
||||
"release_id": existing["id"],
|
||||
"html_url": existing.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
raise PublishError(
|
||||
f"published release {tag} already exists with different assets; "
|
||||
"refusing to overwrite"
|
||||
)
|
||||
|
||||
if existing and existing.get("draft"):
|
||||
release = existing
|
||||
# Keep draft body/target aligned when continuing an interrupted publish.
|
||||
release = patch_release(
|
||||
api,
|
||||
repo,
|
||||
int(release["id"]),
|
||||
token_value,
|
||||
{
|
||||
"name": tag,
|
||||
"body": body,
|
||||
"draft": True,
|
||||
"prerelease": prerelease,
|
||||
"target_commitish": target,
|
||||
},
|
||||
)
|
||||
else:
|
||||
release = create_draft(
|
||||
api, repo, tag, body, token_value, prerelease=prerelease, target=target
|
||||
)
|
||||
|
||||
release_id = int(release["id"])
|
||||
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
|
||||
for path in ordered:
|
||||
if path.name in remote_names:
|
||||
# Same-name asset already on this draft: require identical size, else fail.
|
||||
match = next(
|
||||
asset
|
||||
for asset in list_assets(api, repo, release_id, token_value)
|
||||
if asset.get("name") == path.name
|
||||
)
|
||||
if int(match.get("size") or -1) != path.stat().st_size:
|
||||
raise PublishError(
|
||||
f"draft asset {path.name} size mismatch; refusing to overwrite"
|
||||
)
|
||||
continue
|
||||
upload_asset(api, repo, release_id, path, token_value)
|
||||
|
||||
refreshed = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not refreshed or not published_matches(refreshed, expected):
|
||||
raise PublishError("post-upload release asset list does not match local files")
|
||||
|
||||
published = patch_release(
|
||||
api,
|
||||
repo,
|
||||
release_id,
|
||||
token_value,
|
||||
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
|
||||
)
|
||||
if published.get("draft"):
|
||||
raise PublishError("release remained draft after publish")
|
||||
final = get_release_by_tag(api, repo, tag, token_value)
|
||||
if not final or final.get("draft") or not published_matches(final, expected):
|
||||
raise PublishError("final release confirmation failed")
|
||||
return {
|
||||
"status": "published",
|
||||
"release_id": final["id"],
|
||||
"html_url": final.get("html_url"),
|
||||
"tag": tag,
|
||||
"assets": expected,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
|
||||
parser.add_argument("--repo", required=True, help="owner/name")
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
|
||||
parser.add_argument("--body-file", default=None)
|
||||
parser.add_argument("--body", default="")
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--prerelease", action="store_true", default=False)
|
||||
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
|
||||
args = parser.parse_args(argv)
|
||||
body = args.body
|
||||
if args.body_file:
|
||||
body = Path(args.body_file).read_text(encoding="utf-8")
|
||||
assets = [Path(item) for item in args.asset]
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
result = publish(
|
||||
api=args.api_url.rstrip("/"),
|
||||
repo=args.repo,
|
||||
tag=args.tag,
|
||||
body=body,
|
||||
target=args.target,
|
||||
assets=assets,
|
||||
prerelease=args.prerelease,
|
||||
token_value=token(),
|
||||
)
|
||||
except PublishError as error:
|
||||
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.evidence_out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+165
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the external release-evidence.json index for a component release.
|
||||
|
||||
The index references already-built assets. It never includes itself in
|
||||
`assets[]` (no self-referential digest). Downstream discoverers hash the index
|
||||
bytes separately when they download it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
MAX_ASSETS = 128
|
||||
MAX_DEPENDENCIES = 256
|
||||
INDEX_NAME = "release-evidence.json"
|
||||
|
||||
|
||||
class EvidenceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def parse_dependency(raw: str) -> dict:
|
||||
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
|
||||
fields = {}
|
||||
for part in raw.split(","):
|
||||
if "=" not in part:
|
||||
raise EvidenceError(f"invalid dependency field: {raw!r}")
|
||||
key, value = part.split("=", 1)
|
||||
fields[key.strip()] = value.strip()
|
||||
component_id = fields.get("id")
|
||||
source_sha = fields.get("source_sha")
|
||||
if not component_id or not source_sha or not SHA_RE.match(source_sha):
|
||||
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
|
||||
entry = {"id": component_id, "source_sha": source_sha}
|
||||
asset = fields.get("asset_sha256")
|
||||
if asset:
|
||||
if not DIGEST_RE.match(asset):
|
||||
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
|
||||
entry["asset_sha256"] = asset
|
||||
return entry
|
||||
|
||||
|
||||
def build_evidence(
|
||||
*,
|
||||
component_id: str,
|
||||
repository: str,
|
||||
tag: str,
|
||||
source_sha: str,
|
||||
assets: list[Path],
|
||||
dependencies: list[dict],
|
||||
pipeline_number: int | None,
|
||||
pipeline_url: str | None,
|
||||
) -> dict:
|
||||
if not component_id:
|
||||
raise EvidenceError("component_id is required")
|
||||
if "/" not in repository:
|
||||
raise EvidenceError("repository must be owner/name")
|
||||
if not tag:
|
||||
raise EvidenceError("tag is required")
|
||||
if not SHA_RE.match(source_sha):
|
||||
raise EvidenceError("source_sha must be a 40-hex commit")
|
||||
if not assets:
|
||||
raise EvidenceError("at least one non-index asset is required")
|
||||
if len(assets) > MAX_ASSETS:
|
||||
raise EvidenceError(f"more than {MAX_ASSETS} assets")
|
||||
if len(dependencies) > MAX_DEPENDENCIES:
|
||||
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
|
||||
|
||||
asset_entries = []
|
||||
seen_names: set[str] = set()
|
||||
for path in assets:
|
||||
if not path.is_file():
|
||||
raise EvidenceError(f"asset missing: {path}")
|
||||
name = path.name
|
||||
if name == INDEX_NAME:
|
||||
raise EvidenceError("assets must not include release-evidence.json itself")
|
||||
if name in seen_names or "/" in name or name in (".", ".."):
|
||||
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
|
||||
seen_names.add(name)
|
||||
target = "source"
|
||||
if name.endswith(".tar.gz") and "linux" in name:
|
||||
target = "x86_64-unknown-linux-gnu"
|
||||
asset_entries.append(
|
||||
{
|
||||
"name": name,
|
||||
"target": target,
|
||||
"size": path.stat().st_size,
|
||||
"sha256": sha256_file(path),
|
||||
}
|
||||
)
|
||||
|
||||
evidence = {
|
||||
"component_id": component_id,
|
||||
"repository": repository,
|
||||
"tag": tag,
|
||||
"source_sha": source_sha,
|
||||
"ci": {
|
||||
"pipeline_number": pipeline_number,
|
||||
"url": pipeline_url,
|
||||
"source_sha": source_sha,
|
||||
},
|
||||
"assets": asset_entries,
|
||||
"dependencies": dependencies,
|
||||
}
|
||||
return evidence
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--repository", required=True)
|
||||
parser.add_argument("--tag", required=True)
|
||||
parser.add_argument("--source-sha", required=True)
|
||||
parser.add_argument("--asset", action="append", default=[], required=True)
|
||||
parser.add_argument("--dependency", action="append", default=[])
|
||||
parser.add_argument("--pipeline-number", type=int, default=None)
|
||||
parser.add_argument("--pipeline-url", default=None)
|
||||
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
dependencies = [parse_dependency(item) for item in args.dependency]
|
||||
evidence = build_evidence(
|
||||
component_id=args.component_id,
|
||||
repository=args.repository,
|
||||
tag=args.tag,
|
||||
source_sha=args.source_sha,
|
||||
assets=[Path(item) for item in args.asset],
|
||||
dependencies=dependencies,
|
||||
pipeline_number=args.pipeline_number,
|
||||
pipeline_url=args.pipeline_url,
|
||||
)
|
||||
except EvidenceError as error:
|
||||
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
||||
if len(payload.encode()) > 1024 * 1024:
|
||||
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
|
||||
return 1
|
||||
out.write_text(payload, encoding="utf-8")
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
//! `marqdo web` — the unique Web Tool: offline preview, check and handoff.
|
||||
//!
|
||||
//! The tool consumes only the public `marqdo-web-design` crate (fixed git
|
||||
//! revision) and the CLI Analysis the design layer produces. It never parses
|
||||
//! Markdown, never calls document `@exec` business functions, never opens the
|
||||
//! network and never starts a server. Output is a static `file://` artifact with
|
||||
//! a strict CSP, an inert prototype banner, escaped content and deterministic
|
||||
//! staging→rename publication.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use marqdo_web_design::{
|
||||
handoff_relative_to, load, ComponentDef, ContentBlock, Design, Error, Instance, LoadConfig,
|
||||
Scenario, Width,
|
||||
};
|
||||
|
||||
const CSS: &str = r#"
|
||||
:root{color-scheme:light dark}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:system-ui,-apple-system,"Noto Sans CJK SC",sans-serif;background:#f7f7f8;color:#1d1d1f}
|
||||
body[data-theme="dark"]{background:#151517;color:#e8e8ea}
|
||||
header{position:sticky;top:0;background:#fff8e1;color:#5b4500;border-bottom:1px solid #e0c56b;padding:.6rem 1rem;font-weight:600}
|
||||
body[data-theme="dark"] header{background:#3a2f00;color:#ffe08a;border-color:#6b5600}
|
||||
main{padding:1rem;max-width:1200px;margin:0 auto}
|
||||
.component{border:1px dashed #b9b9c0;border-radius:8px;padding:.75rem;margin:.5rem 0;background:rgba(255,255,255,.6)}
|
||||
body[data-theme="dark"] .component{background:rgba(255,255,255,.04);border-color:#4a4a52}
|
||||
.grid{display:grid;gap:.75rem}
|
||||
.content p,.content pre{margin:.4rem 0}
|
||||
pre{overflow:auto;background:#f0f0f4;padding:.6rem;border-radius:6px;max-height:24rem}
|
||||
body[data-theme="dark"] pre{background:#232329}
|
||||
button{margin:.25rem .35rem .25rem 0;padding:.35rem .7rem;border-radius:6px;border:1px solid #888;background:#fff;cursor:pointer}
|
||||
body[data-theme="dark"] button{background:#2a2a31;color:#eee;border-color:#666}
|
||||
.badge{display:inline-block;font-size:.75rem;padding:.1rem .45rem;border-radius:999px;background:#ffe08a;color:#3a2f00;margin-right:.4rem}
|
||||
.summary{font-size:.8rem;color:#555;margin-top:2rem;border-top:1px solid #ccc;padding-top:.75rem}
|
||||
body[data-theme="dark"] .summary{color:#aaa;border-color:#444}
|
||||
.hidden{display:none}
|
||||
"#;
|
||||
|
||||
const SCRIPT: &str = r#"
|
||||
(function(){
|
||||
function setup(root){
|
||||
var panels = root.querySelectorAll('[data-scenario-panel]');
|
||||
function show(state){
|
||||
panels.forEach(function(panel){
|
||||
panel.classList.toggle('hidden', panel.getAttribute('data-scenario-panel') !== state);
|
||||
});
|
||||
root.setAttribute('data-current-state', state);
|
||||
}
|
||||
root.querySelectorAll('button[data-next]').forEach(function(button){
|
||||
button.addEventListener('click', function(){
|
||||
show(button.getAttribute('data-next'));
|
||||
});
|
||||
});
|
||||
var reset = root.querySelector('button[data-reset]');
|
||||
if(reset){ reset.addEventListener('click', function(){ show(root.getAttribute('data-initial-state')); }); }
|
||||
}
|
||||
document.querySelectorAll('[data-scenario]').forEach(setup);
|
||||
})();
|
||||
"#;
|
||||
|
||||
struct Args {
|
||||
command: String,
|
||||
entry: String,
|
||||
unit: String,
|
||||
root: Option<String>,
|
||||
out: Option<String>,
|
||||
theme: String,
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Args, String> {
|
||||
let mut argv = std::env::args().skip(1);
|
||||
let Some(command) = argv.next() else {
|
||||
return Err(
|
||||
"usage: web <check|preview|handoff> ENTRY --unit ANCHOR [--root DIR] [--out PATH]"
|
||||
.into(),
|
||||
);
|
||||
};
|
||||
if !matches!(command.as_str(), "check" | "preview" | "handoff") {
|
||||
return Err(format!(
|
||||
"unknown web subcommand {command:?}; expected check|preview|handoff"
|
||||
));
|
||||
}
|
||||
let mut entry = None;
|
||||
let mut unit = None;
|
||||
let mut root = None;
|
||||
let mut out = None;
|
||||
let mut theme = "light".to_string();
|
||||
let mut rest: Vec<String> = argv.collect();
|
||||
let mut index = 0;
|
||||
while index < rest.len() {
|
||||
let item = rest[index].clone();
|
||||
match item.as_str() {
|
||||
"--unit" => {
|
||||
index += 1;
|
||||
unit = rest.get(index).cloned();
|
||||
}
|
||||
"--root" => {
|
||||
index += 1;
|
||||
root = rest.get(index).cloned();
|
||||
}
|
||||
"--out" => {
|
||||
index += 1;
|
||||
out = rest.get(index).cloned();
|
||||
}
|
||||
"--theme" => {
|
||||
index += 1;
|
||||
theme = rest.get(index).cloned().unwrap_or_default();
|
||||
}
|
||||
other if other.starts_with("--") => {
|
||||
return Err(format!("unknown option {other:?}"));
|
||||
}
|
||||
other => {
|
||||
if entry.is_some() {
|
||||
return Err("exactly one ENTRY is required".into());
|
||||
}
|
||||
entry = Some(other.to_string());
|
||||
let _ = &mut rest;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if !matches!(theme.as_str(), "light" | "dark") {
|
||||
return Err("--theme must be light or dark".into());
|
||||
}
|
||||
Ok(Args {
|
||||
command,
|
||||
entry: entry.ok_or("missing ENTRY")?,
|
||||
unit: unit.ok_or("--unit ANCHOR is required")?,
|
||||
root,
|
||||
out,
|
||||
theme,
|
||||
})
|
||||
}
|
||||
|
||||
fn hex_escape(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len());
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn base64(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::new();
|
||||
for chunk in bytes.chunks(3) {
|
||||
let mut value = 0u32;
|
||||
for (index, byte) in chunk.iter().enumerate() {
|
||||
value |= u32::from(*byte) << (16 - 8 * index);
|
||||
}
|
||||
out.push(ALPHABET[((value >> 18) & 63) as usize] as char);
|
||||
out.push(ALPHABET[((value >> 12) & 63) as usize] as char);
|
||||
out.push(if chunk.len() > 1 {
|
||||
ALPHABET[((value >> 6) & 63) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
out.push(if chunk.len() > 2 {
|
||||
ALPHABET[(value & 63) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn csp_hash(content: &str) -> String {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
// SHA-256 is required for CSP; use the design-independent tiny implementation.
|
||||
sha256_b64(content.as_bytes()).unwrap_or_else(|| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
content.hash(&mut hasher);
|
||||
format!("sha256-{}", hasher.finish())
|
||||
})
|
||||
}
|
||||
|
||||
fn sha256_b64(bytes: &[u8]) -> Option<String> {
|
||||
// Minimal SHA-256; preview must not add dependencies beyond the Design crate.
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
|
||||
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
|
||||
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
|
||||
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
||||
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
||||
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
|
||||
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
|
||||
0xc67178f2,
|
||||
];
|
||||
let mut h: [u32; 8] = [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
|
||||
0x5be0cd19,
|
||||
];
|
||||
let mut message = bytes.to_vec();
|
||||
let bit_len = (bytes.len() as u64) * 8;
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&bit_len.to_be_bytes());
|
||||
for chunk in message.chunks(64) {
|
||||
let mut w = [0u32; 64];
|
||||
for index in 0..16 {
|
||||
w[index] = u32::from_be_bytes([
|
||||
chunk[4 * index],
|
||||
chunk[4 * index + 1],
|
||||
chunk[4 * index + 2],
|
||||
chunk[4 * index + 3],
|
||||
]);
|
||||
}
|
||||
for index in 16..64 {
|
||||
let s0 = w[index - 15].rotate_right(7)
|
||||
^ w[index - 15].rotate_right(18)
|
||||
^ (w[index - 15] >> 3);
|
||||
let s1 = w[index - 2].rotate_right(17)
|
||||
^ w[index - 2].rotate_right(19)
|
||||
^ (w[index - 2] >> 10);
|
||||
w[index] = w[index - 16]
|
||||
.wrapping_add(s0)
|
||||
.wrapping_add(w[index - 7])
|
||||
.wrapping_add(s1);
|
||||
}
|
||||
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
|
||||
(h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
|
||||
for index in 0..64 {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let ch = (e & f) ^ ((!e) & g);
|
||||
let temp1 = hh
|
||||
.wrapping_add(s1)
|
||||
.wrapping_add(ch)
|
||||
.wrapping_add(K[index])
|
||||
.wrapping_add(w[index]);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
let temp2 = s0.wrapping_add(maj);
|
||||
hh = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d.wrapping_add(temp1);
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1.wrapping_add(temp2);
|
||||
}
|
||||
h[0] = h[0].wrapping_add(a);
|
||||
h[1] = h[1].wrapping_add(b);
|
||||
h[2] = h[2].wrapping_add(c);
|
||||
h[3] = h[3].wrapping_add(d);
|
||||
h[4] = h[4].wrapping_add(e);
|
||||
h[5] = h[5].wrapping_add(f);
|
||||
h[6] = h[6].wrapping_add(g);
|
||||
h[7] = h[7].wrapping_add(hh);
|
||||
}
|
||||
let mut digest = Vec::new();
|
||||
for word in h {
|
||||
digest.extend_from_slice(&word.to_be_bytes());
|
||||
}
|
||||
Some(base64(&digest))
|
||||
}
|
||||
|
||||
fn render_blocks(blocks: &[ContentBlock]) -> String {
|
||||
let mut out = String::new();
|
||||
for block in blocks {
|
||||
let text = hex_escape(&block.text);
|
||||
match block.kind.as_str() {
|
||||
"paragraph" => out.push_str(&format!("<p>{text}</p>\n")),
|
||||
"heading" => out.push_str(&format!("<h3>{text}</h3>\n")),
|
||||
"list" | "table" | "code" | "quote" => out.push_str(&format!("<pre>{text}</pre>\n")),
|
||||
_ => out.push_str(&format!("<p class=\"inert\">{text}</p>\n")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn slot_columns(definition: &ComponentDef, row: u32) -> String {
|
||||
definition
|
||||
.slots
|
||||
.iter()
|
||||
.filter(|slot| slot.row == row)
|
||||
.map(|slot| match slot.width {
|
||||
Width::Auto => "minmax(0,auto)".to_string(),
|
||||
Width::Fr(value) => format!("minmax(0,{value}fr)"),
|
||||
Width::Px(value) => format!("minmax(0,{value}px)"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn render_instance(
|
||||
design: &Design,
|
||||
instance: &Instance,
|
||||
instance_by_id: &BTreeMap<String, &Instance>,
|
||||
depth: usize,
|
||||
) -> Result<String, String> {
|
||||
if depth > 40 {
|
||||
return Err("instance rendering depth exceeded".into());
|
||||
}
|
||||
let definition = design
|
||||
.definitions
|
||||
.get(&instance.definition)
|
||||
.ok_or_else(|| format!("missing definition {}", instance.definition))?;
|
||||
let mut out = format!(
|
||||
"<section class=\"component\" data-instance=\"{}\">\n",
|
||||
hex_escape(&instance.id)
|
||||
);
|
||||
out.push_str(&format!(
|
||||
"<div class=\"source\"><span class=\"badge\">原型</span>{}#{} </div>\n",
|
||||
hex_escape(&definition.source.path),
|
||||
hex_escape(&definition.source.anchor)
|
||||
));
|
||||
if !definition.content.is_empty() {
|
||||
out.push_str("<div class=\"content\">");
|
||||
out.push_str(&render_blocks(&definition.content));
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
let rows: Vec<u32> = {
|
||||
let mut rows: Vec<u32> = definition.slots.iter().map(|slot| slot.row).collect();
|
||||
rows.sort_unstable();
|
||||
rows.dedup();
|
||||
rows
|
||||
};
|
||||
for row in rows {
|
||||
let columns = slot_columns(definition, row);
|
||||
out.push_str(&format!(
|
||||
"<div class=\"grid\" style=\"grid-template-columns:{columns}\">\n"
|
||||
));
|
||||
for slot in definition.slots.iter().filter(|slot| slot.row == row) {
|
||||
let child_id = format!("{}/{}", instance.id, slot.slot);
|
||||
let child = instance_by_id
|
||||
.get(&child_id)
|
||||
.ok_or_else(|| format!("missing child instance {child_id}"))?;
|
||||
out.push_str(&render_instance(design, child, instance_by_id, depth + 1)?);
|
||||
}
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
if let Some(scenario_markup) = render_scenarios(instance, definition) {
|
||||
out.push_str(&scenario_markup);
|
||||
}
|
||||
out.push_str("</section>\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn render_scenarios(instance: &Instance, definition: &ComponentDef) -> Option<String> {
|
||||
if definition.scenarios.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let initial = definition
|
||||
.scenarios
|
||||
.iter()
|
||||
.find(|scene| scene.initial)
|
||||
.map(|scene| scene.state.clone())
|
||||
.unwrap_or_default();
|
||||
let mut out = format!(
|
||||
"<div class=\"scenario\" data-scenario data-initial-state=\"{}\" data-current-state=\"{}\">\n",
|
||||
hex_escape(&initial),
|
||||
hex_escape(&initial)
|
||||
);
|
||||
for scene in &definition.scenarios {
|
||||
let hidden = if scene.state == initial {
|
||||
""
|
||||
} else {
|
||||
" hidden"
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"<div class=\"scenario-panel{hidden}\" data-scenario-panel=\"{}\">\n",
|
||||
hex_escape(&scene.state)
|
||||
));
|
||||
out.push_str(&render_blocks(&scene.content_blocks));
|
||||
for interaction in definition
|
||||
.interactions
|
||||
.iter()
|
||||
.filter(|interaction| interaction.current == scene.state)
|
||||
{
|
||||
out.push_str(&format!(
|
||||
"<button type=\"button\" data-next=\"{}\">模拟:{}</button>\n",
|
||||
hex_escape(&interaction.next),
|
||||
hex_escape(&interaction.event)
|
||||
));
|
||||
}
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
out.push_str("<button type=\"button\" data-reset>重置原型</button>\n");
|
||||
let _ = instance;
|
||||
out.push_str("</div>\n");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn render(design: &Design, theme: &str) -> Result<String, String> {
|
||||
let mut instance_by_id: BTreeMap<String, &Instance> = BTreeMap::new();
|
||||
for instance in &design.instances {
|
||||
instance_by_id.insert(instance.id.clone(), instance);
|
||||
}
|
||||
let root = instance_by_id
|
||||
.get("root")
|
||||
.ok_or_else(|| "design has no root instance".to_string())?;
|
||||
let mut body = render_instance(design, root, &instance_by_id, 0)?;
|
||||
let mut summary =
|
||||
String::from("<div class=\"summary\">\n<strong>本轮构建摘要</strong>\n<ul>\n");
|
||||
summary.push_str(&format!("<li>root: {}</li>\n", hex_escape(&design.root)));
|
||||
for source in &design.sources {
|
||||
summary.push_str(&format!(
|
||||
"<li>{} sha256:{}</li>\n",
|
||||
hex_escape(&source.path),
|
||||
hex_escape(&source.source_digest)
|
||||
));
|
||||
}
|
||||
summary.push_str("</ul>\n<p>原型 / 模拟:不连接网络、不执行文档 @exec 业务函数、不代表生产站点。</p>\n</div>\n");
|
||||
body.push_str(&summary);
|
||||
let style_hash = csp_hash(CSS);
|
||||
let script_hash = csp_hash(SCRIPT);
|
||||
let csp = format!(
|
||||
"default-src 'none'; style-src 'sha256-{style_hash}'; script-src 'sha256-{script_hash}'; img-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'"
|
||||
);
|
||||
Ok(format!(
|
||||
"<!DOCTYPE html>\n<html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\"><title>Marqdo Web 原型预览</title><style>{CSS}</style></head><body data-theme=\"{theme}\"><header>原型 / 模拟:本地离线预览,不连接网络,不代表生产站点</header><main>{body}</main><script>{SCRIPT}</script></body></html>\n"
|
||||
))
|
||||
}
|
||||
|
||||
fn diagnostic_text(error: &Error) -> (u8, String) {
|
||||
let (code, diagnostics) = match error {
|
||||
Error::Engine(items) => (2u8, items),
|
||||
Error::Design(items) => (1u8, items),
|
||||
};
|
||||
let mut text = String::new();
|
||||
for diagnostic in diagnostics {
|
||||
text.push_str(&format!(
|
||||
"{} [{:?}] {}",
|
||||
diagnostic.code, diagnostic.severity, diagnostic.message
|
||||
));
|
||||
if let Some(path) = &diagnostic.path {
|
||||
text.push_str(&format!(" at {path}"));
|
||||
}
|
||||
if let Some(span) = &diagnostic.span {
|
||||
text.push_str(&format!(" [{}..{}]", span.start, span.end));
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
(code, text)
|
||||
}
|
||||
|
||||
fn design_load(args: &Args) -> Result<Design, (u8, String)> {
|
||||
let cli = std::env::var("MARQDO_BIN")
|
||||
.map(PathBuf::from)
|
||||
.map_err(|_| {
|
||||
(
|
||||
2u8,
|
||||
"MARQDO_BIN must name the verified marqdo executable\n".to_string(),
|
||||
)
|
||||
})?;
|
||||
let entry = PathBuf::from(&args.entry);
|
||||
let root = args
|
||||
.root
|
||||
.clone()
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| entry.parent().unwrap_or(Path::new(".")).to_path_buf());
|
||||
let config = LoadConfig::new(cli, entry, args.unit.clone(), root);
|
||||
load(&config).map_err(|error| diagnostic_text(&error))
|
||||
}
|
||||
|
||||
fn staging_for(out: &Path) -> Result<PathBuf, String> {
|
||||
let parent = out
|
||||
.parent()
|
||||
.ok_or_else(|| "output path has no parent".to_string())?;
|
||||
if !parent.is_dir() {
|
||||
return Err(format!(
|
||||
"output parent is not a directory: {}",
|
||||
parent.display()
|
||||
));
|
||||
}
|
||||
if out.exists() {
|
||||
return Err(format!("output already exists: {}", out.display()));
|
||||
}
|
||||
if out
|
||||
.symlink_metadata()
|
||||
.map(|meta| meta.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(format!("output is a symbolic link: {}", out.display()));
|
||||
}
|
||||
let staging = parent.join(format!(".web-staging-{}", std::process::id()));
|
||||
if staging.exists() {
|
||||
fs::remove_dir_all(&staging).map_err(|error| format!("cannot reset staging: {error}"))?;
|
||||
}
|
||||
fs::create_dir(&staging).map_err(|error| format!("cannot create staging: {error}"))?;
|
||||
Ok(staging)
|
||||
}
|
||||
|
||||
fn publish(staging: &Path, out: &Path) -> Result<(), String> {
|
||||
fs::rename(staging, out).map_err(|error| format!("cannot publish artifact: {error}"))
|
||||
}
|
||||
|
||||
fn run_check(args: &Args) -> ExitCode {
|
||||
match design_load(args) {
|
||||
Ok(design) => {
|
||||
println!(
|
||||
"design {} definitions={} instances={} sources={}",
|
||||
design.root,
|
||||
design.definitions.len(),
|
||||
design.instances.len(),
|
||||
design.sources.len()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
ExitCode::from(code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_preview(args: &Args) -> ExitCode {
|
||||
let Some(out) = &args.out else {
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let design = match design_load(args) {
|
||||
Ok(design) => design,
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
return ExitCode::from(code);
|
||||
}
|
||||
};
|
||||
let html = match render(&design, &args.theme) {
|
||||
Ok(html) => html,
|
||||
Err(error) => {
|
||||
eprintln!("web preview: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if html.len() > 4 * 1024 * 1024 {
|
||||
eprintln!("web preview: error: rendered HTML exceeds the 4 MiB budget");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let out = PathBuf::from(out);
|
||||
let staging = match staging_for(&out) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("web preview: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if let Err(error) = fs::write(staging.join("index.html"), html) {
|
||||
eprintln!("web preview: error: cannot write index.html: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Err(error) = publish(&staging, &out) {
|
||||
eprintln!("web preview: error: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
println!("preview {} (theme {})", out.display(), args.theme);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_handoff(args: &Args) -> ExitCode {
|
||||
let Some(out) = &args.out else {
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let design = match design_load(args) {
|
||||
Ok(design) => design,
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
return ExitCode::from(code);
|
||||
}
|
||||
};
|
||||
let out = PathBuf::from(out);
|
||||
let base = out
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let base = base.canonicalize().unwrap_or(base);
|
||||
let text = handoff_relative_to(&design, &base);
|
||||
if text.len() > 4 * 1024 * 1024 {
|
||||
eprintln!("web handoff: error: handoff exceeds the 4 MiB budget");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Some(parent) = out.parent() {
|
||||
if !parent.as_os_str().is_empty() && !parent.is_dir() {
|
||||
eprintln!("web handoff: error: output parent is not a directory");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
if out.exists() {
|
||||
eprintln!(
|
||||
"web handoff: error: output already exists: {}",
|
||||
out.display()
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let staging = match staging_for(&out) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("web handoff: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let staging_file = staging.join("handoff.md");
|
||||
if let Err(error) = fs::write(&staging_file, text) {
|
||||
eprintln!("web handoff: error: cannot write handoff: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Err(error) = fs::rename(&staging_file, &out) {
|
||||
eprintln!("web handoff: error: cannot publish handoff: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
println!("handoff {}", out.display());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args = match parse_args() {
|
||||
Ok(args) => args,
|
||||
Err(error) => {
|
||||
eprintln!("web: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match args.command.as_str() {
|
||||
"check" => run_check(&args),
|
||||
"preview" => run_preview(&args),
|
||||
"handoff" => run_handoff(&args),
|
||||
_ => ExitCode::from(2),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn _scenario_state(scenario: &Scenario) -> String {
|
||||
scenario.state.clone()
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# 导航组件
|
||||
|
||||
## @knowledge 导航
|
||||
|
||||
### 内容
|
||||
|
||||
- 首页
|
||||
- 任务
|
||||
|
||||
### 验收
|
||||
|
||||
- 导航在窄屏下重排。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 任务组件
|
||||
|
||||
## @knowledge 任务
|
||||
|
||||
### 场景
|
||||
|
||||
| 状态 | 内容 | 初始 |
|
||||
| --- | --- | --- |
|
||||
| empty | [空状态](../states.mq.md#空状态) | true |
|
||||
| done | [完成](../states.mq.md#完成) | false |
|
||||
|
||||
### 交互
|
||||
|
||||
| 当前 | 事件 | 下一状态 |
|
||||
| --- | --- | --- |
|
||||
| empty | 模拟保存 | done |
|
||||
@@ -0,0 +1,16 @@
|
||||
# 科研原型
|
||||
|
||||
## @knowledge 工作台
|
||||
|
||||
面向研究人员的原型页面。访问 [项目说明](https://example.test/docs) 或 [危险](javascript:alert(1))。
|
||||
|
||||
### 内容
|
||||
|
||||
<div onerror="alert(1)">raw html 应显示为文本</div>
|
||||
|
||||
### 组件
|
||||
|
||||
| 行 | 槽 | 组件 | 宽度 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | nav | [导航](components/nav.mq.md#导航) | 220px |
|
||||
| 1 | main | [任务](components/tasks.mq.md#任务) | 1fr |
|
||||
@@ -0,0 +1,9 @@
|
||||
# 状态
|
||||
|
||||
## @knowledge 空状态
|
||||
|
||||
暂无任务。
|
||||
|
||||
## @knowledge 完成
|
||||
|
||||
任务已完成(模拟)。
|
||||
Reference in new issue
Block a user