Add host stdlib modules and unify view/run capabilities.

Ship fs/time/sys/json/net L1 libs (plus existing text/table), default-on host caps with soft exit under view, bilingual public/stdlib docs, and design notes for deferred math/foreign.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-05 10:03:54 +08:00
1 parent a5d30c00b3
commit a53ebb65ee
66 files changed
+2703 -45

No files matched your search

+227
View File
@@ -0,0 +1,227 @@
//! Host function registry and dispatch.
use std::collections::HashMap;
use crate::host::{fs, json, net, sys, time, HostContext};
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum HostFn {
ReadText = 1,
WriteText = 2,
AppendText = 3,
Exists = 4,
ListDir = 5,
MakeDir = 6,
Remove = 7,
NowUnix = 8,
NowMs = 9,
FormatTime = 10,
SleepMs = 11,
ParseTime = 12,
EnvGet = 13,
EnvSet = 14,
Args = 15,
Cwd = 16,
Exit = 17,
Exec = 18,
JsonParse = 19,
JsonStringify = 20,
JsonGet = 21,
JsonKeys = 22,
HttpGet = 23,
HttpPost = 24,
UrlEncode = 25,
}
impl HostFn {
pub fn from_u16(id: u16) -> Option<Self> {
Some(match id {
1 => Self::ReadText,
2 => Self::WriteText,
3 => Self::AppendText,
4 => Self::Exists,
5 => Self::ListDir,
6 => Self::MakeDir,
7 => Self::Remove,
8 => Self::NowUnix,
9 => Self::NowMs,
10 => Self::FormatTime,
11 => Self::SleepMs,
12 => Self::ParseTime,
13 => Self::EnvGet,
14 => Self::EnvSet,
15 => Self::Args,
16 => Self::Cwd,
17 => Self::Exit,
18 => Self::Exec,
19 => Self::JsonParse,
20 => Self::JsonStringify,
21 => Self::JsonGet,
22 => Self::JsonKeys,
23 => Self::HttpGet,
24 => Self::HttpPost,
25 => Self::UrlEncode,
_ => return None,
})
}
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"host_read_text" => Self::ReadText,
"host_write_text" => Self::WriteText,
"host_append_text" => Self::AppendText,
"host_exists" => Self::Exists,
"host_list_dir" => Self::ListDir,
"host_make_dir" => Self::MakeDir,
"host_remove" => Self::Remove,
"host_now_unix" => Self::NowUnix,
"host_now_ms" => Self::NowMs,
"host_format_time" => Self::FormatTime,
"host_sleep_ms" => Self::SleepMs,
"host_parse_time" => Self::ParseTime,
"host_env_get" => Self::EnvGet,
"host_env_set" => Self::EnvSet,
"host_args" => Self::Args,
"host_cwd" => Self::Cwd,
"host_exit" => Self::Exit,
"host_exec" => Self::Exec,
"host_json_parse" => Self::JsonParse,
"host_json_stringify" => Self::JsonStringify,
"host_json_get" => Self::JsonGet,
"host_json_keys" => Self::JsonKeys,
"host_http_get" => Self::HttpGet,
"host_http_post" => Self::HttpPost,
"host_url_encode" => Self::UrlEncode,
_ => return None,
})
}
pub fn as_u16(self) -> u16 {
self as u16
}
pub fn name(self) -> &'static str {
match self {
Self::ReadText => "host_read_text",
Self::WriteText => "host_write_text",
Self::AppendText => "host_append_text",
Self::Exists => "host_exists",
Self::ListDir => "host_list_dir",
Self::MakeDir => "host_make_dir",
Self::Remove => "host_remove",
Self::NowUnix => "host_now_unix",
Self::NowMs => "host_now_ms",
Self::FormatTime => "host_format_time",
Self::SleepMs => "host_sleep_ms",
Self::ParseTime => "host_parse_time",
Self::EnvGet => "host_env_get",
Self::EnvSet => "host_env_set",
Self::Args => "host_args",
Self::Cwd => "host_cwd",
Self::Exit => "host_exit",
Self::Exec => "host_exec",
Self::JsonParse => "host_json_parse",
Self::JsonStringify => "host_json_stringify",
Self::JsonGet => "host_json_get",
Self::JsonKeys => "host_json_keys",
Self::HttpGet => "host_http_get",
Self::HttpPost => "host_http_post",
Self::UrlEncode => "host_url_encode",
}
}
/// Required params first; see `optional_params` for trailing optionals.
pub fn required_params(self) -> &'static [&'static str] {
match self {
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
&["path"]
}
Self::WriteText | Self::AppendText => &["path", "text"],
Self::NowUnix | Self::NowMs | Self::Args | Self::Cwd => &[],
Self::FormatTime => &["unix", "pattern"],
Self::ParseTime => &["text", "pattern"],
Self::SleepMs => &["ms"],
Self::EnvGet => &["name"],
Self::EnvSet => &["name", "value"],
Self::Exit => &["code"],
Self::Exec => &["cmd"],
Self::JsonParse | Self::UrlEncode => &["text"],
Self::JsonStringify | Self::JsonKeys => &["value"],
Self::JsonGet => &["value", "key"],
Self::HttpGet => &["url"],
Self::HttpPost => &["url", "body"],
}
}
pub fn optional_params(self) -> &'static [&'static str] {
match self {
Self::JsonStringify => &["indent"],
Self::HttpPost => &["content_type"],
Self::Exec => &["args"],
_ => &[],
}
}
pub fn all_params(self) -> Vec<&'static str> {
let mut v = self.required_params().to_vec();
v.extend_from_slice(self.optional_params());
v
}
}
pub fn call_host(
ctx: &HostContext,
fn_id: HostFn,
bound: &HashMap<String, Value>,
) -> Result<Value, String> {
match fn_id {
HostFn::ReadText => fs::read_text(ctx, require(bound, "path")?),
HostFn::WriteText => {
fs::write_text(ctx, require(bound, "path")?, require(bound, "text")?)
}
HostFn::AppendText => {
fs::append_text(ctx, require(bound, "path")?, require(bound, "text")?)
}
HostFn::Exists => fs::exists(ctx, require(bound, "path")?),
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::NowUnix => time::now_unix(),
HostFn::NowMs => time::now_ms(),
HostFn::FormatTime => {
time::format_time(require(bound, "unix")?, require(bound, "pattern")?)
}
HostFn::SleepMs => time::sleep_ms(ctx, require(bound, "ms")?),
HostFn::ParseTime => {
time::parse_time(require(bound, "text")?, require(bound, "pattern")?)
}
HostFn::EnvGet => sys::env_get(require(bound, "name")?),
HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?),
HostFn::Args => sys::args(ctx),
HostFn::Cwd => sys::cwd(ctx),
HostFn::Exit => sys::exit(ctx, require(bound, "code")?),
HostFn::Exec => sys::exec(ctx, require(bound, "cmd")?, bound.get("args")),
HostFn::JsonParse => json::parse(require(bound, "text")?),
HostFn::JsonStringify => {
json::stringify(require(bound, "value")?, bound.get("indent"))
}
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?),
HostFn::HttpPost => net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
),
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
}
}
fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value, String> {
bound
.get(key)
.ok_or_else(|| format!("host call missing `{key}`"))
}
+108
View File
@@ -0,0 +1,108 @@
//! Filesystem host primitives.
use std::fs;
use std::path::Path;
use crate::host::HostContext;
use crate::value::Value;
pub fn path_under_root(path: &Path, root: &Path) -> bool {
let mut cur = path.to_path_buf();
loop {
if cur == *root {
return true;
}
if !cur.pop() {
return false;
}
}
}
fn text_path(v: &Value) -> Result<&str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err("path must be text".into()),
}
}
fn text_body(v: &Value) -> Result<&str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err("text must be text".into()),
}
}
pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?;
Ok(Value::Text(s))
}
pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("write_text denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
if let Some(parent) = p.parent() {
fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?;
}
fs::write(&p, text_body(text)?).map_err(|e| format!("write_text {}: {e}", p.display()))?;
Ok(Value::None)
}
pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("append_text denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
use std::io::Write;
let mut f = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&p)
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
f.write_all(text_body(text)?.as_bytes())
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
Ok(Value::None)
}
pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
Ok(Value::Bool(p.exists()))
}
pub fn list_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
let mut names = Vec::new();
let rd = fs::read_dir(&p).map_err(|e| format!("list_dir {}: {e}", p.display()))?;
for ent in rd {
let ent = ent.map_err(|e| format!("list_dir: {e}"))?;
names.push(Value::Text(
ent.file_name().to_string_lossy().into_owned(),
));
}
names.sort_by(|a, b| a.as_display().cmp(&b.as_display()));
Ok(Value::List(names))
}
pub fn make_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("make_dir denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
fs::create_dir_all(&p).map_err(|e| format!("make_dir {}: {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());
}
let p = ctx.resolve_path(text_path(path)?)?;
if p.is_dir() {
fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
} else {
fs::remove_file(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
}
Ok(Value::None)
}
+106
View File
@@ -0,0 +1,106 @@
//! JSON host primitives + Value↔JSON mapping.
use crate::value::Value;
pub fn parse(text: &Value) -> Result<Value, String> {
let s = match text {
Value::Text(s) => s.as_str(),
_ => return Err("json parse needs text".into()),
};
let v: serde_json::Value =
serde_json::from_str(s).map_err(|e| format!("json parse: {e}"))?;
json_to_value(&v)
}
pub fn stringify(value: &Value, indent: Option<&Value>) -> Result<Value, String> {
let j = value_to_json(value)?;
let pretty = match indent {
None => false,
Some(Value::Int(n)) => *n > 0,
Some(Value::Bool(b)) => *b,
Some(Value::None) => false,
Some(_) => return Err("json stringify indent must be int or bool".into()),
};
let s = if pretty {
serde_json::to_string_pretty(&j).map_err(|e| format!("json stringify: {e}"))?
} else {
serde_json::to_string(&j).map_err(|e| format!("json stringify: {e}"))?
};
Ok(Value::Text(s))
}
pub fn get(value: &Value, key: &Value) -> Result<Value, String> {
let k = match key {
Value::Text(s) => s.as_str(),
_ => return Err("json get key must be text".into()),
};
match value {
Value::Map(entries) => Ok(entries
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
.unwrap_or(Value::None)),
_ => Err("json get needs map".into()),
}
}
pub fn keys(value: &Value) -> Result<Value, String> {
match value {
Value::Map(entries) => Ok(Value::List(
entries.iter().map(|(k, _)| Value::Text(k.clone())).collect(),
)),
_ => Err("json keys needs map".into()),
}
}
fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
Ok(match v {
serde_json::Value::Null => Value::None,
serde_json::Value::Bool(b) => Value::Bool(*b),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Value::Int(i)
} else {
Value::Text(n.to_string())
}
}
serde_json::Value::String(s) => Value::Text(s.clone()),
serde_json::Value::Array(xs) => {
let mut out = Vec::with_capacity(xs.len());
for x in xs {
out.push(json_to_value(x)?);
}
Value::List(out)
}
serde_json::Value::Object(map) => {
let mut entries = Vec::with_capacity(map.len());
for (k, v) in map {
entries.push((k.clone(), json_to_value(v)?));
}
Value::Map(entries)
}
})
}
fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
Ok(match v {
Value::None => serde_json::Value::Null,
Value::Bool(b) => serde_json::Value::Bool(*b),
Value::Int(n) => serde_json::Value::Number((*n).into()),
Value::Text(s) => serde_json::Value::String(s.clone()),
Value::List(xs) => {
let mut arr = Vec::with_capacity(xs.len());
for x in xs {
arr.push(value_to_json(x)?);
}
serde_json::Value::Array(arr)
}
Value::Map(entries) => {
let mut map = serde_json::Map::new();
for (k, v) in entries {
map.insert(k.clone(), value_to_json(v)?);
}
serde_json::Value::Object(map)
}
})
}
+126
View File
@@ -0,0 +1,126 @@
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, …).
//!
//! User docs should import L1 wrappers; these `host_*` names are the Rust surface.
//! Capabilities default **on** (importing a lib means you intend to use it).
//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only.
mod dispatch;
mod fs;
mod json;
mod net;
mod sys;
mod time;
pub use dispatch::{call_host, HostFn};
pub use fs::path_under_root;
use std::path::{Path, PathBuf};
/// Host capability flags. Default: all enabled.
#[derive(Debug, Clone)]
pub struct HostCaps {
pub fs_write: bool,
pub exec: bool,
pub net: bool,
}
impl Default for HostCaps {
fn default() -> Self {
Self {
fs_write: true,
exec: true,
net: true,
}
}
}
#[derive(Debug, Clone)]
pub struct HostContext {
pub caps: HostCaps,
pub fs_root: Option<PathBuf>,
pub cwd: PathBuf,
pub argv: Vec<String>,
/// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export).
pub soft_side_effects: bool,
pub sleep_limit_ms: Option<u64>,
}
impl Default for HostContext {
fn default() -> Self {
Self {
caps: HostCaps::default(),
fs_root: None,
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
argv: Vec::new(),
soft_side_effects: false,
sleep_limit_ms: Some(30_000),
}
}
}
impl HostContext {
pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec<String>) -> Self {
let mut ctx = Self::default();
ctx.caps = caps;
ctx.argv = argv;
if let Some(p) = path {
if let Some(parent) = p.parent() {
let parent = if parent.as_os_str().is_empty() {
PathBuf::from(".")
} else {
parent.to_path_buf()
};
ctx.cwd = parent.clone();
ctx.fs_root = Some(parent);
}
}
ctx
}
/// Capture stdout / view / export: soft exit + sleep clamp; same caps as CLI by default.
pub fn for_capture(path: Option<&Path>, caps: HostCaps) -> Self {
let mut ctx = Self::for_run(path, caps, Vec::new());
ctx.soft_side_effects = true;
ctx.sleep_limit_ms = Some(0);
ctx
}
pub fn allow_fs_write(&self) -> bool {
self.caps.fs_write
}
pub fn allow_exec(&self) -> bool {
self.caps.exec
}
pub fn allow_net(&self) -> bool {
self.caps.net
}
pub fn resolve_path(&self, rel: &str) -> Result<PathBuf, String> {
let p = Path::new(rel);
let abs = if p.is_absolute() {
p.to_path_buf()
} else {
self.cwd.join(p)
};
if let Some(root) = &self.fs_root {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.clone());
let check = abs.canonicalize().unwrap_or_else(|_| abs.clone());
if !path_under_root(&check, &root_canon) && !path_under_root(&abs, root) {
if let Some(parent) = abs.parent() {
let parent_ok = parent
.canonicalize()
.map(|p| path_under_root(&p, &root_canon))
.unwrap_or_else(|_| path_under_root(parent, root));
if !parent_ok {
return Err(format!("path escapes sandbox root: {}", abs.display()));
}
} else {
return Err(format!("path escapes sandbox root: {}", abs.display()));
}
}
}
Ok(abs)
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Minimal HTTP host primitives (HTTP cleartext in v1; HTTPS deferred).
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;
use crate::host::HostContext;
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} must be text")),
}
}
struct UrlParts {
host: String,
port: u16,
path: String,
}
fn parse_http_url(url: &str) -> Result<UrlParts, String> {
let rest = url
.strip_prefix("http://")
.ok_or_else(|| {
if url.starts_with("https://") {
"https is not supported yet (use http:// or wait for TLS)".to_string()
} else {
"url must start with http://".into()
}
})?;
let (hostport, path) = match rest.split_once('/') {
Some((h, p)) => (h, format!("/{p}")),
None => (rest, "/".into()),
};
let (host, port) = if let Some((h, p)) = hostport.split_once(':') {
let port: u16 = p
.parse()
.map_err(|_| format!("invalid port in url: {p}"))?;
(h.to_string(), port)
} else {
(hostport.to_string(), 80)
};
if host.is_empty() {
return Err("url missing host".into());
}
Ok(UrlParts { host, port, path })
}
fn http_exchange(
method: &str,
url: &str,
body: Option<&str>,
content_type: &str,
) -> Result<(u16, String), String> {
let parts = parse_http_url(url)?;
let addr = format!("{}:{}", parts.host, parts.port);
let mut stream = TcpStream::connect(&addr).map_err(|e| format!("http connect {addr}: {e}"))?;
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.ok();
stream
.set_write_timeout(Some(Duration::from_secs(10)))
.ok();
let body = body.unwrap_or("");
let mut req = format!(
"{method} {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: marqdo\r\n",
path = parts.path,
host = parts.host,
);
if method == "POST" {
req.push_str(&format!(
"Content-Type: {content_type}\r\nContent-Length: {}\r\n",
body.len()
));
}
req.push_str("\r\n");
if method == "POST" {
req.push_str(body);
}
stream
.write_all(req.as_bytes())
.map_err(|e| format!("http write: {e}"))?;
let mut buf = Vec::new();
stream
.read_to_end(&mut buf)
.map_err(|e| format!("http read: {e}"))?;
if buf.len() > 2 * 1024 * 1024 {
return Err("http response exceeds 2MiB limit".into());
}
let text = String::from_utf8_lossy(&buf);
let (header, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_ref(), ""));
let status = header
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(0);
Ok((status, body.to_string()))
}
pub fn http_get(ctx: &HostContext, url: &Value) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_get denied by host policy".into());
}
let url = as_text(url, "url")?;
let (status, body) = http_exchange("GET", url, None, "")?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(body)),
]))
}
pub fn http_post(
ctx: &HostContext,
url: &Value,
body: &Value,
content_type: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_post denied by host policy".into());
}
let url = as_text(url, "url")?;
let body = as_text(body, "body")?;
let ct = match content_type {
Some(v) => as_text(v, "content_type")?,
None => "text/plain; charset=utf-8",
};
let (status, resp) = http_exchange("POST", url, Some(body), ct)?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(resp)),
]))
}
pub fn url_encode(text: &Value) -> Result<Value, String> {
let s = as_text(text, "text")?;
Ok(Value::Text(
s.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
(b as char).to_string()
}
b' ' => "+".into(),
_ => format!("%{b:02X}"),
})
.collect(),
))
}
+79
View File
@@ -0,0 +1,79 @@
//! System / process host primitives.
use std::process::Command;
use crate::host::HostContext;
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} must be text")),
}
}
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!("{label} must be int")),
}
}
pub fn env_get(name: &Value) -> Result<Value, String> {
let key = as_text(name, "name")?;
Ok(match std::env::var(key) {
Ok(v) => Value::Text(v),
Err(_) => Value::None,
})
}
pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
let key = as_text(name, "name")?;
let val = as_text(value, "value")?;
std::env::set_var(key, val);
Ok(Value::None)
}
pub fn args(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
))
}
pub fn cwd(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::Text(ctx.cwd.display().to_string()))
}
pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
let c = as_i64(code, "code")?;
if ctx.soft_side_effects {
return Err(format!("exit {c} (soft mode does not terminate process)"));
}
std::process::exit(c as i32);
}
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
if !ctx.allow_exec() {
return Err("exec denied by host policy".into());
}
let cmd = as_text(cmd, "cmd")?;
let mut command = Command::new(cmd);
command.current_dir(&ctx.cwd);
if let Some(a) = args {
match a {
Value::List(xs) => {
for x in xs {
command.arg(x.as_display());
}
}
Value::Text(s) => {
command.arg(s);
}
_ => return Err("exec args must be list or text".into()),
}
}
let status = command
.status()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
+71
View File
@@ -0,0 +1,71 @@
//! Time host primitives.
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{DateTime, NaiveDateTime, Utc};
use crate::host::HostContext;
use crate::value::Value;
pub fn now_unix() -> Result<Value, String> {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
}
pub fn now_ms() -> Result<Value, String> {
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
}
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!("{label} must be int")),
}
}
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} must be text")),
}
}
pub fn format_time(unix: &Value, pattern: &Value) -> Result<Value, String> {
let secs = as_i64(unix, "unix")?;
let pat = as_text(pattern, "pattern")?;
let dt = DateTime::<Utc>::from_timestamp(secs, 0)
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
Ok(Value::Text(dt.format(pat).to_string()))
}
pub fn parse_time(text: &Value, pattern: &Value) -> Result<Value, String> {
let t = as_text(text, "text")?;
let pat = as_text(pattern, "pattern")?;
let dt = NaiveDateTime::parse_from_str(t, pat).map_err(|e| format!("parse_time: {e}"))?;
Ok(Value::Int(dt.and_utc().timestamp()))
}
pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
let n = as_i64(ms, "ms")?;
if n < 0 {
return Err("sleep_ms must be >= 0".into());
}
let n = n as u64;
if let Some(lim) = ctx.sleep_limit_ms {
if n > lim {
return Err(format!("sleep_ms {n} exceeds limit {lim}"));
}
}
if n > 0 {
thread::sleep(Duration::from_millis(n));
}
Ok(Value::None)
}