Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0c9d727f1 | ||
|
|
efcf1a0fb4 | ||
|
|
b4f097bf9e | ||
|
|
a4d2e835b6 | ||
|
|
063f4b8794 | ||
|
|
cd636a5acf | ||
|
|
02d1ad172c | ||
|
|
e18b0b1b40 |
No files matched your search
@@ -0,0 +1 @@
|
||||
dist/
|
||||
@@ -0,0 +1,13 @@
|
||||
# Unified Woodpecker CI for a source-only Marqdo component.
|
||||
#
|
||||
# The published `marqdo-ci-shell` image is the only runtime dependency: one
|
||||
# Ubuntu 24.04 base, the released CLI/Bundle, and common test tools. No image
|
||||
# variance, apt install, Rust toolchain download, CLI rebuild or sibling checkout.
|
||||
when:
|
||||
event: [push, pull_request, manual]
|
||||
|
||||
steps:
|
||||
test:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
||||
commands:
|
||||
- sh scripts/test.sh
|
||||
@@ -0,0 +1,34 @@
|
||||
# Protected publish workflow: tag or manual only.
|
||||
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: std-io
|
||||
REPOSITORY: cflmy/marqdo-std-io
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${GITEA_PUBLISH_TOKEN:?gitea_publish_token secret missing}"
|
||||
test -n "${CI_COMMIT_TAG:?publish requires a tag}"
|
||||
export SOURCE_SHA="${CI_COMMIT_SHA}"
|
||||
export VERSION="${CI_COMMIT_TAG#v}"
|
||||
export TAG="${CI_COMMIT_TAG}"
|
||||
export COMPONENT_ID=std-io
|
||||
export REPOSITORY=cflmy/marqdo-std-io
|
||||
sh scripts/package.sh
|
||||
ARCHIVE="dist/marqdo-std-io-${VERSION}-source.tar.gz"
|
||||
python3 scripts/release/publish_gitea.py \
|
||||
--repo "cflmy/marqdo-std-io" \
|
||||
--tag "$TAG" \
|
||||
--target "$SOURCE_SHA" \
|
||||
--prerelease \
|
||||
--body "Automated source release for std-io $TAG." \
|
||||
--asset "$ARCHIVE" \
|
||||
--asset "${ARCHIVE}.sha256" \
|
||||
--asset dist/release-evidence.json \
|
||||
--evidence-out dist/gitea-publish-result.json
|
||||
@@ -0,0 +1,17 @@
|
||||
# Fast-path notification after a completed Gitea release.
|
||||
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
|
||||
test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
|
||||
python3 scripts/release/notify_root.py \
|
||||
--hint-component "std-io" \
|
||||
--hint-tag "${CI_COMMIT_TAG:-}"
|
||||
@@ -0,0 +1,37 @@
|
||||
<!-- marqdo:repo-conventions v1 -->
|
||||
# AGENTS.md — std-io
|
||||
|
||||
全局规范唯一来源:[marqdo 仓库开发规范](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md)。本文件只写本仓边界,不复制全局规范或合同正文。
|
||||
|
||||
## 1. 本仓定位与唯一权威
|
||||
|
||||
- catalog ID:`std-io`;父级:根;角色:stdlib;状态:active。
|
||||
- 职责/本仓拥有:Console、Stream、格式化与官方 print 别名目标
|
||||
- 本仓不拥有:CLI 语法/运行时、Bundle 打包实现、其它 stdlib 模块的算法或序列化
|
||||
- 权威输入/合同:真实 CLI `MARQDO_BIN` + 显式 `MARQDO_STDLIB_DIR` Bundle 的公开模块接口;根 Bundle 生产者
|
||||
|
||||
## 2. 必做 / 禁止
|
||||
|
||||
| 必做 | 禁止 |
|
||||
| --- | --- |
|
||||
| 只在本仓职责内修改,先开本仓工单 | 实现其它仓库功能,复制 parser/实现/合同 |
|
||||
| 用真实 CLI/制品与独立期望测试 | mock、字符串检查或原型冒充真实验收/PASS |
|
||||
| 依赖使用固定 SHA/摘要与显式输入 | 依赖父仓 checkout、兄弟仓相对路径、浮动分支 |
|
||||
| 未运行写 `UNVERIFIED` | 伪造 entry/版本/CI 徽章/gitlink/发布资产 |
|
||||
| 记录 SHA、制品摘要、平台、命令、退出码 | 提交密钥、凭证、构建产物或本地绝对路径 |
|
||||
| 跨仓变更走 C2 → B2 → A2 晋升 | 自动 tag/release/合并,或直接改父仓/兄弟仓 |
|
||||
|
||||
- 不新增第二 catalog/manifest/lock/版本表/发布流程;不为单功能拆仓或建空壳仓。
|
||||
- 不在本仓登记其它仓库后代路径;治理树最多两级 gitlink。
|
||||
|
||||
## 3. 构建、测试与证据
|
||||
|
||||
- CI/验收入口:`scripts/test.sh`(非交互、失败非零、不打印秘密、只写声明输出;构建与发布权限分离)。
|
||||
- 输入与依赖:真实 CLI `MARQDO_BIN` + 显式 `MARQDO_STDLIB_DIR` Bundle 的公开模块接口;根 Bundle 生产者
|
||||
- 交付:唯一模块源码 + 断言 + 确定性源码归档/证据(不强制二进制)
|
||||
- 证据:候选 SHA、依赖/制品 SHA-256、平台/工具链、命令与退出码、日志位置、测试范围;FAIL/UNVERIFIED 不得写成 PASS。
|
||||
|
||||
## 4. 工单路由
|
||||
|
||||
- 语言/模块加载/Bundle 协议 → `marqdo-cli`;Bundle 装配/路径 → 根 Bundle 生产者;模块语义 → 本仓。
|
||||
- 模块边界按迁移台账;不复制其它 stdlib 的算法或序列化实现。
|
||||
@@ -1,14 +1,39 @@
|
||||
# marqdo-std-io
|
||||
|
||||
本仓负责Console、Stream、格式化和官方 print 别名。当前状态为 `planned`。
|
||||
本仓负责Console、Stream、格式化和官方 print 别名。当前处于**标准库源码归位迁移**阶段:源码与断言已迁入本仓,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1))。
|
||||
|
||||
## 首项任务
|
||||
## 唯一公开入口(Bundle 根相对路径)
|
||||
|
||||
迁入 Console、Stream 和格式化,负责官方 `print` 与 `打印` 别名。
|
||||
| 发布路径 | 公开导入 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| `format.mq.md` | `std:format` | 值显示、列表显示与转义 |
|
||||
| `io.mq.md` | `std:io` | 官方 `print`/`打印` 别名目标 `写值` |
|
||||
| `io/console.mq.md` | `std:io/console` | stdin 读取行与 stdout 打印 |
|
||||
| `io/stream.mq.md` | `std:io/stream` | 短写检测与关闭语义 |
|
||||
|
||||
`modules/` 保存将来 Bundle 根下的相对路径;Bundle 与 `stdlib.json` 由父仓唯一生产者生成,本仓不维护第二份官方 manifest。
|
||||
|
||||
## 目录
|
||||
|
||||
- [modules/](modules/README.md) 存放对外发布的模块源码。
|
||||
- [tests/](tests/README.md) 存放独立验收用的输入和断言。
|
||||
- `modules/`:对外发布的模块源码(Bundle 根相对路径)。
|
||||
- `tests/`:迁入的 `.mq.md` 自测源与 `tests/cases/` 期望(observation 终值、stdout、参数、环境)。
|
||||
- `scripts/`:独立验收入口。
|
||||
|
||||
## 独立验收
|
||||
|
||||
只接受显式传入的已验证制品,不读取兄弟仓物理路径或浮动分支:
|
||||
|
||||
```sh
|
||||
MARQDO_BIN=/path/to/verified/marqdo \
|
||||
MARQDO_STDLIB_DIR=/path/to/installed/bundle \
|
||||
scripts/test.sh
|
||||
```
|
||||
|
||||
- `MARQDO_BIN`:真实 CLI 二进制;`MARQDO_STDLIB_DIR`:已安装且通过 manifest digest 校验、包含本仓模块的 Bundle。
|
||||
- 期望值来自迁移前基线的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。
|
||||
|
||||
## 边界
|
||||
|
||||
不实现语言内核、Host 权限或资源原语;`io/console` 与 `io/stream` 只包装现行 resource 原语,stdout/stderr 不混合;`io.mq.md#写值` 保持官方 `print`/`打印` 别名目标、签名与 effects 不变,不接管别名元数据。
|
||||
|
||||
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
|
||||
@@ -0,0 +1,334 @@
|
||||
|
||||
# @exec format
|
||||
## 字节长度
|
||||
|
||||
`params(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
**总字节 = 0**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
|
||||
`if 码点 < 128`
|
||||
|
||||
**总字节 = 总字节 + 1**
|
||||
|
||||
`else`
|
||||
`if 码点 < 2048`
|
||||
|
||||
**总字节 = 总字节 + 2**
|
||||
|
||||
`else`
|
||||
`if 码点 < 65536`
|
||||
|
||||
**总字节 = 总字节 + 3**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**总字节 = 总字节 + 4**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
`return 总字节`
|
||||
|
||||
## 显示
|
||||
|
||||
`params(值)`
|
||||
|
||||
按语言值语义格式化,用于与内置 打印 的输出对照。
|
||||
覆盖 Unit/None/Bool/Int/Float/Text/List/Map/Table/Formula/Code/
|
||||
FunctionRef/PluginHandle/Memory/Resource。
|
||||
|
||||
**类别 = 类型(值)**
|
||||
|
||||
`if 类别 == "Unit"`
|
||||
|
||||
`return "Unit"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "None"`
|
||||
|
||||
`return "None"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Text"`
|
||||
|
||||
`return 值`
|
||||
|
||||
`else`
|
||||
`if 类别 == "List"`
|
||||
|
||||
`return 列表显示(值)`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Map"`
|
||||
|
||||
`return 映射显示(值)`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Table"`
|
||||
|
||||
`return 表格显示(值)`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Formula"`
|
||||
|
||||
`return "Formula(" + 转义文本(值.latex) + ")"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Code"`
|
||||
|
||||
`return "Code(" + 转义文本(值.language) + ", " + 文本(字节长度(值.source)) + " bytes)"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "FunctionRef"`
|
||||
|
||||
`return "FunctionRef(" + 值.module + "::" + 值.name + ")"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "PluginHandle"`
|
||||
|
||||
`return "PluginHandle(" + 值.plugin + "::" + 值.export + ")"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Memory"`
|
||||
|
||||
`return "Memory"`
|
||||
|
||||
`else`
|
||||
`if 类别 == "Resource"`
|
||||
|
||||
`return "Resource"`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return 文本(值)`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 列表显示
|
||||
|
||||
`params(列表)`
|
||||
|
||||
**结果 = "["**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + ", "**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 值显示(列表[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
`return 结果 + "]"`
|
||||
|
||||
## 映射显示
|
||||
|
||||
`params(映射)`
|
||||
|
||||
**键 = map.keys(映射)**
|
||||
|
||||
**结果 = "{"**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(键)`
|
||||
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + ", "**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**当前键 = 键[下标]**
|
||||
|
||||
**结果 = 结果 + 当前键 + ": " + 值显示(map.get(映射, 当前键))**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
`return 结果 + "}"`
|
||||
|
||||
## 表格显示
|
||||
|
||||
`params(表格)`
|
||||
|
||||
**列 = table.columns(表格)**
|
||||
|
||||
**结果 = "Table[" + 连接文本(列, " | ") + "]{"**
|
||||
|
||||
**行号 = 0**
|
||||
|
||||
`while 行号 < 长度(表格)`
|
||||
|
||||
`if 行号 > 0`
|
||||
|
||||
**结果 = 结果 + "; "**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**行 = table.row(表格, 行号)**
|
||||
|
||||
**单元格 = []**
|
||||
|
||||
**列号 = 0**
|
||||
|
||||
`while 列号 < 长度(行)`
|
||||
|
||||
**单元格 = list.append(单元格, 显示(行[列号]))**
|
||||
|
||||
**列号 = 列号 + 1**
|
||||
|
||||
`end`
|
||||
**结果 = 结果 + 连接文本(单元格, " | ")**
|
||||
|
||||
**行号 = 行号 + 1**
|
||||
|
||||
`end`
|
||||
`return 结果 + "}"`
|
||||
|
||||
## 连接文本
|
||||
|
||||
`params(列表, 分隔)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(列表)`
|
||||
|
||||
`if 下标 > 0`
|
||||
|
||||
**结果 = 结果 + 分隔**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**结果 = 结果 + 列表[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
`return 结果`
|
||||
|
||||
## 值显示
|
||||
|
||||
`params(值)`
|
||||
|
||||
列表/映射/表格内部使用 repr 语义:Text 带引号并转义,其它值递归显示。
|
||||
|
||||
**类别 = 类型(值)**
|
||||
|
||||
`if 类别 == "Text"`
|
||||
|
||||
`return 转义文本(值)`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return 显示(值)`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 转义文本
|
||||
|
||||
`params(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
**`结果 = "\""`**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(点)`
|
||||
|
||||
**码点 = 点[下标]**
|
||||
|
||||
`if 码点 == 34`
|
||||
|
||||
**`结果 = 结果 + "\\\""`**
|
||||
|
||||
`else`
|
||||
`if 码点 == 92`
|
||||
|
||||
**`结果 = 结果 + "\\\\"`**
|
||||
|
||||
`else`
|
||||
`if 码点 == 10`
|
||||
|
||||
**`结果 = 结果 + "\\n"`**
|
||||
|
||||
`else`
|
||||
`if 码点 == 9`
|
||||
|
||||
**`结果 = 结果 + "\\t"`**
|
||||
|
||||
`else`
|
||||
`if 码点 == 13`
|
||||
|
||||
**`结果 = 结果 + "\\r"`**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(码点)**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
``return 结果 + "\""``
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
import:
|
||||
format: "./format.mq.md"
|
||||
stream: "./io/stream.mq.md"
|
||||
console: "./io/console.mq.md"
|
||||
---
|
||||
|
||||
# @exec io
|
||||
|
||||
## 写文本
|
||||
|
||||
`params(文本)`
|
||||
|
||||
`return stream.写文本(文本)`
|
||||
|
||||
## 写全部
|
||||
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
`return stream.写全部(流, 内存, 起点, 长度)`
|
||||
|
||||
## 写值
|
||||
|
||||
`params(值)`
|
||||
|
||||
按语言值语义格式化后输出,并追加换行。
|
||||
|
||||
`return stream.写文本(format.显示(值) + "\n")`
|
||||
|
||||
## 读取行
|
||||
|
||||
`params()`
|
||||
|
||||
`return console.读取行()`
|
||||
|
||||
## 打印
|
||||
|
||||
`params(值)`
|
||||
|
||||
`return console.打印(值)`
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
import:
|
||||
format: "../format.mq.md"
|
||||
stream: "./stream.mq.md"
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec console
|
||||
|
||||
## 读取行
|
||||
|
||||
`params()`
|
||||
|
||||
从已授权的 stdio/stdin 资源读取一行。按有界块读取并增量解码 UTF-8;
|
||||
EOF 返回 {ok:false, code:"io.eof"},无效 UTF-8 返回可恢复错误。
|
||||
|
||||
**流 = resource.open("stdio", "stdin", ["read"])**
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**字节 = []**
|
||||
|
||||
**结束 = false**
|
||||
|
||||
**错误 = ""**
|
||||
|
||||
`while not 结束`
|
||||
|
||||
**读取 = resource.read(流, 内存, 0, 1)**
|
||||
|
||||
`if not 读取.ok`
|
||||
|
||||
**结束 = true**
|
||||
|
||||
**错误 = 读取.code**
|
||||
|
||||
`else`
|
||||
`if 读取.value.eof and 读取.value.count == 0`
|
||||
|
||||
**结束 = true**
|
||||
|
||||
`else`
|
||||
`if 内存[0] == 10`
|
||||
|
||||
**结束 = true**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**字节 = list.append(字节, 内存[0])**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
`if 错误 != ""`
|
||||
|
||||
`return {ok: false, code: 错误, message: "stdin read failed"}`
|
||||
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
`return 关闭`
|
||||
|
||||
`else`
|
||||
`if 长度(字节) == 0`
|
||||
|
||||
`return {ok: false, code: "io.eof", message: "end of input"}`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**数据长度 = 长度(字节)**
|
||||
|
||||
`if 数据长度 > 0 and 字节[数据长度 - 1] == 13`
|
||||
|
||||
**数据长度 = 数据长度 - 1**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
**页 = (数据长度 + 65535) // 65536**
|
||||
|
||||
**数据 = memory.new(页, 页)**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 数据长度`
|
||||
|
||||
**`数据[下标] = 字节[下标]`**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
**解码 = utf8.解码(数据, 0, 数据长度)**
|
||||
|
||||
`if not 解码.ok`
|
||||
|
||||
`return 解码`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return {ok: true, value: 解码.value}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 打印
|
||||
|
||||
`params(值)`
|
||||
|
||||
**结果 = stream.写文本(format.显示(值) + "\n")**
|
||||
|
||||
`if not 结果.ok`
|
||||
|
||||
`return 结果`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return {ok: true, value: None}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 写文本
|
||||
|
||||
`params(文本)`
|
||||
|
||||
`return stream.写文本(文本)`
|
||||
|
||||
## 写全部
|
||||
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
`return stream.写全部(流, 内存, 起点, 长度)`
|
||||
@@ -0,0 +1,122 @@
|
||||
---
|
||||
import:
|
||||
format: "../format.mq.md"
|
||||
utf8: "../text/utf8.mq.md"
|
||||
---
|
||||
|
||||
# @exec stream
|
||||
|
||||
## 页数
|
||||
|
||||
`params(字节)`
|
||||
|
||||
**页 = (字节 + 65535) // 65536**
|
||||
|
||||
`if 页 == 0`
|
||||
|
||||
`return 1`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return 页`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
## 写全部
|
||||
|
||||
`params(流, 内存, 起点, 长度)`
|
||||
|
||||
把 长度 字节从 内存 写到资源流。短写只返回实际数量,调用方继续;
|
||||
零进度返回 io.write_zero,不静默吞掉失败。
|
||||
|
||||
**已写 = 0**
|
||||
|
||||
**失败 = false**
|
||||
|
||||
**本次 = {ok: true, value: {count: 0}}**
|
||||
|
||||
**错误结果 = {ok: false, code: "io.write_zero", message: "resource.write made no progress"}**
|
||||
|
||||
`while 已写 < 长度`
|
||||
|
||||
**剩余 = 长度 - 已写**
|
||||
|
||||
**本次 = resource.write(流, 内存, 起点 + 已写, 剩余)**
|
||||
|
||||
`if not 本次.ok`
|
||||
|
||||
**失败 = true**
|
||||
|
||||
**错误结果 = 本次**
|
||||
|
||||
**已写 = 长度**
|
||||
|
||||
`else`
|
||||
`if 本次.value.count == 0`
|
||||
|
||||
**失败 = true**
|
||||
|
||||
**已写 = 长度**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**已写 = 已写 + 本次.value.count**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
`if 失败`
|
||||
|
||||
`return 错误结果`
|
||||
|
||||
`else`
|
||||
`if 已写 < 长度`
|
||||
|
||||
`return 错误结果`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return {ok: true, value: {count: 长度}}`
|
||||
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
## 写文本
|
||||
|
||||
`params(文本)`
|
||||
|
||||
把文本编码为 UTF-8 并写入已授权的 stdout 资源流。内存按实际字节长度增长,
|
||||
写入循环检查 {ok,count};只有全部字节写完并关闭成功才返回成功。
|
||||
|
||||
**字节数 = format.字节长度(文本)**
|
||||
|
||||
**内存 = memory.new(页数(字节数), 页数(字节数))**
|
||||
|
||||
**长度 = utf8.编码(文本, 内存, 0)**
|
||||
|
||||
**流 = resource.open("stdio", "stdout", ["write"])**
|
||||
|
||||
**写结果 = 写全部(流, 内存, 0, 长度)**
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
`if not 写结果.ok`
|
||||
|
||||
`return 写结果`
|
||||
|
||||
`else`
|
||||
`if not 关闭.ok`
|
||||
|
||||
`return 关闭`
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
`return {ok: true, value: {count: 长度}}`
|
||||
`end`
|
||||
`end`
|
||||
`end`
|
||||
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())
|
||||
Executable
+207
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run this component's public `.mq.md` self-tests against a real CLI Bundle.
|
||||
|
||||
Inputs are explicit and never discovered from sibling checkouts:
|
||||
|
||||
* ``MARQDO_BIN`` verified ``marqdo`` executable;
|
||||
* ``MARQDO_STDLIB_DIR`` Bundle that already installs this component's modules at
|
||||
their frozen bundle paths (the Bundle identity is the caller's responsibility;
|
||||
the CLI itself verifies the manifest digest before loading a module).
|
||||
|
||||
Each ``tests/cases/*.json`` file pins one self-test: the source file, stdin, CLI
|
||||
flags, environment, the expected bundle module path and the expected observation
|
||||
terminal value / stdout. The expected values are the baseline captured from the
|
||||
pre-migration CLI Bundle; a change is a public behaviour change and must be
|
||||
reviewed as one.
|
||||
|
||||
Usage: scripts/test.sh [CASE_NAME...]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
CASES = REPO / "tests" / "cases"
|
||||
SCHEMA = "marqdo.stdlib-test-case"
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class CaseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _substitute(value, bin_version: str):
|
||||
if isinstance(value, dict):
|
||||
if set(value) == {"$bin_version"}:
|
||||
return bin_version
|
||||
return {key: _substitute(item, bin_version) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_substitute(item, bin_version) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def _channel_text(events: list[dict], channel: str) -> str:
|
||||
chunks = []
|
||||
for event in events:
|
||||
if event.get("kind") != channel:
|
||||
continue
|
||||
payload = event["payload"]
|
||||
data = base64.b64decode(payload["data_base64"])
|
||||
if len(data) != payload["byte_count"]:
|
||||
raise CaseError(f"{channel} byte_count does not match decoded bytes")
|
||||
chunks.append(data)
|
||||
return b"".join(chunks).decode("utf-8")
|
||||
|
||||
|
||||
def _run_case(case: dict, case_path: Path, binary: str, bundle: Path) -> None:
|
||||
name = case["name"]
|
||||
module = case.get("require_module")
|
||||
if module and not (bundle / module).is_file():
|
||||
raise CaseError(f"{name}: Bundle {bundle} does not install {module}")
|
||||
source = REPO / "tests" / case["file"]
|
||||
if not source.is_file():
|
||||
raise CaseError(f"{name}: missing test source {source}")
|
||||
for relative in case.get("clean", []):
|
||||
target = (REPO / relative).resolve()
|
||||
if REPO not in target.parents:
|
||||
raise CaseError(f"{name}: clean path escapes the repository")
|
||||
if target.is_dir():
|
||||
shutil.rmtree(target)
|
||||
elif target.exists():
|
||||
target.unlink()
|
||||
env = os.environ.copy()
|
||||
env["MARQDO_STDLIB_DIR"] = str(bundle)
|
||||
for key, value in case.get("env", {}).items():
|
||||
env[key] = str(value).replace("$MARQDO_BIN", binary)
|
||||
version = subprocess.run(
|
||||
[binary, "--version"], capture_output=True, text=True, check=True
|
||||
).stdout
|
||||
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
|
||||
command = [binary, "run", str(source), *args, "--output", "json"]
|
||||
result = subprocess.run(
|
||||
command,
|
||||
cwd=REPO,
|
||||
env=env,
|
||||
input=case.get("stdin", "").encode(),
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise CaseError(
|
||||
f"{name}: CLI exited {result.returncode}\nstderr:\n"
|
||||
f"{result.stderr.decode(errors='replace')}"
|
||||
)
|
||||
try:
|
||||
report = json.loads(result.stdout)
|
||||
except json.JSONDecodeError as error:
|
||||
raise CaseError(f"{name}: CLI did not emit a JSON report: {error}") from error
|
||||
if report.get("run", {}).get("status") != "ok":
|
||||
raise CaseError(f"{name}: run status is not ok: {report.get('run')}")
|
||||
events = report.get("events") or []
|
||||
if not events or events[-1].get("kind") not in (
|
||||
"run.completed",
|
||||
"run.failed",
|
||||
"run.rejected",
|
||||
):
|
||||
raise CaseError(f"{name}: report has no terminal event")
|
||||
terminal = events[-1]["payload"]
|
||||
if terminal.get("status") != "ok":
|
||||
raise CaseError(f"{name}: terminal status is not ok: {terminal.get('status')}")
|
||||
actual_value = terminal.get("value")
|
||||
expected_value = _substitute(case["expected_terminal"], version)
|
||||
if actual_value != expected_value:
|
||||
raise CaseError(
|
||||
f"{name}: terminal value changed\nexpected: "
|
||||
f"{json.dumps(expected_value, ensure_ascii=False, sort_keys=True)}\n"
|
||||
f"actual: {json.dumps(actual_value, ensure_ascii=False, sort_keys=True)}"
|
||||
)
|
||||
expected_stdout = case.get("expected_stdout", "")
|
||||
actual_stdout = _channel_text(events, "stdout.chunk")
|
||||
if actual_stdout != expected_stdout:
|
||||
raise CaseError(
|
||||
f"{name}: stdout changed: expected {expected_stdout!r}, got {actual_stdout!r}"
|
||||
)
|
||||
for check in case.get("event_checks", []):
|
||||
matching = [
|
||||
event
|
||||
for event in events
|
||||
if event.get("kind") == check["kind"]
|
||||
and all(
|
||||
_dig(event.get("payload"), pointer) == expected
|
||||
for pointer, expected in check.get("payload", {}).items()
|
||||
)
|
||||
]
|
||||
if not matching:
|
||||
raise CaseError(
|
||||
f"{name}: no {check['kind']} event matched {check.get('payload')}"
|
||||
)
|
||||
|
||||
|
||||
def _dig(value, pointer: str):
|
||||
current = value
|
||||
for part in pointer.split("."):
|
||||
if isinstance(current, list):
|
||||
current = current[int(part)]
|
||||
elif isinstance(current, dict):
|
||||
current = current[part]
|
||||
else:
|
||||
return object()
|
||||
return current
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("cases", nargs="*", help="case names to run")
|
||||
args = parser.parse_args()
|
||||
binary = os.environ.get("MARQDO_BIN")
|
||||
bundle = os.environ.get("MARQDO_STDLIB_DIR")
|
||||
if not binary or not shutil.which(binary):
|
||||
print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr)
|
||||
return 2
|
||||
if not bundle or not Path(bundle).is_dir():
|
||||
print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr)
|
||||
return 2
|
||||
bundle = Path(bundle).resolve()
|
||||
paths = sorted(CASES.glob("*.json"))
|
||||
if not paths:
|
||||
print("no test cases in tests/cases", file=sys.stderr)
|
||||
return 2
|
||||
selected = set(args.cases)
|
||||
failures = 0
|
||||
ran = 0
|
||||
for path in paths:
|
||||
try:
|
||||
case = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as error:
|
||||
print(f"FAIL {path.name}: invalid JSON: {error}", file=sys.stderr)
|
||||
failures += 1
|
||||
continue
|
||||
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
|
||||
print(f"FAIL {path.name}: unsupported case schema", file=sys.stderr)
|
||||
failures += 1
|
||||
continue
|
||||
if selected and case["name"] not in selected:
|
||||
continue
|
||||
ran += 1
|
||||
try:
|
||||
_run_case(case, path, binary, bundle)
|
||||
print(f"PASS {case['name']}")
|
||||
except CaseError as error:
|
||||
print(f"FAIL {error}", file=sys.stderr)
|
||||
failures += 1
|
||||
if failures:
|
||||
print(f"{failures} of {ran} cases failed", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{ran} cases passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Explicit inputs only: a verified CLI binary and a Bundle that installs this
|
||||
# component's modules at their frozen paths. Never discovers sibling checkouts.
|
||||
set -eu
|
||||
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
|
||||
: "${MARQDO_STDLIB_DIR:?set MARQDO_STDLIB_DIR to the installed Bundle}"
|
||||
exec python3 "$(dirname "$0")/run_cases.py" "$@"
|
||||
+5
-1
@@ -1,3 +1,7 @@
|
||||
# 验收测试
|
||||
|
||||
首个功能附带正例和失败用例,记录所用 CLI 提交或发行版本以及实际运行命令。
|
||||
`tests/*.mq.md` 是从迁移前 CLI 官方标准库自测迁入的真实测试源;`tests/cases/*.json` 固定每个测试的输入(stdin、CLI 参数、环境、所需 Bundle 模块)和期望结果(observation 终值、stdout、必要的资源事件)。
|
||||
|
||||
运行入口是 `scripts/test.sh`,它要求显式传入 `MARQDO_BIN` 与 `MARQDO_STDLIB_DIR`。缺少制品、Bundle 缺少模块或 digest 校验失败时必须失败,不得回退到其它目录。
|
||||
|
||||
期望值取自迁移前基线 Bundle(`sha256:5407d36...`)与已验证候选 CLI 的真实执行结果;任何期望值改动都必须作为公开行为变化单独评审并记录证据。
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"schema": "marqdo.stdlib-test-case",
|
||||
"schema_version": 1,
|
||||
"name": "console",
|
||||
"file": "console.mq.md",
|
||||
"require_module": "io/console.mq.md",
|
||||
"args": [],
|
||||
"stdin": "hello\n",
|
||||
"env": {},
|
||||
"expected_stdout": "",
|
||||
"expected_terminal": {
|
||||
"items": [
|
||||
{
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "hello"
|
||||
}
|
||||
],
|
||||
"type": "list"
|
||||
},
|
||||
"event_checks": [
|
||||
{
|
||||
"kind": "effect",
|
||||
"payload": {
|
||||
"operation": "resource.read"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"schema": "marqdo.stdlib-test-case",
|
||||
"schema_version": 1,
|
||||
"name": "format",
|
||||
"file": "format.mq.md",
|
||||
"require_module": "format.mq.md",
|
||||
"args": [],
|
||||
"stdin": "",
|
||||
"env": {},
|
||||
"expected_stdout": "",
|
||||
"expected_terminal": {
|
||||
"items": [
|
||||
{
|
||||
"decimal": "3",
|
||||
"type": "int"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "[\"文本\", 2, 1.5]"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "{a: 1}"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "[\"a\", 2]"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "None"
|
||||
}
|
||||
],
|
||||
"type": "list"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schema": "marqdo.stdlib-test-case",
|
||||
"schema_version": 1,
|
||||
"name": "io",
|
||||
"file": "io.mq.md",
|
||||
"require_module": "io.mq.md",
|
||||
"args": [],
|
||||
"stdin": "",
|
||||
"env": {},
|
||||
"expected_stdout": "stdlib self-test\n",
|
||||
"expected_terminal": {
|
||||
"type": "none"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "marqdo.stdlib-test-case",
|
||||
"schema_version": 1,
|
||||
"name": "stream",
|
||||
"file": "stream.mq.md",
|
||||
"require_module": "io/stream.mq.md",
|
||||
"args": [],
|
||||
"stdin": "",
|
||||
"env": {},
|
||||
"expected_stdout": "stream\n",
|
||||
"expected_terminal": {
|
||||
"items": [
|
||||
{
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"decimal": "7",
|
||||
"type": "int"
|
||||
}
|
||||
],
|
||||
"type": "list"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
import:
|
||||
console: "std:io/console"
|
||||
---
|
||||
|
||||
# @exec console
|
||||
|
||||
## main
|
||||
|
||||
**行 = console.读取行()**
|
||||
|
||||
`return [行.ok, 行.value]`
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
import:
|
||||
format: "std:format"
|
||||
---
|
||||
|
||||
# @exec format
|
||||
|
||||
## main
|
||||
|
||||
`return [format.字节长度("Aé"), format.显示(["文本", 2, 1.5]), format.显示({a: 1}), format.列表显示(["a", 2]), format.显示(None)]`
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
import:
|
||||
io: "std:io"
|
||||
---
|
||||
|
||||
# @exec io
|
||||
|
||||
## main
|
||||
|
||||
> **io.写值("stdlib self-test")**
|
||||
|
||||
`return None`
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
import:
|
||||
stream: "std:io/stream"
|
||||
---
|
||||
|
||||
# @exec stream
|
||||
|
||||
## main
|
||||
|
||||
**结果 = stream.写文本("stream\n")**
|
||||
|
||||
`return [结果.ok, 结果.value.count]`
|
||||
Reference in new issue
Block a user