Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f1b1133ab | ||
|
|
76cc20d9d8 | ||
|
|
edb04bfdd9 | ||
|
|
982c2cdb77 | ||
|
|
86a260c646 | ||
|
|
eff273f7f2 |
No files matched your search
@@ -1,3 +1,4 @@
|
|||||||
/target
|
/target
|
||||||
/dist
|
/dist
|
||||||
/out
|
/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 维护指引
|
# 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`:只有文档,
|
本文件约束在本仓库工作的维护者与 AI Coding Agent。仓库状态为 `planned`:只有文档,
|
||||||
没有实现源码、`Cargo.toml`/`Cargo.lock`、`tool.json` 实体、CI 入口或发布制品,也没有
|
没有实现源码、`Cargo.toml`/`Cargo.lock`、`tool.json` 实体、CI 入口或发布制品,也没有
|
||||||
接入 `marqdo-ext-web` 的 gitlink。
|
接入 `marqdo-ext-web` 的 gitlink。
|
||||||
|
|||||||
Generated
+1
-1
@@ -11,7 +11,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-web-design"
|
name = "marqdo-web-design"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "git+https://git.cflmy.cn/cflmy/marqdo-web-design?rev=2f18dede8540c82611819e2c24a19db138d5ac14#2f18dede8540c82611819e2c24a19db138d5ac14"
|
source = "git+https://git.cflmy.cn/cflmy/marqdo-web-design?rev=1b6607fd3cc09801b4f6eacd2fba547caa0ec637#1b6607fd3cc09801b4f6eacd2fba547caa0ec637"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
]
|
]
|
||||||
|
|||||||
+1
-1
@@ -7,5 +7,5 @@ license = "MIT OR Apache-2.0"
|
|||||||
description = "Offline Web design preview and the unique marqdo web Tool"
|
description = "Offline Web design preview and the unique marqdo web Tool"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
marqdo-web-design = { git = "https://git.cflmy.cn/cflmy/marqdo-web-design", rev = "2f18dede8540c82611819e2c24a19db138d5ac14" }
|
marqdo-web-design = { git = "https://git.cflmy.cn/cflmy/marqdo-web-design", rev = "1b6607fd3cc09801b4f6eacd2fba547caa0ec637" }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
`marqdo-web-design` 已经解释好的设计模型,生成不依赖服务器、可用本地浏览器直接打开的
|
`marqdo-web-design` 已经解释好的设计模型,生成不依赖服务器、可用本地浏览器直接打开的
|
||||||
离线 HTML 原型,并以 `web` 命令注册为生态中唯一的 Web Tool 入口。
|
离线 HTML 原型,并以 `web` 命令注册为生态中唯一的 Web Tool 入口。
|
||||||
|
|
||||||
- **状态:`planned`**。本仓库目前只有文档:没有实现源码、`Cargo.toml`/`Cargo.lock`、
|
- **状态:`active`**。已实现独立 executable、`tool.json`、离线预览与 `scripts/ci.sh`;
|
||||||
`tool.json` 实体、`scripts/ci.sh`、CI 流水线或发布制品,也没有接入领域仓库
|
`tool.json` 实体、`scripts/ci.sh`、CI 流水线或发布制品,也没有接入领域仓库
|
||||||
`marqdo-ext-web` 的子 gitlink。本文中“将/目标”描述的是接入后必须满足的合同,不是
|
`marqdo-ext-web` 的子 gitlink。本文中“将/目标”描述的是接入后必须满足的合同,不是
|
||||||
已实现能力,也不是已验收结果。
|
已实现能力,也不是已验收结果。
|
||||||
@@ -16,8 +16,8 @@
|
|||||||
- **上游实现**:[marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design)
|
- **上游实现**:[marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design)
|
||||||
(唯一设计解释实现,Rust library;本仓库通过其公开 API 消费设计模型)。
|
(唯一设计解释实现,Rust library;本仓库通过其公开 API 消费设计模型)。
|
||||||
- **仓库远端**:`https://git.cflmy.cn/cflmy/marqdo-web-preview`。远端已创建并推送
|
- **仓库远端**:`https://git.cflmy.cn/cflmy/marqdo-web-preview`。远端已创建并推送
|
||||||
初始开发文档;领域 `components.toml` 已登记为 planned,开发工单也已建立;gitlink、
|
实现/证据;领域 `components.toml` 已登记为 active 并固定 gitlink;真实浏览器/资产等
|
||||||
独立 CI 与发布仍属于后续激活工作,当前 `planned`。
|
剩余验收项在组件工单跟踪,不得把未验证项写成 PASS。
|
||||||
|
|
||||||
## 职责与禁止
|
## 职责与禁止
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
| 对象 | 身份 |
|
| 对象 | 身份 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e...` |
|
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e...` |
|
||||||
| Design 依赖 | `marqdo-web-design@2f18dede8540c82611819e2c24a19db138d5ac14`(`Cargo.lock` 固定 git rev;不是 `../design` 路径依赖) |
|
| Design 依赖 | `marqdo-web-design@1b6607fd3cc09801b4f6eacd2fba547caa0ec637`(WEB-03 handoff/图/切片)(`Cargo.lock` 固定 git rev;不是 `../design` 路径依赖) |
|
||||||
| 平台 | Linux x86_64(本机验证) |
|
| 平台 | Linux x86_64(本机验证) |
|
||||||
|
|
||||||
## 执行
|
## 执行
|
||||||
@@ -33,7 +33,7 @@ MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
|||||||
|
|
||||||
## 未验证 / 后续(不隐藏)
|
## 未验证 / 后续(不隐藏)
|
||||||
|
|
||||||
- 真实浏览器(Playwright/file://)行为、responsive 390px 无横向溢出、按钮实际状态切换的 DOM 断言未执行;当前只有静态制品断言。
|
- WEB-03 交付内容由图/切片/漂移提供,Preview 已验证相对链接;真实浏览器(Playwright/file://)行为、responsive 390px 无横向溢出、按钮实际状态切换的 DOM 断言未执行;当前只有静态制品断言。
|
||||||
- 图片/本地 raster 资产复制、魔数/大小校验、远端图片文本占位尚未实现(当前不渲染图片)。
|
- 图片/本地 raster 资产复制、魔数/大小校验、远端图片文本占位尚未实现(当前不渲染图片)。
|
||||||
- 完整安全负例矩阵(`</script>`/Unicode/双引号 fixture、输出预算边界、超时/进程限制)未系统性覆盖。
|
- 完整安全负例矩阵(`</script>`/Unicode/双引号 fixture、输出预算边界、超时/进程限制)未系统性覆盖。
|
||||||
- 冷安装(root 生态 `web` Tool 与 WEB-05)未开始;WEB-04 生产交付试验未开始。
|
- 冷安装(root 生态 `web` Tool 与 WEB-05)未开始;WEB-04 生产交付试验未开始。
|
||||||
@@ -27,6 +27,16 @@ handoff="$work/handoff.md"
|
|||||||
"$MARQDO_BIN" web handoff tests/fixture/index.mq.md --unit 工作台 --out "$handoff"
|
"$MARQDO_BIN" web handoff tests/fixture/index.mq.md --unit 工作台 --out "$handoff"
|
||||||
test -s "$handoff"
|
test -s "$handoff"
|
||||||
grep -q "Design handoff" "$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
|
if "$MARQDO_BIN" web preview tests/fixture/index.mq.md --unit 工作台 --out "$preview" 2>/dev/null; then
|
||||||
echo "preview overwrote an existing directory" >&2
|
echo "preview overwrote an existing directory" >&2
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
+48
-24
@@ -1,25 +1,49 @@
|
|||||||
#!/usr/bin/env bash
|
#!/bin/sh
|
||||||
# Build the installable marqdo web Tool bundle.
|
# 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
|
set -eu
|
||||||
cd "$(dirname "$0")/.."
|
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
cargo build --release --locked
|
COMPONENT_ID=${COMPONENT_ID:?COMPONENT_ID is required}
|
||||||
dist="$PWD/dist/marqdo-web-preview"
|
REPOSITORY=${REPOSITORY:?REPOSITORY is required}
|
||||||
rm -rf "$dist"
|
SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)}
|
||||||
mkdir -p "$dist/bin"
|
OUT_DIR=${OUT_DIR:-dist}
|
||||||
cp target/release/marqdo-web-preview "$dist/bin/marqdo-web-preview"
|
TAG=${CI_COMMIT_TAG:-${TAG:-}}
|
||||||
chmod 0755 "$dist/bin/marqdo-web-preview"
|
if [ -n "${VERSION:-}" ]; then
|
||||||
cat > "$dist/tool.json" <<'JSON'
|
:
|
||||||
{
|
elif [ -n "$TAG" ]; then
|
||||||
"schema": "marqdo.cli-tool",
|
VERSION=${TAG#v}
|
||||||
"schema_version": 1,
|
else
|
||||||
"name": "cflmy.marqdo-web-preview",
|
echo "package.sh: set VERSION or CI_COMMIT_TAG" >&2
|
||||||
"version": "0.1.0",
|
exit 1
|
||||||
"command": "web",
|
fi
|
||||||
"entrypoint": "bin/marqdo-web-preview",
|
TAG=${TAG:-v$VERSION}
|
||||||
"requires": {
|
|
||||||
"api_revision": 1,
|
python3 "$ROOT/scripts/release/package_source.py" \
|
||||||
"analysis": 3
|
--root "$ROOT" \
|
||||||
}
|
--component-id "$COMPONENT_ID" \
|
||||||
}
|
--version "$VERSION" \
|
||||||
JSON
|
--out-dir "$OUT_DIR"
|
||||||
echo "tool bundle: $dist"
|
|
||||||
|
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())
|
||||||
+10
-3
@@ -13,7 +13,8 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
|
|
||||||
use marqdo_web_design::{
|
use marqdo_web_design::{
|
||||||
handoff, load, ComponentDef, ContentBlock, Design, Error, Instance, LoadConfig, Scenario, Width,
|
handoff_relative_to, load, ComponentDef, ContentBlock, Design, Error, Instance, LoadConfig,
|
||||||
|
Scenario, Width,
|
||||||
};
|
};
|
||||||
|
|
||||||
const CSS: &str = r#"
|
const CSS: &str = r#"
|
||||||
@@ -574,12 +575,18 @@ fn run_handoff(args: &Args) -> ExitCode {
|
|||||||
return ExitCode::from(code);
|
return ExitCode::from(code);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let text = handoff(&design);
|
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 {
|
if text.len() > 4 * 1024 * 1024 {
|
||||||
eprintln!("web handoff: error: handoff exceeds the 4 MiB budget");
|
eprintln!("web handoff: error: handoff exceeds the 4 MiB budget");
|
||||||
return ExitCode::from(2);
|
return ExitCode::from(2);
|
||||||
}
|
}
|
||||||
let out = PathBuf::from(out);
|
|
||||||
if let Some(parent) = out.parent() {
|
if let Some(parent) = out.parent() {
|
||||||
if !parent.as_os_str().is_empty() && !parent.is_dir() {
|
if !parent.as_os_str().is_empty() && !parent.is_dir() {
|
||||||
eprintln!("web handoff: error: output parent is not a directory");
|
eprintln!("web handoff: error: output parent is not a directory");
|
||||||
|
|||||||
Reference in new issue
Block a user