feat(stdlib): Mid M2 path algebra and fs copy/move/temp

Add lib/path (EN/ZH) and thicken fs with sandboxed copy_file, move,
and make_temp, with golds and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-07 20:10:12 +08:00
1 parent 838a2b425a
commit 94ae6713aa
22 files changed
+618 -25

No files matched your search

+63 -1
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use crate::host::{encoding, fs, json, math, net, re, sys, time, writeback, HostContext};
use crate::host::{encoding, fs, json, math, net, path, re, sys, time, writeback, HostContext};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
@@ -137,6 +137,16 @@ pub enum HostFn {
EncodingBase64Decode = 131,
EncodingHexEncode = 132,
EncodingHexDecode = 133,
PathJoin = 134,
PathSplit = 135,
PathFileName = 136,
PathParent = 137,
PathExtension = 138,
PathNormalize = 139,
PathIsAbsolute = 140,
FsCopyFile = 141,
FsMove = 142,
FsMakeTemp = 143,
}
@@ -267,6 +277,16 @@ impl HostFn {
131 => Self::EncodingBase64Decode,
132 => Self::EncodingHexEncode,
133 => Self::EncodingHexDecode,
134 => Self::PathJoin,
135 => Self::PathSplit,
136 => Self::PathFileName,
137 => Self::PathParent,
138 => Self::PathExtension,
139 => Self::PathNormalize,
140 => Self::PathIsAbsolute,
141 => Self::FsCopyFile,
142 => Self::FsMove,
143 => Self::FsMakeTemp,
_ => return None,
})
}
@@ -400,6 +420,16 @@ impl HostFn {
"host_encoding_base64_decode" | "encoding_base64_decode" => Self::EncodingBase64Decode,
"host_encoding_hex_encode" | "encoding_hex_encode" => Self::EncodingHexEncode,
"host_encoding_hex_decode" | "encoding_hex_decode" => Self::EncodingHexDecode,
"host_path_join" | "path_join" => Self::PathJoin,
"host_path_split" | "path_split" => Self::PathSplit,
"host_path_file_name" | "path_file_name" => Self::PathFileName,
"host_path_parent" | "path_parent" => Self::PathParent,
"host_path_extension" | "path_extension" => Self::PathExtension,
"host_path_normalize" | "path_normalize" => Self::PathNormalize,
"host_path_is_absolute" | "path_is_absolute" => Self::PathIsAbsolute,
"host_copy_file" | "copy_file" => Self::FsCopyFile,
"host_move" | "move_path" => Self::FsMove,
"host_make_temp" | "make_temp" => Self::FsMakeTemp,
_ => return None,
})
}
@@ -520,6 +550,16 @@ impl HostFn {
Self::EncodingBase64Decode => "host_encoding_base64_decode",
Self::EncodingHexEncode => "host_encoding_hex_encode",
Self::EncodingHexDecode => "host_encoding_hex_decode",
Self::PathJoin => "host_path_join",
Self::PathSplit => "host_path_split",
Self::PathFileName => "host_path_file_name",
Self::PathParent => "host_path_parent",
Self::PathExtension => "host_path_extension",
Self::PathNormalize => "host_path_normalize",
Self::PathIsAbsolute => "host_path_is_absolute",
Self::FsCopyFile => "host_copy_file",
Self::FsMove => "host_move",
Self::FsMakeTemp => "host_make_temp",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -613,6 +653,15 @@ impl HostFn {
| Self::EncodingBase64Decode
| Self::EncodingHexEncode
| Self::EncodingHexDecode => &["text"],
Self::PathJoin => &["a", "b"],
Self::PathSplit
| Self::PathFileName
| Self::PathParent
| Self::PathExtension
| Self::PathNormalize
| Self::PathIsAbsolute => &["path"],
Self::FsCopyFile | Self::FsMove => &["src", "dest"],
Self::FsMakeTemp => &[],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -646,6 +695,7 @@ impl HostFn {
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
Self::ListSlice => &["end"],
Self::ReReplace => &["count"],
Self::FsMakeTemp => &["prefix"],
_ => &[],
}
}
@@ -1029,6 +1079,18 @@ pub fn call_host(
HostFn::EncodingBase64Decode => encoding::base64_decode(require(bound, "text")?),
HostFn::EncodingHexEncode => encoding::hex_encode(require(bound, "text")?),
HostFn::EncodingHexDecode => encoding::hex_decode(require(bound, "text")?),
HostFn::PathJoin => path::join(require(bound, "a")?, require(bound, "b")?),
HostFn::PathSplit => path::split(require(bound, "path")?),
HostFn::PathFileName => path::file_name(require(bound, "path")?),
HostFn::PathParent => path::parent(require(bound, "path")?),
HostFn::PathExtension => path::extension(require(bound, "path")?),
HostFn::PathNormalize => path::normalize(require(bound, "path")?),
HostFn::PathIsAbsolute => path::is_absolute(require(bound, "path")?),
HostFn::FsCopyFile => {
fs::copy_file(ctx, require(bound, "src")?, require(bound, "dest")?)
}
HostFn::FsMove => fs::move_path(ctx, require(bound, "src")?, require(bound, "dest")?),
HostFn::FsMakeTemp => fs::make_temp(ctx, bound.get("prefix")),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
+55
View File
@@ -107,6 +107,61 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
Ok(Value::None)
}
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());
}
let from = ctx.resolve_path(text_path(src)?)?;
let to = ctx.resolve_path(text_path(dest)?)?;
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?;
}
fs::copy(&from, &to).map_err(|e| format!("copy_file {} -> {}: {e}", from.display(), to.display()))?;
Ok(Value::None)
}
pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("move denied by host policy".into());
}
let from = ctx.resolve_path(text_path(src)?)?;
let to = ctx.resolve_path(text_path(dest)?)?;
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).map_err(|e| format!("move mkdir: {e}"))?;
}
fs::rename(&from, &to).map_err(|e| format!("move {} -> {}: {e}", from.display(), to.display()))?;
Ok(Value::None)
}
/// Create an empty temp file under the program cwd / fs_root; return relative path text.
pub fn make_temp(ctx: &HostContext, prefix: Option<&Value>) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("make_temp denied by host policy".into());
}
let pref = match prefix {
None | Some(Value::None) => "mqtmp".to_string(),
Some(v) => text_path(v)?.to_string(),
};
if pref.contains('/') || pref.contains('\\') || pref.contains("..") {
return Err("make_temp: prefix must be a simple name".into());
}
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let name = format!("{pref}-{stamp}");
let p = ctx.resolve_path(&name)?;
if let Some(parent) = p.parent() {
fs::create_dir_all(parent).map_err(|e| format!("make_temp mkdir: {e}"))?;
}
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&p)
.map_err(|e| format!("make_temp {}: {e}", p.display()))?;
Ok(Value::Text(name))
}
/// Exact UTF-8 FIND→REPLACE on a file. `find` must occur exactly once.
pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
+1
View File
@@ -15,6 +15,7 @@ mod fs;
pub(crate) mod json;
pub mod math;
mod net;
mod path;
mod re;
#[cfg(feature = "plugin-host")]
pub mod plugin;
+122
View File
@@ -0,0 +1,122 @@
//! Path algebra for Mid M2 (`lib/path`) — no I/O.
use std::path::{Component, Path, PathBuf};
use crate::value::Value;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} needs text")),
}
}
fn path_to_text(p: &Path) -> String {
if p.as_os_str().is_empty() {
".".into()
} else {
p.to_string_lossy().into_owned()
}
}
pub fn join(a: &Value, b: &Value) -> Result<Value, String> {
let a = as_text(a, "a")?;
let b = as_text(b, "b")?;
let out = Path::new(a).join(b);
Ok(Value::Text(path_to_text(&out)))
}
pub fn split(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
let mut parts = Vec::new();
for c in Path::new(p).components() {
match c {
Component::RootDir | Component::CurDir | Component::ParentDir => {
parts.push(Value::Text(c.as_os_str().to_string_lossy().into_owned()));
}
Component::Prefix(prefix) => {
parts.push(Value::Text(prefix.as_os_str().to_string_lossy().into_owned()));
}
Component::Normal(s) => parts.push(Value::Text(s.to_string_lossy().into_owned())),
}
}
Ok(Value::List(parts))
}
pub fn file_name(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
Ok(Value::Text(
Path::new(p)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
))
}
pub fn parent(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
let parent = Path::new(p).parent();
Ok(Value::Text(match parent {
Some(par) if !par.as_os_str().is_empty() => path_to_text(par),
_ => ".".into(),
}))
}
pub fn extension(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
Ok(Value::Text(
Path::new(p)
.extension()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
))
}
pub fn normalize(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
let mut out = PathBuf::new();
for c in Path::new(p).components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
match out.components().next_back() {
Some(Component::Normal(_)) => {
out.pop();
}
Some(Component::RootDir) | Some(Component::Prefix(_)) => {}
_ => out.push(".."),
}
}
other => out.push(other.as_os_str()),
}
}
Ok(Value::Text(path_to_text(&out)))
}
pub fn is_absolute(path: &Value) -> Result<Value, String> {
let p = as_text(path, "path")?;
Ok(Value::Bool(Path::new(p).is_absolute()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn join_and_name() {
let j = join(
&Value::Text("a/b".into()),
&Value::Text("c.txt".into()),
)
.unwrap();
assert_eq!(j, Value::Text("a/b/c.txt".into()));
assert_eq!(
file_name(&Value::Text("a/b/c.txt".into())).unwrap(),
Value::Text("c.txt".into())
);
assert_eq!(
extension(&Value::Text("c.txt".into())).unwrap(),
Value::Text("txt".into())
);
}
}