Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
703ee7af24 | ||
|
|
61b4dd370e | ||
|
|
5c7e517121 | ||
|
|
37404dbc6a | ||
|
|
a231068f23 | ||
|
|
cbef7b622a | ||
|
|
1b6607fd3c | ||
|
|
8cd72b87b6 |
No files matched your search
@@ -1 +1,2 @@
|
||||
/target
|
||||
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-design
|
||||
REPOSITORY: cflmy/marqdo-web-design
|
||||
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-design
|
||||
export REPOSITORY=cflmy/marqdo-web-design
|
||||
sh scripts/package.sh
|
||||
ARCHIVE="dist/marqdo-web-design-${VERSION}-source.tar.gz"
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo cflmy/marqdo-web-design --tag "${CI_COMMIT_TAG}" --target "$SOURCE_SHA" --prerelease \
|
||||
--body "Automated source release for web-design ${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-design --hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -1,5 +1,10 @@
|
||||
# marqdo-web-design 维护指引
|
||||
|
||||
<!-- marqdo:repo-conventions v1 -->
|
||||
|
||||
生态级仓库开发规范:https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md
|
||||
|
||||
|
||||
1. 只以 `marqdo-ext-web` 的 [WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 为现行作者合同;本仓库是实现者,不是合同所有者。合同语义冲突先在领域仓库开 ADR 工单,不同时维护两套解释。
|
||||
2. 只消费 CLI 公开接口(`check --emit` 的 Analysis 3 与文档化的 CLI/Tool 合同)。禁止复制 parser、读取 CLI 私有结构或以 `inspect` 等私有输出替代 Analysis;边界不够用时先取证再向 CLI 开通用工单。
|
||||
3. 不启动服务、不渲染 DOM、不写 HTML、不读密钥、不调用模型、不执行文档、不修改源文件。库失败必须返回带稳定错误码与来源 span 的 `Diagnostics`,禁止静默跳过子组件。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust library,消费真实 CLI 的公开 Analysis,把符合 [WEB-DESIGN 合同](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 的 `.mq.md` 解释为设计模型、诊断与交付快照。
|
||||
|
||||
**当前状态:`planned`。** 尚未实现、尚未发布、没有 CI 入口或制品;仓库中的 API 与目录均为暂定计划,未经真实 CLI 夹具验证。
|
||||
**当前状态:`active`。** 已实现并固定于领域 gitlink:消费真实 CLI Analysis 3,提供设计模型/诊断/handoff 与 `scripts/ci.sh`;24 个真实 CLI 契约测试通过。发布身份仍以领域/根固定提交与证据为准。
|
||||
|
||||
## 职责与禁止
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# WEB-03 Handoff、组件/依赖图与单组件交付证据
|
||||
|
||||
日期:2026-11-27。责任仓:`marqdo-web-design`;工单:[marqdo-web-design#2](https://git.cflmy.cn/cflmy/marqdo-web-design/issues/2)(WEB-03);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
|
||||
|
||||
## 输入身份
|
||||
|
||||
| 对象 | 身份 |
|
||||
| --- | --- |
|
||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,`sha256:6ede3b9e...` |
|
||||
| Design | `marqdo-web-design@8cd72b87b6291ceae769de081debe1b5dc826010` |
|
||||
| 平台 | Linux x86_64(本机验证) |
|
||||
|
||||
## 已验证(24/24 真实 CLI 契约测试)
|
||||
|
||||
- `handoff`/`handoff_relative_to`:确定性输出(同输入两次逐字节一致);包含 design id、源摘要、递归组件树、视觉包含边、非视觉依赖边、每组件源链接/职责视觉说明/输入/事件/场景/交互/依赖/验收、明确“原型/模拟、真实功能由目标应用实现”边界;输出到其它目录时源链接相对输出目录重算。
|
||||
- `graph()`:视觉包含边(含 slot)与非视觉依赖边分离;依赖循环组可报告(load 仍以 `web.dependency.cycle` 拒绝组合,要求协调)。
|
||||
- `slice()`:单组件只包含其视觉子树定义/实例与实际使用源,未知组件报错。
|
||||
- `drift()` + `design_id()`:源改动后受影响组件与源变化可定位,未变组件不误报;相同 design 的 id 稳定、改动后变化。
|
||||
- 负例保持:错误输入拒绝、验收文本不被自动翻译成测试结论、交付只含模型派生内容不复制整仓源码。
|
||||
- 非视觉依赖目标作为定义加载,使交付图显式;该路径成环报告依赖环错误。
|
||||
|
||||
## 未验证 / 后续
|
||||
|
||||
- WEB-04 的三领域组合案例与成熟框架生产交付试验未开始。
|
||||
- WEB-05 根接入、web Tool 冷安装、领域激活未开始。
|
||||
- 交付的“视觉说明/参考”目前来自 Design 安全内容投影;参考图/外部资源在 Preview/生产交付中的表达仍属 WEB-02/WEB-04 范围。
|
||||
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())
|
||||
+363
-35
@@ -186,6 +186,8 @@ pub struct SourceIdentity {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Design {
|
||||
pub root: String,
|
||||
/// Canonical explicit design root; source links are derived from it.
|
||||
pub root_dir: PathBuf,
|
||||
pub definitions: BTreeMap<String, ComponentDef>,
|
||||
pub instances: Vec<Instance>,
|
||||
pub sources: Vec<SourceIdentity>,
|
||||
@@ -926,8 +928,25 @@ impl Loader {
|
||||
}
|
||||
let (target_module, target_unit) =
|
||||
self.resolve_dependency_component(module, link)?;
|
||||
// A dependency names a design component that may not be placed in
|
||||
// this visual tree; load its definition so the graph is explicit.
|
||||
let target_key = normalized_key(&target_module, target_unit.anchor_text());
|
||||
if self.stack.iter().any(|item| item == &target_key) {
|
||||
return Err(design_error(
|
||||
"web.dependency.cycle",
|
||||
format!(
|
||||
"design dependency cycle at {target_key}; coordination is required"
|
||||
),
|
||||
));
|
||||
}
|
||||
let target_key = self.load_definition(
|
||||
&target_module,
|
||||
&target_unit,
|
||||
target_unit.anchor_text(),
|
||||
depth + 1,
|
||||
)?;
|
||||
dependencies.push(Dependency {
|
||||
target: normalized_key(&target_module, target_unit.anchor_text()),
|
||||
target: target_key,
|
||||
reason,
|
||||
span: json_span(cells[0].span),
|
||||
});
|
||||
@@ -1177,6 +1196,7 @@ pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
||||
sources.sort_by(|left, right| left.path.cmp(&right.path));
|
||||
Ok(Design {
|
||||
root: root_key,
|
||||
root_dir: root.clone(),
|
||||
definitions: loader.definitions,
|
||||
instances,
|
||||
sources,
|
||||
@@ -1205,81 +1225,389 @@ fn collect_instances(
|
||||
}
|
||||
}
|
||||
|
||||
/// Derive a Markdown handoff from the model only; never re-reads sources.
|
||||
/// Deterministic design identity (FNV-1a over root, sources and definitions).
|
||||
pub fn design_id(design: &Design) -> String {
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
let mut hash = 0xcbf2_9ce4_8422_2325u64;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
let mut material = String::new();
|
||||
material.push_str(&design.root);
|
||||
material.push('\n');
|
||||
for source in &design.sources {
|
||||
material.push_str(&format!("{}:{}\n", source.path, source.source_digest));
|
||||
}
|
||||
for (key, definition) in &design.definitions {
|
||||
material.push_str(&format!("{key}:"));
|
||||
for slot in &definition.slots {
|
||||
material.push_str(&format!("{}:{};", slot.slot, slot.target));
|
||||
}
|
||||
material.push('\n');
|
||||
}
|
||||
format!(
|
||||
"fnv128:{:016x}{:016x}",
|
||||
fnv(material.as_bytes()),
|
||||
material.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DesignGraph {
|
||||
/// Visual containment: parent definition key -> child definition key (+slot).
|
||||
pub visual_edges: Vec<(String, String, String)>,
|
||||
/// Non-visual design dependencies: definition key -> target definition key.
|
||||
pub dependency_edges: Vec<(String, String, String)>,
|
||||
/// Dependency cycles that need coordination (normally empty; load rejects them).
|
||||
pub dependency_cycles: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
pub fn graph(design: &Design) -> DesignGraph {
|
||||
let mut visual_edges = Vec::new();
|
||||
let mut dependency_edges = Vec::new();
|
||||
for (key, definition) in &design.definitions {
|
||||
for slot in &definition.slots {
|
||||
visual_edges.push((key.clone(), slot.target.clone(), slot.slot.clone()));
|
||||
}
|
||||
for dependency in &definition.dependencies {
|
||||
dependency_edges.push((
|
||||
key.clone(),
|
||||
dependency.target.clone(),
|
||||
dependency.reason.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut adjacency: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
|
||||
for (from, to, _) in &dependency_edges {
|
||||
adjacency
|
||||
.entry(from.as_str())
|
||||
.or_default()
|
||||
.push(to.as_str());
|
||||
}
|
||||
let mut cycles: Vec<Vec<String>> = Vec::new();
|
||||
let mut done: BTreeSet<&str> = BTreeSet::new();
|
||||
fn walk<'a>(
|
||||
node: &'a str,
|
||||
adjacency: &BTreeMap<&'a str, Vec<&'a str>>,
|
||||
stack: &mut Vec<&'a str>,
|
||||
done: &mut BTreeSet<&'a str>,
|
||||
cycles: &mut Vec<Vec<String>>,
|
||||
) {
|
||||
if done.contains(node) {
|
||||
return;
|
||||
}
|
||||
if let Some(position) = stack.iter().position(|item| *item == node) {
|
||||
cycles.push(
|
||||
stack[position..]
|
||||
.iter()
|
||||
.map(|item| item.to_string())
|
||||
.collect(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
stack.push(node);
|
||||
if let Some(targets) = adjacency.get(node) {
|
||||
for target in targets {
|
||||
walk(target, adjacency, stack, done, cycles);
|
||||
}
|
||||
}
|
||||
stack.pop();
|
||||
done.insert(node);
|
||||
}
|
||||
for node in adjacency.keys() {
|
||||
let mut stack = Vec::new();
|
||||
walk(node, &adjacency, &mut stack, &mut done, &mut cycles);
|
||||
}
|
||||
cycles.sort();
|
||||
cycles.dedup();
|
||||
DesignGraph {
|
||||
visual_edges,
|
||||
dependency_edges,
|
||||
dependency_cycles: cycles,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Drift {
|
||||
pub added_components: Vec<String>,
|
||||
pub removed_components: Vec<String>,
|
||||
pub changed_components: Vec<String>,
|
||||
pub changed_sources: Vec<String>,
|
||||
pub unchanged: bool,
|
||||
}
|
||||
|
||||
/// Compare two accepted designs; a changed source digest or component model is drift.
|
||||
pub fn drift(previous: &Design, current: &Design) -> Drift {
|
||||
let mut added = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut changed = Vec::new();
|
||||
for key in current.definitions.keys() {
|
||||
match previous.definitions.get(key) {
|
||||
None => added.push(key.clone()),
|
||||
Some(before) if before != ¤t.definitions[key] => changed.push(key.clone()),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
for key in previous.definitions.keys() {
|
||||
if !current.definitions.contains_key(key) {
|
||||
removed.push(key.clone());
|
||||
}
|
||||
}
|
||||
let mut changed_sources = Vec::new();
|
||||
let previous_sources: BTreeMap<&str, &str> = previous
|
||||
.sources
|
||||
.iter()
|
||||
.map(|source| (source.path.as_str(), source.source_digest.as_str()))
|
||||
.collect();
|
||||
let current_sources: BTreeMap<&str, &str> = current
|
||||
.sources
|
||||
.iter()
|
||||
.map(|source| (source.path.as_str(), source.source_digest.as_str()))
|
||||
.collect();
|
||||
for path in current_sources.keys() {
|
||||
if previous_sources.get(path) != current_sources.get(path) {
|
||||
changed_sources.push(path.to_string());
|
||||
}
|
||||
}
|
||||
for path in previous_sources.keys() {
|
||||
if !current_sources.contains_key(path) {
|
||||
changed_sources.push(path.to_string());
|
||||
}
|
||||
}
|
||||
added.sort();
|
||||
removed.sort();
|
||||
changed.sort();
|
||||
changed_sources.sort();
|
||||
let unchanged =
|
||||
added.is_empty() && removed.is_empty() && changed.is_empty() && changed_sources.is_empty();
|
||||
Drift {
|
||||
added_components: added,
|
||||
removed_components: removed,
|
||||
changed_components: changed,
|
||||
changed_sources,
|
||||
unchanged,
|
||||
}
|
||||
}
|
||||
|
||||
/// Select one loaded component and its visual subtree as an independent Design.
|
||||
pub fn slice(design: &Design, component: &str) -> Result<Design, LoadError> {
|
||||
if !design.definitions.contains_key(component) {
|
||||
return Err(design_error(
|
||||
"web.slice.unknown",
|
||||
format!("unknown component definition {component:?}"),
|
||||
));
|
||||
}
|
||||
let mut keys: BTreeSet<String> = BTreeSet::new();
|
||||
let mut queue = vec![component.to_string()];
|
||||
while let Some(key) = queue.pop() {
|
||||
if !keys.insert(key.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(definition) = design.definitions.get(&key) {
|
||||
for slot in &definition.slots {
|
||||
queue.push(slot.target.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let definitions: BTreeMap<String, ComponentDef> = design
|
||||
.definitions
|
||||
.iter()
|
||||
.filter(|(key, _)| keys.contains(*key))
|
||||
.map(|(key, definition)| (key.clone(), definition.clone()))
|
||||
.collect();
|
||||
let mut instances = Vec::new();
|
||||
collect_instances(&definitions, component, "root", &mut instances);
|
||||
let used_paths: BTreeSet<String> = definitions
|
||||
.values()
|
||||
.map(|definition| definition.source.path.clone())
|
||||
.collect();
|
||||
let sources = design
|
||||
.sources
|
||||
.iter()
|
||||
.filter(|source| used_paths.contains(&source.path))
|
||||
.cloned()
|
||||
.collect();
|
||||
Ok(Design {
|
||||
root: component.to_string(),
|
||||
root_dir: design.root_dir.clone(),
|
||||
definitions,
|
||||
instances,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
fn relative_link(base: Option<&Path>, root: &Path, path: &str) -> String {
|
||||
let Some(base) = base else {
|
||||
return path.to_string();
|
||||
};
|
||||
let target = root.join(path);
|
||||
let base_components: Vec<_> = base.components().collect();
|
||||
let target_components: Vec<_> = target.components().collect();
|
||||
let mut common = 0;
|
||||
while common < base_components.len()
|
||||
&& common < target_components.len()
|
||||
&& base_components[common] == target_components[common]
|
||||
{
|
||||
common += 1;
|
||||
}
|
||||
let mut relative = PathBuf::new();
|
||||
for _ in common..base_components.len() {
|
||||
relative.push("..");
|
||||
}
|
||||
for component in &target_components[common..] {
|
||||
relative.push(component.as_os_str());
|
||||
}
|
||||
relative.to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
fn push_source_link(out: &mut String, base: Option<&Path>, design: &Design, source: &SourceRef) {
|
||||
let link = relative_link(base, &design.root_dir, &source.path);
|
||||
out.push_str(&format!(
|
||||
"- [{}]({}#{}) — `sha256:{}`\n",
|
||||
source.path, link, source.anchor, source.source_digest
|
||||
));
|
||||
}
|
||||
|
||||
/// Derive the Markdown handoff from the model only; never re-reads sources.
|
||||
/// Links are project-relative (authoritative when the handoff stays in-project).
|
||||
pub fn handoff(design: &Design) -> String {
|
||||
handoff_with_base(design, None)
|
||||
}
|
||||
|
||||
/// Handoff whose source links are recomputed relative to an output directory.
|
||||
pub fn handoff_relative_to(design: &Design, output_dir: &Path) -> String {
|
||||
handoff_with_base(design, Some(output_dir))
|
||||
}
|
||||
|
||||
fn handoff_with_base(design: &Design, base: Option<&Path>) -> String {
|
||||
let graph = graph(design);
|
||||
let mut out = String::new();
|
||||
out.push_str("# Design handoff\n\n");
|
||||
out.push_str(&format!("root: `{}`\n\n", design.root));
|
||||
out.push_str("## Component tree\n\n");
|
||||
out.push_str(&format!("- design id: `{}`\n", design_id(design)));
|
||||
out.push_str(&format!("- root: `{}`\n\n", design.root));
|
||||
out.push_str("## Sources\n\n");
|
||||
for source in &design.sources {
|
||||
out.push_str(&format!(
|
||||
"- `{}` — `sha256:{}`\n",
|
||||
source.path, source.source_digest
|
||||
));
|
||||
}
|
||||
out.push_str("\n## Component tree\n\n");
|
||||
for instance in &design.instances {
|
||||
let definition = design.definitions.get(&instance.definition);
|
||||
let depth = instance.id.matches('/').count();
|
||||
let indent = " ".repeat(depth);
|
||||
out.push_str(&format!(
|
||||
"{indent}- `{}` ({})",
|
||||
"{indent}- `{}` → `{}`\n",
|
||||
instance.id, instance.definition
|
||||
));
|
||||
if let Some(definition) = definition {
|
||||
}
|
||||
out.push_str("\n## Design graph\n\n");
|
||||
out.push_str("Visual containment:\n");
|
||||
for (parent, child, slot) in &graph.visual_edges {
|
||||
out.push_str(&format!("- `{parent}` --{slot}--> `{child}`\n"));
|
||||
}
|
||||
out.push_str("\nNon-visual dependencies:\n");
|
||||
if graph.dependency_edges.is_empty() {
|
||||
out.push_str("- 未声明\n");
|
||||
}
|
||||
for (from, to, reason) in &graph.dependency_edges {
|
||||
out.push_str(&format!("- `{from}` -> `{to}`: {reason}\n"));
|
||||
}
|
||||
if !graph.dependency_cycles.is_empty() {
|
||||
out.push_str("\nDependency cycle groups (需要协调,不自动宣称可并行):\n");
|
||||
for group in &graph.dependency_cycles {
|
||||
out.push_str(&format!("- {}\n", group.join(" -> ")));
|
||||
}
|
||||
}
|
||||
out.push_str("\n## Components\n\n");
|
||||
for (key, definition) in &design.definitions {
|
||||
out.push_str(&format!("### `{key}`\n\n"));
|
||||
out.push_str("Source:\n");
|
||||
push_source_link(&mut out, base, design, &definition.source);
|
||||
let instances: Vec<&str> = design
|
||||
.instances
|
||||
.iter()
|
||||
.filter(|instance| &instance.definition == key)
|
||||
.map(|instance| instance.id.as_str())
|
||||
.collect();
|
||||
if !instances.is_empty() {
|
||||
out.push_str(&format!("\nInstances: {}\n", instances.join(", ")));
|
||||
}
|
||||
if !definition.content.is_empty() {
|
||||
out.push_str("\nResponsibility / visual notes:\n");
|
||||
for block in &definition.content {
|
||||
let text = block.text.trim();
|
||||
if !text.is_empty() {
|
||||
out.push_str(&format!(
|
||||
"- ({}) `{}`\n",
|
||||
block.kind,
|
||||
text.replace('`', "\\`").replace('\n', " ")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(&format!("\nLayout slots ({}):\n", definition.slots.len()));
|
||||
for slot in &definition.slots {
|
||||
out.push_str(&format!(
|
||||
" — {} [{}]",
|
||||
definition.source.path, definition.source.anchor
|
||||
"- row {} slot `{}` width `{}` -> `{}`\n",
|
||||
slot.row, slot.slot, slot.width, slot.target
|
||||
));
|
||||
}
|
||||
out.push('\n');
|
||||
if let Some(definition) = definition {
|
||||
for slot in &definition.slots {
|
||||
out.push_str(&format!(
|
||||
"{indent} - slot `{}` row {} {} -> `{}`\n",
|
||||
slot.slot, slot.row, slot.width, slot.target
|
||||
));
|
||||
}
|
||||
if !definition.inputs.is_empty() {
|
||||
out.push_str("\nInputs:\n");
|
||||
for input in &definition.inputs {
|
||||
out.push_str(&format!(
|
||||
"{indent} - input `{}` ({}) {}\n",
|
||||
"- `{}` ({}) {}\n",
|
||||
input.name, input.entry_type, input.description
|
||||
));
|
||||
}
|
||||
}
|
||||
if !definition.events.is_empty() {
|
||||
out.push_str("\nEvents:\n");
|
||||
for event in &definition.events {
|
||||
out.push_str(&format!(
|
||||
"{indent} - event `{}` ({}) {}\n",
|
||||
"- `{}` ({}) {}\n",
|
||||
event.name, event.data, event.description
|
||||
));
|
||||
}
|
||||
}
|
||||
if !definition.scenarios.is_empty() {
|
||||
out.push_str("\nScenarios:\n");
|
||||
for scenario in &definition.scenarios {
|
||||
out.push_str(&format!(
|
||||
"{indent} - scenario `{}`{} -> `{}#{}`\n",
|
||||
"- `{}`{} content `{}#{}`\n",
|
||||
scenario.state,
|
||||
if scenario.initial { " (initial)" } else { "" },
|
||||
scenario.content.path,
|
||||
scenario.content.anchor
|
||||
));
|
||||
}
|
||||
}
|
||||
if !definition.interactions.is_empty() {
|
||||
out.push_str("\nInteractions:\n");
|
||||
for interaction in &definition.interactions {
|
||||
out.push_str(&format!(
|
||||
"{indent} - transition `{}` --{}--> `{}`\n",
|
||||
"- `{}` --{}--> `{}`\n",
|
||||
interaction.current, interaction.event, interaction.next
|
||||
));
|
||||
}
|
||||
}
|
||||
if !definition.dependencies.is_empty() {
|
||||
out.push_str("\nDependencies:\n");
|
||||
for dependency in &definition.dependencies {
|
||||
out.push_str(&format!(
|
||||
"{indent} - dependency `{}`: {}\n",
|
||||
"- `{}`: {}\n",
|
||||
dependency.target, dependency.reason
|
||||
));
|
||||
}
|
||||
if let Some(acceptance) = &definition.acceptance {
|
||||
out.push_str(&format!(
|
||||
"{indent} - acceptance: {}\n",
|
||||
acceptance.text.replace('\n', " ")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str("\n## Sources\n\n");
|
||||
for source in &design.sources {
|
||||
out.push_str(&format!(
|
||||
"- `{}` digest `sha256:{}`\n",
|
||||
source.path, source.source_digest
|
||||
));
|
||||
if let Some(acceptance) = &definition.acceptance {
|
||||
out.push_str(&format!("\nAcceptance:\n{}\n", acceptance.text));
|
||||
}
|
||||
out.push_str("\n未实现/边界: 原型与模拟交付;真实业务功能、登录/支付/数据库/网络由目标应用实现;本 handoff 不生成生产代码。\n\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
+144
-12
@@ -3,7 +3,10 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use marqdo_web_design::{handoff, load, statistics, Error, LoadConfig};
|
||||
use marqdo_web_design::{
|
||||
design_id, drift, graph, handoff, handoff_relative_to, load, slice, statistics, Error,
|
||||
LoadConfig,
|
||||
};
|
||||
|
||||
static UNIQUE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -356,10 +359,13 @@ fn loads_full_leaf_contract_inputs_events_scenarios_interactions_dependencies()
|
||||
assert_eq!(a.dependencies[0].target, "components/b.mq.md#乙");
|
||||
assert!(a.acceptance.as_ref().unwrap().text.contains("模拟保存"));
|
||||
let text = handoff(&design);
|
||||
assert!(text.contains("scenario `empty` (initial)"));
|
||||
assert!(text.contains("transition `empty` --模拟保存--> `done`"));
|
||||
assert!(text.contains("dependency `components/b.mq.md#乙`"));
|
||||
assert!(text.contains("acceptance:"));
|
||||
assert!(text.contains("Scenarios:"));
|
||||
assert!(text.contains("`empty` (initial)"));
|
||||
assert!(text.contains("Interactions:"));
|
||||
assert!(text.contains("--模拟保存--> `done`"));
|
||||
assert!(text.contains("Dependencies:"));
|
||||
assert!(text.contains("`components/b.mq.md#乙`: 提交后展示详情"));
|
||||
assert!(text.contains("Acceptance:"));
|
||||
}
|
||||
|
||||
fn leaf_project(sections: &str) -> TempProject {
|
||||
@@ -456,15 +462,11 @@ fn rejects_invalid_inputs_dependencies_and_acceptance() {
|
||||
);
|
||||
|
||||
let unknown = leaf_project(
|
||||
"### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](target.mq.md#目标) | 需要 |\n",
|
||||
);
|
||||
unknown.write(
|
||||
"target.mq.md",
|
||||
"# 目标页面\n\n## @knowledge 目标\n\n### 内容\n\nx\n",
|
||||
"### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](missing.mq.md#目标) | 需要 |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&unknown.config("a.mq.md", "甲")).unwrap_err()),
|
||||
"web.dependency.unknown"
|
||||
"web.dependency.target"
|
||||
);
|
||||
|
||||
let empty = leaf_project("### 验收\n\n \n");
|
||||
@@ -550,7 +552,8 @@ fn projects_safe_content_blocks_for_components_and_scenarios() {
|
||||
.iter()
|
||||
.all(|scene| !scene.content_blocks.is_empty()));
|
||||
let text = handoff(&design);
|
||||
assert!(text.contains("scenario `only`"));
|
||||
assert!(text.contains("Scenarios:"));
|
||||
assert!(text.contains("`only`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -668,3 +671,132 @@ fn resolves_outside_scope_links_that_stay_inside_the_explicit_root() {
|
||||
"shared/b.mq.md#乙"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handoff_is_deterministic_and_contains_graph_sources_and_contracts() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n页面职责。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n| 1 | b | [B](b.mq.md#乙) | auto |\n",
|
||||
);
|
||||
project.write(
|
||||
"a.mq.md",
|
||||
"# A 组件\n\n## @knowledge 甲\n\n### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| x | Text | 输入 |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| only | [样例](states.mq.md#空状态) | true |\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [B](b.mq.md#乙) | 组合交付 |\n\n### 验收\n\n- A 可见。\n",
|
||||
);
|
||||
project.write(
|
||||
"b.mq.md",
|
||||
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nB 正文。\n",
|
||||
);
|
||||
project.write("states.mq.md", STATES);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
let first = handoff(&design);
|
||||
assert_eq!(first, handoff(&design));
|
||||
assert_eq!(
|
||||
first,
|
||||
handoff(&load(&project.config("index.mq.md", "工作台")).expect("reload"))
|
||||
);
|
||||
assert!(first.contains("design id:"));
|
||||
assert!(first.contains("## Sources"));
|
||||
assert!(first.contains("## Design graph"));
|
||||
assert!(first.contains("Visual containment:"));
|
||||
assert!(first.contains("Non-visual dependencies:"));
|
||||
assert!(first.contains("--a-->"));
|
||||
assert!(first.contains("`a.mq.md#甲`"));
|
||||
assert!(first.contains("Inputs:"));
|
||||
assert!(first.contains("Scenarios:"));
|
||||
assert!(first.contains("Acceptance:"));
|
||||
assert!(first.contains("未实现/边界"));
|
||||
assert!(first.contains("sha256:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handoff_relative_to_recomputes_source_links_for_another_directory() {
|
||||
let project = basic_project();
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
let out_dir = project.path.join("deliver/out");
|
||||
std::fs::create_dir_all(&out_dir).unwrap();
|
||||
let text = handoff_relative_to(&design, &out_dir);
|
||||
assert!(!text.contains(&format!("({}", project.path.display())));
|
||||
assert!(text.contains("../../components/leaf.mq.md#叶子"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drift_reports_changed_components_and_sources_only() {
|
||||
let project = basic_project();
|
||||
let before = load(&project.config("index.mq.md", "工作台")).expect("load v1");
|
||||
let before_id = design_id(&before);
|
||||
project.write(
|
||||
"components/nav.mq.md",
|
||||
"# 导航组件\n\n## @knowledge 导航\n\n### 内容\n\n更新后的导航正文。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | leaf | [叶子](leaf.mq.md#叶子) | auto |\n",
|
||||
);
|
||||
let after = load(&project.config("index.mq.md", "工作台")).expect("load v2");
|
||||
assert_ne!(before_id, design_id(&after));
|
||||
let report = drift(&before, &after);
|
||||
assert!(!report.unchanged);
|
||||
assert_eq!(report.changed_components, vec!["components/nav.mq.md#导航"]);
|
||||
assert_eq!(report.changed_sources, vec!["components/nav.mq.md"]);
|
||||
assert!(!report
|
||||
.changed_components
|
||||
.contains(&"components/leaf.mq.md#叶子".to_string()));
|
||||
assert!(drift(&after, &after).unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slice_keeps_only_the_visual_subtree_and_its_sources() {
|
||||
let project = basic_project();
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
let sliced = slice(&design, "components/nav.mq.md#导航").expect("slice");
|
||||
assert_eq!(sliced.root, "components/nav.mq.md#导航");
|
||||
assert_eq!(
|
||||
sliced.definitions.keys().cloned().collect::<Vec<_>>(),
|
||||
vec!["components/leaf.mq.md#叶子", "components/nav.mq.md#导航"]
|
||||
);
|
||||
let ids: Vec<&str> = sliced
|
||||
.instances
|
||||
.iter()
|
||||
.map(|item| item.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, vec!["root", "root/leaf"]);
|
||||
let sources: Vec<&str> = sliced
|
||||
.sources
|
||||
.iter()
|
||||
.map(|item| item.path.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sources,
|
||||
vec!["components/leaf.mq.md", "components/nav.mq.md"]
|
||||
);
|
||||
assert!(slice(&design, "missing").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_separates_visual_containment_from_design_dependencies() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n",
|
||||
);
|
||||
project.write(
|
||||
"a.mq.md",
|
||||
"# A 组件\n\n## @knowledge 甲\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [B](b.mq.md#乙) | 共享合同 |\n",
|
||||
);
|
||||
project.write(
|
||||
"b.mq.md",
|
||||
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nB。\n",
|
||||
);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
let graph = graph(&design);
|
||||
assert!(graph
|
||||
.visual_edges
|
||||
.iter()
|
||||
.any(|(parent, child, slot)| parent == "index.mq.md#工作台"
|
||||
&& child == "a.mq.md#甲"
|
||||
&& slot == "a"));
|
||||
assert!(graph
|
||||
.dependency_edges
|
||||
.iter()
|
||||
.any(|(from, to, reason)| from == "a.mq.md#甲"
|
||||
&& to == "b.mq.md#乙"
|
||||
&& reason == "共享合同"));
|
||||
assert!(graph.dependency_cycles.is_empty());
|
||||
}
|
||||
Reference in new issue
Block a user