Compare commits

...
Author SHA1 Message Date
cflmy 63bceae587 migrate: own fs/file and path sources with host-authorization assertions
Move the official stdlib file and path modules to their unique source authority
without changing public paths or host authorization. Carry the pre-migration
product assertions, including the bounded read and cleanup semantics.

Refs cflmy/marqdo#9, cflmy/marqdo-std-fs#1
2026-11-26 23:30:29 +08:00
10 changed files with 893 additions and 6 deletions

No files matched your search

+28 -5
View File
@@ -1,14 +1,37 @@
# marqdo-std-fs # marqdo-std-fs
本仓负责文件、目录与路径。当前状态为 `planned`。 本仓负责文件、目录与词法路径。当前处于**标准库源码归位迁移**阶段:源码与断言已迁入本仓,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-std-fs/issues/1))。
## 首项任务 ## 唯一公开入口(Bundle 根相对路径)
迁入文件、路径和目录操作,核验读写边界。 | 发布路径 | 公开导入 | 职责 |
| --- | --- | --- |
| `fs/file.mq.md` | `std:fs/file` | 有界文件读写、目录遍历与删除 |
| `path.mq.md` | `std:path` | 纯词法 join/basename/dirname/normalize |
`modules/` 保存将来 Bundle 根下的相对路径;Bundle 与 `stdlib.json` 由父仓唯一生产者生成,本仓不维护第二份官方 manifest。
## 目录 ## 目录
- [modules/](modules/README.md) 存放对外发布的模块源码。 - `modules/`:对外发布的模块源码(Bundle 根相对路径)。
- [tests/](tests/README.md) 存放独立验收用的输入和断言。 - `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 负责,库只做薄封装;`path` 不进行 I/O。保留基线中的 8 MiB 有界读取、close 写入、非递归删除与既有错误。
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md) [生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
+237
View File
@@ -0,0 +1,237 @@
---
import:
utf8: "../text/utf8.mq.md"
---
# @exec file
## 读文本
`params(路径)`
以 UTF-8 读取一个有界的项目文件。文件在打开时整文件载入,上限 8 MiB;
结果使用可恢复 Result 形状。
**流 = resource.open("file", 路径, ["read"])**
**内存 = memory.new(128, 128)**
**读取 = resource.read(流, 内存, 0, 8388608)**
**关闭 = resource.close(流)**
`if not 读取.ok`
`return 读取`
`else`
`if not 关闭.ok`
`return 关闭`
`else`
`if true`
**文本 = utf8.解码(内存, 0, 读取.value.count)**
`if not 文本.ok`
`return 文本`
`else`
`if true`
`return {ok: true, value: 文本.value}`
`end`
`end`
`end`
`end`
`end`
## 写文本
`params(路径, 文本)`
把文本按 UTF-8 写入项目文件。路径必须已经通过 fs_write 授权;
文件只在 resource.close 成功时创建或覆盖,写入缓冲上限 8 MiB。
**内存 = memory.new(128, 128)**
**长度 = utf8.编码(文本, 内存, 0)**
**流 = resource.open("file", 路径, ["write"])**
**写入 = resource.write(流, 内存, 0, 长度)**
**关闭 = resource.close(流)**
`if not 写入.ok`
`return 写入`
`else`
`if not 关闭.ok`
`return 关闭`
`else`
`if true`
`return {ok: true, value: {count: 写入.value.count}}`
`end`
`end`
`end`
## 复制文件
`params(源, 目标)`
按字节复制一个有界的项目文件。源读取和目标写入分别需要
fs_read/fs_write 授权,结果值与 [写文本](#写文本) 相同。
**输入 = resource.open("file", 源, ["read"])**
**内存 = memory.new(128, 128)**
**读取 = resource.read(输入, 内存, 0, 8388608)**
**关闭输入 = resource.close(输入)**
`if not 读取.ok`
`return 读取`
`else`
`if not 关闭输入.ok`
`return 关闭输入`
`else`
`if true`
**输出 = resource.open("file", 目标, ["write"])**
**写入 = resource.write(输出, 内存, 0, 读取.value.count)**
**关闭输出 = resource.close(输出)**
`if not 写入.ok`
`return 写入`
`else`
`if not 关闭输出.ok`
`return 关闭输出`
`else`
`if true`
`return {ok: true, value: {count: 写入.value.count}}`
`end`
`end`
`end`
`end`
`end`
`end`
## 存在
`params(路径)`
`return resource.request("fs.exists", [路径])`
## 元数据
`params(路径)`
`return resource.request("fs.metadata", [路径])`
## 是文件
`params(路径)`
**元数据 = resource.request("fs.metadata", [路径])**
`if not 元数据.ok`
`return 元数据`
`else`
`if true`
`return {ok: true, value: 元数据.value.kind == "file"}`
`end`
`end`
## 是目录
`params(路径)`
**元数据 = resource.request("fs.metadata", [路径])**
`if not 元数据.ok`
`return 元数据`
`else`
`if true`
`return {ok: true, value: 元数据.value.kind == "directory"}`
`end`
`end`
## 列出目录
`params(路径)`
`return resource.request("fs.list", [路径])`
## 创建目录
`params(路径)`
`return resource.request("fs.mkdir", [路径])`
## 删除
`params(路径)`
删除一个文件或空目录。非空目录返回 fs.not_empty,不递归删除。
`return resource.request("fs.remove", [路径])`
## 重命名
`params(源, 目标)`
目标已存在时返回 fs.exists,不覆盖。
`return resource.request("fs.rename", [源, 目标])`
## 追加文本
`params(路径, 文本)`
把文本追加到项目文件;文件不存在时创建。仍受 8 MiB 单次读取上限和
fs_write 授权约束。
`return resource.request("fs.append", [路径, 文本])`
## 读取片段
`params(路径, 偏移, 长度)`
从偏移处读取最多 长度 字节,按 UTF-8 解码后返回文本。偏移/长度必须
是非负整数,长度上限 8 MiB。
`return resource.request("fs.read_at", [路径, 偏移, 长度])`
## 遍历
`params(路径)`
递归列出目录下的普通文件,返回相对项目根的路径列表。跳过符号链接,
深度上限 64,条目上限 4096。
`return resource.request("fs.walk", [路径])`
+211
View File
@@ -0,0 +1,211 @@
# @exec path
## 是否绝对
`params(路径)`
**点 = text.codepoints(路径)**
`if 长度(点) == 0`
`return false`
`else`
`if 点[0] == 47`
`return true`
`end`
`end`
`return false`
## 分割
`params(文本, 分隔码点)`
**点 = text.codepoints(文本)**
**结果 = []**
**当前 = ""**
**下标 = 0**
`while 下标 < 长度(点)`
`if 点[下标] == 分隔码点`
**结果 = list.append(结果, 当前)**
**当前 = ""**
`else`
`if true`
**当前 = 当前 + text.from_codepoint(点[下标])**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return list.append(结果, 当前)`
## 连接
`params(片段列表)`
空片段被跳过,片段之间只插入一个 /。
**结果 = ""**
**下标 = 0**
`while 下标 < 长度(片段列表)`
**片段 = 文本(片段列表[下标])**
`if 片段 != ""`
`if 结果 == ""`
**结果 = 片段**
`else`
`if true`
**结果 = 结果 + "/" + 片段**
`end`
`end`
`else`
`if true`
**忽略 = 0**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 结果`
## 文件名
`params(路径)`
**片段 = 分割(路径, 47)**
`return 片段[长度(片段) - 1]`
## 目录名
`params(路径)`
**片段 = 分割(路径, 47)**
**结果 = []**
**下标 = 0**
`while 下标 < 长度(片段) - 1`
**结果 = list.append(结果, 片段[下标])**
**下标 = 下标 + 1**
`end`
`return 连接(结果)`
## 扩展名
`params(路径)`
**名字 = 文件名(路径)**
**点列表 = 分割(名字, 46)**
`if 长度(点列表) <= 1`
`return ""`
`end`
`return 点列表[长度(点列表) - 1]`
## 去尾
`params(列表)`
**结果 = []**
**下标 = 0**
`while 下标 < 长度(列表) - 1`
**结果 = list.append(结果, 列表[下标])**
**下标 = 下标 + 1**
`end`
`return 结果`
## 规范
`params(路径)`
词法规范化:折叠 .、空片段和重复 /,用 .. 消去前一片段;
绝对路径保留前导 /。不访问文件系统。
**片段 = 分割(路径, 47)**
**绝对 = 是否绝对(路径)**
**栈 = []**
**下标 = 0**
`while 下标 < 长度(片段)`
**段 = 片段[下标]**
`if 段 == "" or 段 == "."`
**忽略 = 0**
`else`
`if 段 == ".."`
`if 长度(栈) > 0 and 栈[长度(栈) - 1] != ".."`
**栈 = 去尾(栈)**
`else`
`if not 绝对`
**栈 = list.append(栈, 段)**
`else`
`if true`
**忽略绝对根 = 0**
`end`
`end`
`end`
`else`
`if true`
**栈 = list.append(栈, 段)**
`end`
`end`
`end`
**下标 = 下标 + 1**
`end`
`if 绝对`
`return "/" + 连接(栈)`
`end`
`return 连接(栈)`
+207
View File
@@ -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())
+7
View File
@@ -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
View File
@@ -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 的真实执行结果;任何期望值改动都必须作为公开行为变化单独评审并记录证据。
+98
View File
@@ -0,0 +1,98 @@
{
"schema": "marqdo.stdlib-test-case",
"schema_version": 1,
"name": "fs",
"file": "fs.mq.md",
"require_module": "fs/file.mq.md",
"args": [
"--allow-read",
"out",
"--allow-read",
"out/**",
"--allow-write",
"out",
"--allow-write",
"out/**"
],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"type": "bool",
"value": true
},
{
"decimal": "7",
"type": "int"
},
{
"type": "bool",
"value": true
},
{
"type": "text",
"value": "file"
},
{
"decimal": "7",
"type": "int"
},
{
"items": [
{
"type": "text",
"value": "fs-a.txt"
}
],
"type": "list"
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "text",
"value": "你好\n"
},
{
"decimal": "7",
"type": "int"
},
{
"type": "text",
"value": "你好\n世界\n"
},
{
"items": [
{
"type": "text",
"value": "fs-b.txt"
}
],
"type": "list"
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
}
],
"type": "list"
},
"clean": [
"out"
]
}
+52
View File
@@ -0,0 +1,52 @@
{
"schema": "marqdo.stdlib-test-case",
"schema_version": 1,
"name": "path",
"file": "path.mq.md",
"require_module": "path.mq.md",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"type": "text",
"value": "a/b/c"
},
{
"type": "text",
"value": "c.txt"
},
{
"type": "text",
"value": "a/b"
},
{
"type": "text",
"value": "txt"
},
{
"type": "text",
"value": "a/c"
},
{
"type": "text",
"value": "/a/c"
},
{
"type": "text",
"value": "../a/b"
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": false
}
],
"type": "list"
}
}
+38
View File
@@ -0,0 +1,38 @@
---
import:
fs_lib: "std:fs/file"
---
# @exec fs
## main
**创建 = fs_lib.创建目录("out")**
**写入 = fs_lib.写文本("out/fs-a.txt", "你好\n")**
**存在 = fs_lib.存在("out/fs-a.txt")**
**元数据 = fs_lib.元数据("out/fs-a.txt")**
**列表 = fs_lib.列出目录("out")**
**是文件 = fs_lib.是文件("out/fs-a.txt")**
**是目录 = fs_lib.是目录("out")**
**重命名 = fs_lib.重命名("out/fs-a.txt", "out/fs-b.txt")**
**读取 = fs_lib.读文本("out/fs-b.txt")**
**追加 = fs_lib.追加文本("out/fs-b.txt", "世界\n")**
**片段 = fs_lib.读取片段("out/fs-b.txt", 0, 100)**
**遍历 = fs_lib.遍历("out")**
**删除 = fs_lib.删除("out/fs-b.txt")**
**删除目录 = fs_lib.删除("out")**
`return [创建.ok, 写入.value.count, 存在.value, 元数据.value.kind, 元数据.value.size, 列表.value, 是文件.value, 是目录.value, 重命名.ok, 读取.value, 追加.value, 片段.value, 遍历.value, 删除.ok, 删除目录.ok]`
+10
View File
@@ -0,0 +1,10 @@
---
import:
path: "std:path"
---
# @exec path
## main
`return [path.连接(["a", "", "b", "c"]), path.文件名("a/b/c.txt"), path.目录名("a/b/c.txt"), path.扩展名("a/b/c.txt"), path.规范("./a//b/../c"), path.规范("/a/./b/../c"), path.规范("../a/b"), path.是否绝对("/a"), path.是否绝对("a")]`