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

+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());