feat(stdlib): Mid2 M9 fs make_dirs, walk, and stat

Thicken lib/fs with recursive mkdir/rmdir-tree, metadata maps, and
depth-first walk; add gold tests and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-09 09:27:06 +08:00
1 parent 435f36b6e9
commit 955834e453
16 files changed
+311 -9

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
## Unreleased
### Added
- **中层标准库 Mid2 M9**:`fs.make_dirs` / `remove_tree` / `stat` / `walk`(中英);金样与 public `16-fs-mid2`。设计 [stdlib-fs-mid2.md](doc/design/stdlib-fs-mid2.md)。
- **中层标准库 Mid2 M8**:`lib/toml` / `配置表`(只读子集)、`lib/html` / `超文本`(escape/unescape)、`encoding` base32;金样与 public `15-toml-html-encoding`。设计 [stdlib-toml.md](doc/design/stdlib-toml.md) · [stdlib-html.md](doc/design/stdlib-html.md)。
- **中层标准库 Mid2 M7**:`lib/datetime` / `日期时间`(`{unix,zone,iso}` · parse/format/add/in_zone)与 `lib/url` / `地址`(parse · query_parse/stringify);金样与 public `14-datetime-url`。设计 [stdlib-datetime.md](doc/design/stdlib-datetime.md) · [stdlib-url.md](doc/design/stdlib-url.md)。
- **文档**:中层标准库 Mid 之后缺口盘点与 Mid2(M7–M10)设计/路线——[stdlib-gaps-after-mid.md](doc/research/stdlib-gaps-after-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md) · [stdlib-mid2.md](doc/roadmap/stdlib-mid2.md)。
+1
View File
@@ -38,6 +38,7 @@
| [design/stdlib-url.md](design/stdlib-url.md) | **`lib/url`(Mid2 M7)** |
| [design/stdlib-toml.md](design/stdlib-toml.md) | **`lib/toml`(Mid2 M8)** |
| [design/stdlib-html.md](design/stdlib-html.md) | **`lib/html`(Mid2 M8)** |
| [design/stdlib-fs-mid2.md](design/stdlib-fs-mid2.md) | **`lib/fs` Mid2 M9 加厚** |
| [research/stdlib-gaps-after-mid.md](research/stdlib-gaps-after-mid.md) | **Mid 之后缺口盘点**(对照 Python/Go) |
| [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** |
| [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** |
+25
View File
@@ -0,0 +1,25 @@
# 设计:`lib/fs` Mid2 加厚(M9)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §4 · [stdlib-fs-mid.md](stdlib-fs-mid.md)(M2) |
| 宿主 | `src/host/fs.rs` · `host_make_dirs` / `host_remove_tree` / `host_stat` / `host_walk` |
---
## API
| EN | ZH | 行为 |
|----|-----|------|
| `make_dirs` | `建目录树` | 递归创建(与既有 `make_dir` 同为 `create_dir_all`;显式命名) |
| `remove_tree` | `删目录树` | 仅删目录树;路径为文件则报错 |
| `stat` | `状态` | `{size, mtime_unix, is_file, is_dir}` |
| `walk` | `遍历` | **深度优先**;相对路径列表(正斜杠);含目录项;同级按名排序 |
既有 `remove` 对目录仍递归删除;`remove_tree` 拒绝文件,语义更窄。
## 刻意不做
ACL、watch、硬链接、`copy_tree`、惰性迭代器协议。
+1 -1
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Draft · M7–M8 已落地;M9–M10 锁定方向** |
| 状态 | **Draft · M7–M9 已落地;M10 可选** |
| 日期 | 2026-09-09 |
| 缺口盘点 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
| 路线图 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) |
+2 -2
View File
@@ -31,7 +31,7 @@
| **配置表** | `lib/toml.mq.md` | `lib/配置表.mq.md` | **Mid2 M8** |
| **超文本** | `lib/html.mq.md` | `lib/超文本.mq.md` | **Mid2 M8** |
| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) |
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2:`copy_file` / `move` / `make_temp` |
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2 + **Mid2 M9**:`make_dirs` / `remove_tree` / `stat` / `walk` |
| 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) |
| 时间 | `lib/time.mq.md` | `lib/时间.mq.md` | 已有 |
| JSON | `lib/json.mq.md` | **同文件** | **仅** parse / stringify / quote;集合请用 table / GFM |
@@ -46,7 +46,7 @@
**中层已落地:** M1–M6(含 log / uuid)— 见 [stdlib-mid.md](stdlib-mid.md) · [stdlib-log-uuid.md](stdlib-log-uuid.md)。
**Mid2:** **M7–M8 done**(`datetime` · `url` · `toml` · `html` · base32)— [stdlib-datetime.md](stdlib-datetime.md) · [stdlib-url.md](stdlib-url.md) · [stdlib-toml.md](stdlib-toml.md) · [stdlib-html.md](stdlib-html.md);M9+ 见 [stdlib-mid2.md](stdlib-mid2.md)。
**Mid2:** **M7–M9 done**(datetime / url / toml / html / base32 / fs++)— [stdlib-datetime.md](stdlib-datetime.md) · [stdlib-url.md](stdlib-url.md) · [stdlib-toml.md](stdlib-toml.md) · [stdlib-html.md](stdlib-html.md) · [stdlib-fs-mid2.md](stdlib-fs-mid2.md);M10 见 [stdlib-mid2.md](stdlib-mid2.md)。
设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。
+1 -1
View File
@@ -128,7 +128,7 @@ catalog / 工具配置若走向 TOML,只读 `toml.parse` 性价比高。YAML
|--------|----------|------|
| **高** | **M7** | `datetime` + `url` — **done** |
| **高** | **M8** | `toml` 只读 + `html.escape` + `encoding` base32 — **done** |
| **中** | **M9** | `fs` 加厚(dirs/stat/walk) |
| **中** | **M9** | `fs` 加厚(dirs/stat/walk) — **done** |
| **低** | **M10** | `stats` 薄 · 可选 zip · 结构化 log 字段 |
| **won't** | — | 完整 YAML · 模板引擎 · sqlite 进 `lib/` |
+6 -5
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Active · M7–M8 已落地 · M9–M10 规划** |
| 状态 | **Active · M7–M9 已落地 · M10 可选** |
| 日期 | 2026-09-09 |
| 设计 | [stdlib-mid2.md](../design/stdlib-mid2.md) |
| 缺口 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
@@ -54,12 +54,13 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过)
| public | `15-toml-html-encoding` · `15-配置表超文本编码` |
| 设计 | [stdlib-toml.md](../design/stdlib-toml.md) · [stdlib-html.md](../design/stdlib-html.md) |
### M9 — fs 加厚 — **todo**
### M9 — fs 加厚 — **done**
| 交付 | 说明 |
|------|------|
| `make_dirs` / `remove_tree` / `stat` / `walk` | 见设计文 |
| 金样 | `fs-mid2-smoke` |
| `make_dirs` / `remove_tree` / `stat` / `walk` | 见 [stdlib-fs-mid2.md](../design/stdlib-fs-mid2.md) |
| 金样 | `fs-mid2-smoke`(中英) |
| public | `16-fs-mid2` · `16-文件mid2` |
### M10 — 可选收口 — **todo**
@@ -75,7 +76,7 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过)
- [x] M7 datetime + url
- [x] M8 toml + html + base32
- [ ] M9 fs 加厚
- [x] M9 fs 加厚
- [ ] M10 可选
- [ ] 研究文高优先级缺口 → closed
- [ ] `stdlib-modules.md` / `stdlib.md` 状态同步
+28
View File
@@ -35,11 +35,39 @@ description: English filesystem wrappers
**> host_make_dir path=`path`**
## make_dirs
+ `path`
Create directories recursively (`mkdir -p`).
**> host_make_dirs path=`path`**
## remove
+ `path`
**> host_remove path=`path`**
## remove_tree
+ `path`
Remove a directory recursively. Errors if `path` is a file.
**> host_remove_tree path=`path`**
## stat
+ `path`
Returns `{size, mtime_unix, is_file, is_dir}`.
**> host_stat path=`path`**
## walk
+ `path`
Depth-first listing of relative paths under `path` (forward slashes).
**> host_walk path=`path`**
## copy_file
+ `src`
+ `dest`
+28
View File
@@ -35,11 +35,39 @@ description: 中文文件系统包装
**> host_make_dir path=`路径`**
## 建目录树
+ `路径`
递归创建目录(等同 `mkdir -p`)。
**> host_make_dirs path=`路径`**
## 删除
+ `路径`
**> host_remove path=`路径`**
## 删目录树
+ `路径`
递归删除目录;若路径是文件则报错。
**> host_remove_tree path=`路径`**
## 状态
+ `路径`
返回 `{size, mtime_unix, is_file, is_dir}`。
**> host_stat path=`路径`**
## 遍历
+ `路径`
深度优先列出相对路径(正斜杠)。
**> host_walk path=`路径`**
## 复制文件
+ `源`
+ `目标`
+24
View File
@@ -0,0 +1,24 @@
---
title: Mid stdlib — fs make_dirs, walk, stat
description: Recursive dirs, walk, and file metadata (Mid2 M9)
import fs:lib/fs.mq.md
---
# Practical filesystem without plugins
`make_dirs` / `remove_tree` / `stat` / `walk` thicken `lib/fs` for scripts and tools.
# main
> fs.make_dirs path="m9-demo/sub"
> fs.write_text path="m9-demo/readme.txt" text="ok"
*st = > fs.stat path="m9-demo/readme.txt"*
> print text=`st`[^size]
*w = > fs.walk path="m9-demo"*
*n = > len `w`*
> print text=`n`
> fs.remove_tree path="m9-demo"
+22
View File
@@ -0,0 +1,22 @@
---
title: 中层标准库 — 文件目录树与状态
description: 递归目录、遍历与元数据(Mid2 M9)
导入 文件:lib/文件.mq.md
---
# 无需插件的实用文件系统
# main
> 文件.建目录树 路径="m9-演示/子"
> 文件.写文本 路径="m9-演示/说明.txt" 内容="好"
*st = > 文件.状态 路径="m9-演示/说明.txt"*
> print text=`st`[^size]
*w = > 文件.遍历 路径="m9-演示"*
*n = > 长度 `w`*
> print text=`n`
> 文件.删目录树 路径="m9-演示"
+21
View File
@@ -191,6 +191,10 @@ pub enum HostFn {
HtmlUnescape = 182,
EncodingBase32Encode = 183,
EncodingBase32Decode = 184,
FsMakeDirs = 185,
FsRemoveTree = 186,
FsStat = 187,
FsWalk = 188,
}
@@ -372,6 +376,10 @@ impl HostFn {
182 => Self::HtmlUnescape,
183 => Self::EncodingBase32Encode,
184 => Self::EncodingBase32Decode,
185 => Self::FsMakeDirs,
186 => Self::FsRemoveTree,
187 => Self::FsStat,
188 => Self::FsWalk,
_ => return None,
})
}
@@ -556,6 +564,10 @@ impl HostFn {
"host_html_unescape" | "html_unescape" => Self::HtmlUnescape,
"host_encoding_base32_encode" | "encoding_base32_encode" => Self::EncodingBase32Encode,
"host_encoding_base32_decode" | "encoding_base32_decode" => Self::EncodingBase32Decode,
"host_make_dirs" | "make_dirs" => Self::FsMakeDirs,
"host_remove_tree" | "remove_tree" => Self::FsRemoveTree,
"host_stat" | "stat" => Self::FsStat,
"host_walk" | "walk" => Self::FsWalk,
_ => return None,
})
}
@@ -727,6 +739,10 @@ impl HostFn {
Self::HtmlUnescape => "host_html_unescape",
Self::EncodingBase32Encode => "host_encoding_base32_encode",
Self::EncodingBase32Decode => "host_encoding_base32_decode",
Self::FsMakeDirs => "host_make_dirs",
Self::FsRemoveTree => "host_remove_tree",
Self::FsStat => "host_stat",
Self::FsWalk => "host_walk",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -861,6 +877,7 @@ impl HostFn {
Self::UrlParse | Self::UrlQueryParse => &["text"],
Self::UrlQueryStringify => &["map"],
Self::TomlParse | Self::HtmlEscape | Self::HtmlUnescape => &["text"],
Self::FsMakeDirs | Self::FsRemoveTree | Self::FsStat | Self::FsWalk => &["path"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -931,6 +948,10 @@ pub fn call_host(
HostFn::ListDir => fs::list_dir(ctx, require(bound, "path")?),
HostFn::MakeDir => fs::make_dir(ctx, require(bound, "path")?),
HostFn::Remove => fs::remove(ctx, require(bound, "path")?),
HostFn::FsMakeDirs => fs::make_dirs(ctx, require(bound, "path")?),
HostFn::FsRemoveTree => fs::remove_tree(ctx, require(bound, "path")?),
HostFn::FsStat => fs::stat(ctx, require(bound, "path")?),
HostFn::FsWalk => fs::walk(ctx, require(bound, "path")?),
HostFn::NowUnix => time::now_unix(),
HostFn::NowMs => time::now_ms(),
HostFn::FormatTime => {
+84
View File
@@ -94,6 +94,16 @@ pub fn make_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
Ok(Value::None)
}
/// Explicit recursive mkdir (same host behavior as `make_dir`).
pub fn make_dirs(ctx: &HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("make_dirs denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
fs::create_dir_all(&p).map_err(|e| format!("make_dirs {}: {e}", p.display()))?;
Ok(Value::None)
}
pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("remove denied by host policy".into());
@@ -107,6 +117,80 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
Ok(Value::None)
}
/// Remove a directory tree. Errors if `path` is a file.
pub fn remove_tree(ctx: &HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("remove_tree denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
if !p.exists() {
return Err(format!("remove_tree: not found: {}", p.display()));
}
if !p.is_dir() {
return Err(format!("remove_tree: not a directory: {}", p.display()));
}
fs::remove_dir_all(&p).map_err(|e| format!("remove_tree {}: {e}", p.display()))?;
Ok(Value::None)
}
/// `{size, mtime_unix, is_file, is_dir}` for a path.
pub fn stat(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
let meta = fs::metadata(&p).map_err(|e| format!("stat {}: {e}", p.display()))?;
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
Ok(Value::Map(vec![
("size".into(), Value::Int(meta.len() as i64)),
("mtime_unix".into(), Value::Int(mtime)),
("is_file".into(), Value::Bool(meta.is_file())),
("is_dir".into(), Value::Bool(meta.is_dir())),
]))
}
/// Depth-first walk; returns path texts relative to `path` (forward slashes), sorted per directory.
pub fn walk(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let root = ctx.resolve_path(text_path(path)?)?;
if !root.is_dir() {
return Err(format!("walk: not a directory: {}", root.display()));
}
let mut out: Vec<Value> = Vec::new();
walk_dfs(&root, Path::new(""), &mut out)?;
Ok(Value::List(out))
}
fn walk_dfs(abs: &Path, rel: &Path, out: &mut Vec<Value>) -> Result<(), String> {
let mut entries: Vec<_> = fs::read_dir(abs)
.map_err(|e| format!("walk {}: {e}", abs.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("walk: {e}"))?;
entries.sort_by_key(|e| e.file_name());
for ent in entries {
let name = ent.file_name();
let child_rel = if rel.as_os_str().is_empty() {
Path::new(&name).to_path_buf()
} else {
rel.join(&name)
};
let rel_text = child_rel
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
out.push(Value::Text(rel_text));
let ft = ent
.file_type()
.map_err(|e| format!("walk file_type: {e}"))?;
if ft.is_dir() {
walk_dfs(&ent.path(), &child_rel, out)?;
}
}
Ok(())
}
pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("copy_file denied by host policy".into());
+13
View File
@@ -1229,6 +1229,19 @@ fn lib_toml_html_encoding_smoke_zh() {
);
}
#[test]
fn lib_fs_mid2_smoke() {
assert_out(
"tests/lib/fs-mid2-smoke.mq.md",
"1\nTrue\nFalse\n3\na.txt\nnested\nnested/b.txt\nFalse",
);
}
#[test]
fn lib_fs_mid2_smoke_zh() {
assert_out("tests/lib/文件-mid2-烟测.mq.md", "True\n2\nFalse");
}
#[test]
fn lib_re_smoke() {
assert_out(
+32
View File
@@ -0,0 +1,32 @@
---
title: fs mid2 M9 smoke
import fs:lib/fs.mq.md
---
# main
> fs.make_dirs path="m9-tree/nested"
> fs.write_text path="m9-tree/a.txt" text="A"
> fs.write_text path="m9-tree/nested/b.txt" text="B"
*st = > fs.stat path="m9-tree/a.txt"*
> print text=`st`[^size]
> print text=`st`[^is_file]
> print text=`st`[^is_dir]
*w = > fs.walk path="m9-tree"*
*n = > len `w`*
> print text=`n`
*p0 = > at value=`w` index=0*
*p1 = > at value=`w` index=1*
*p2 = > at value=`w` index=2*
> print text=`p0`
> print text=`p1`
> print text=`p2`
> fs.remove_tree path="m9-tree"
*gone = > fs.exists path="m9-tree"*
> print text=`gone`
+22
View File
@@ -0,0 +1,22 @@
---
title: 文件 Mid2 M9 烟测
导入 文件:lib/文件.mq.md
---
# main
> 文件.建目录树 路径="m9-zh/子"
> 文件.写文本 路径="m9-zh/a.txt" 内容="A"
*st = > 文件.状态 路径="m9-zh/a.txt"*
> print text=`st`[^is_file]
*w = > 文件.遍历 路径="m9-zh"*
*n = > 长度 `w`*
> print text=`n`
> 文件.删目录树 路径="m9-zh"
*gone = > 文件.存在 路径="m9-zh"*
> print text=`gone`