Refactor executable library handbooks and improve document reading
This commit is contained in:
1 parent
16c44588d5
commit
c50c515c4a
191 files changed
+29572
-7816
No files matched your search
@@ -0,0 +1,199 @@
|
||||
//! Optional ZIP tasks with preflight, expansion limits and no path traversal.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = operate(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("ZIP unavailable: build with net-host (native default)".into())
|
||||
};
|
||||
Ok(super::result::capture(
|
||||
if id == HostFn::ZipPack {
|
||||
"archive.pack"
|
||||
} else {
|
||||
"archive.unpack"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn operate(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("ZIP unavailable in CoW sandbox".into());
|
||||
}
|
||||
let src = ctx.resolve_path(super::as_text(arg(b, "src")?, "src")?)?;
|
||||
let dest = ctx.resolve_path(super::as_text(arg(b, "dest")?, "dest")?)?;
|
||||
let max = match arg(b, "max_bytes")? {
|
||||
Value::Int(n) if *n > 0 && *n <= 1024 * 1024 * 1024 => *n as u64,
|
||||
_ => return Err("max_bytes must be 1..1073741824".into()),
|
||||
};
|
||||
if dest.exists() {
|
||||
return Err("destination conflict: ZIP output must not exist".into());
|
||||
}
|
||||
if id == HostFn::ZipPack {
|
||||
if !src.is_dir() || dest.starts_with(&src) {
|
||||
return Err("pack src must be directory and dest outside src".into());
|
||||
}
|
||||
let mut args = HashMap::new();
|
||||
args.insert("path".into(), Value::Text(src.to_string_lossy().into()));
|
||||
args.insert("pattern".into(), Value::Text("**".into()));
|
||||
args.insert("exclude".into(), Value::None);
|
||||
args.insert("max_depth".into(), Value::Int(256));
|
||||
args.insert("kind".into(), Value::Text("file".into()));
|
||||
let Value::List(files) = super::fs_ops::call(ctx, HostFn::FsFind, &args)? else {
|
||||
unreachable!()
|
||||
};
|
||||
let total = files.iter().try_fold(0u64, |n, name| {
|
||||
let p = src.join(super::as_text(name, "name")?);
|
||||
let size = fs::metadata(p).map_err(|e| e.to_string())?.len();
|
||||
n.checked_add(size)
|
||||
.ok_or_else(|| "archive size overflow".to_string())
|
||||
})?;
|
||||
if total > max {
|
||||
return Err("archive source exceeds max_bytes".into());
|
||||
}
|
||||
let parent = dest.parent().ok_or("archive needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let temp = parent.join(format!(".mq-zip-{}", random_name()?));
|
||||
let file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let written = (|| {
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let mut buffer = [0u8; 65536];
|
||||
let mut seen = 0u64;
|
||||
for name in &files {
|
||||
let name = super::as_text(name, "name")?;
|
||||
writer
|
||||
.start_file(
|
||||
name,
|
||||
zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated),
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let p = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let mut file = fs::File::open(p).map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = file.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
seen += n as u64;
|
||||
if seen > max {
|
||||
return Err("archive source grew past max_bytes".into());
|
||||
}
|
||||
writer.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
writer
|
||||
.finish()
|
||||
.map_err(|e| e.to_string())?
|
||||
.sync_all()
|
||||
.map_err(|e| e.to_string())?;
|
||||
// hard_link is an atomic no-clobber publish on the same filesystem.
|
||||
fs::hard_link(&temp, &dest).map_err(|e| e.to_string())?;
|
||||
Ok(Value::Int(files.len() as i64))
|
||||
})();
|
||||
let _ = fs::remove_file(&temp);
|
||||
return written;
|
||||
}
|
||||
let file = fs::File::open(src).map_err(|e| e.to_string())?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
if zip.len() > 100000 {
|
||||
return Err("archive exceeds 100000 entries".into());
|
||||
}
|
||||
let mut names = HashSet::new();
|
||||
let mut total = 0u64;
|
||||
for i in 0..zip.len() {
|
||||
let entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let name = entry
|
||||
.enclosed_name()
|
||||
.ok_or("archive path escapes destination")?;
|
||||
if entry.name().contains('\\') || name == Path::new("") || !names.insert(name.to_path_buf())
|
||||
{
|
||||
return Err("invalid or duplicate archive path".into());
|
||||
}
|
||||
if entry
|
||||
.unix_mode()
|
||||
.is_some_and(|mode| mode & 0o170000 == 0o120000)
|
||||
{
|
||||
return Err("archive symlinks unsupported".into());
|
||||
}
|
||||
total = total
|
||||
.checked_add(entry.size())
|
||||
.ok_or("archive size overflow")?;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(dest.parent().ok_or("destination needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
fs::create_dir(&dest).map_err(|e| e.to_string())?;
|
||||
let extracted = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let path = ctx.resolve_path(
|
||||
dest.join(entry.enclosed_name().ok_or("invalid archive path")?)
|
||||
.to_str()
|
||||
.ok_or("non UTF-8 path")?,
|
||||
)?;
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(path).map_err(|e| e.to_string())?;
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(path.parent().ok_or("entry needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = entry.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Int(zip.len() as i64))
|
||||
})();
|
||||
if extracted.is_err() {
|
||||
let _ = fs::remove_dir_all(&dest);
|
||||
}
|
||||
extracted
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn random_name() -> Result<String, String> {
|
||||
let mut bytes = [0u8; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?;
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
+61
-17
@@ -16,7 +16,7 @@ fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
|
||||
if *n < 1 {
|
||||
return Err("put path index must be >= 1 (1-based)".into());
|
||||
}
|
||||
Ok(vec![PathSeg::Index1(*n as usize)])
|
||||
Ok(vec![PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)])
|
||||
}
|
||||
Value::List(xs) => {
|
||||
if xs.is_empty() {
|
||||
@@ -32,7 +32,7 @@ fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
|
||||
"put path segment {i}: index must be >= 1 (1-based)"
|
||||
));
|
||||
}
|
||||
out.push(PathSeg::Index1(*n as usize));
|
||||
out.push(PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
@@ -284,7 +284,7 @@ pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result<Value, Stri
|
||||
Value::None => vec![],
|
||||
_ => return Err("list_insert needs list".into()),
|
||||
};
|
||||
if index < 0 || index as usize > xs.len() {
|
||||
if index < 0 || index > xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_insert index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -298,7 +298,7 @@ pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result<Value, Stri
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_set_at needs list".into());
|
||||
};
|
||||
if index < 0 || index as usize >= xs.len() {
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_set_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -313,7 +313,7 @@ pub fn list_remove_at(list: &Value, index: i64) -> Result<Value, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_remove_at needs list".into());
|
||||
};
|
||||
if index < 0 || index as usize >= xs.len() {
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_remove_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
@@ -385,16 +385,33 @@ pub fn list_last(list: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
/// Total type order avoids cyclic comparisons between numeric and text keys.
|
||||
pub(super) fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering;
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => x.cmp(y),
|
||||
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Int(x), Value::Num(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Num(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal),
|
||||
(Value::Text(x), Value::Text(y)) => x.cmp(y),
|
||||
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
|
||||
_ => a.as_display().cmp(&b.as_display()),
|
||||
fn rank(v:&Value)->u8{match v{
|
||||
Value::Int(_)|Value::Num(_)=>0,Value::Text(_)=>1,Value::Bool(_)=>2,
|
||||
Value::None=>3,Value::List(_)=>4,Value::Map(_)=>5,Value::Formula(_)=>6,
|
||||
Value::Code(_)=>7,Value::Secret(_)=>8,Value::Handle(_)=>9,
|
||||
}}
|
||||
fn int_float(integer:i64,number:f64)->Ordering{
|
||||
if number.is_nan(){return Ordering::Less}
|
||||
if number >= -(i64::MIN as f64){return Ordering::Less}
|
||||
if number < i64::MIN as f64{return Ordering::Greater}
|
||||
let truncated=number as i64;
|
||||
match integer.cmp(&truncated){Ordering::Equal=>0.0f64.partial_cmp(&number.fract()).unwrap_or(Ordering::Equal),other=>other}
|
||||
}
|
||||
let order=rank(a).cmp(&rank(b));if !order.is_eq(){return order}
|
||||
match (a,b){
|
||||
(Value::Int(a),Value::Int(b))=>a.cmp(b),
|
||||
(Value::Num(a),Value::Num(b))=>match(a.is_nan(),b.is_nan()){
|
||||
(true,false)=>Ordering::Greater,(false,true)=>Ordering::Less,
|
||||
_=>a.partial_cmp(b).unwrap_or_else(||a.total_cmp(b)),
|
||||
},
|
||||
(Value::Int(a),Value::Num(b))=>int_float(*a,*b),
|
||||
(Value::Num(a),Value::Int(b))=>int_float(*b,*a).reverse(),
|
||||
(Value::Text(a),Value::Text(b))=>a.cmp(b),
|
||||
(Value::Bool(a),Value::Bool(b))=>a.cmp(b),
|
||||
_=>a.as_display().cmp(&b.as_display()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,9 +464,12 @@ pub fn list_sort_by(list: &Value, key: &Value) -> Result<Value, String> {
|
||||
pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut seen: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
|
||||
for x in xs {
|
||||
if !out.iter().any(|y| y == x) {
|
||||
let bucket = seen.entry(super::collection_ops::fingerprint(x)).or_default();
|
||||
if !bucket.iter().any(|i| out[*i] == *x) {
|
||||
bucket.push(out.len());
|
||||
out.push(x.clone());
|
||||
}
|
||||
}
|
||||
@@ -462,7 +482,7 @@ pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
|
||||
pub fn list_chunk(list: &Value, size: &Value) -> Result<Value, String> {
|
||||
let n = match size {
|
||||
Value::Int(i) if *i > 0 => *i as usize,
|
||||
Value::Int(i) if *i > 0 => usize::try_from(*i).unwrap_or(usize::MAX),
|
||||
Value::Int(_) => return Err("chunk size must be positive".into()),
|
||||
_ => return Err("chunk size needs int".into()),
|
||||
};
|
||||
@@ -570,3 +590,27 @@ mod tests {
|
||||
assert!(matches!(m, Value::Map(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod task_scale_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unique_preserves_signed_zero_nan_and_nested_equality(){
|
||||
let xs=Value::List(vec![Value::Num(-0.0),Value::Num(0.0),Value::Num(f64::NAN),Value::Num(f64::NAN),Value::Int(0),Value::List(vec![Value::Num(-0.0)]),Value::List(vec![Value::Num(0.0)])]);
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};
|
||||
assert_eq!(out.len(),5);assert_eq!(out[0],Value::Num(-0.0));assert_eq!(out[3],Value::Int(0));
|
||||
}
|
||||
#[test]
|
||||
fn mixed_order_is_transitive_and_exact_at_integer_float_boundary(){
|
||||
let values=[Value::Int(2),Value::Int(10),Value::Text("11".into()),Value::Int(i64::MAX),Value::Num(i64::MAX as f64),Value::Num(f64::NAN),Value::Num(-0.0),Value::Bool(false),Value::None];
|
||||
for a in &values{for b in &values{for c in &values{
|
||||
if cmp_value(a,b).is_le()&&cmp_value(b,c).is_le(){assert!(cmp_value(a,c).is_le(),"{a:?} {b:?} {c:?}");}
|
||||
}}}
|
||||
assert!(cmp_value(&Value::Int(i64::MAX),&Value::Num(i64::MAX as f64)).is_lt());
|
||||
}
|
||||
#[test]
|
||||
fn bulk_unique_handles_one_hundred_thousand_values(){
|
||||
let xs=Value::List((0..100_000).map(|n|Value::Int(n%50_000)).collect());
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};assert_eq!(out.len(),50_000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
//! Field-driven collection transforms. No string evaluation or callback language.
|
||||
use super::{as_text, collection::cmp_value};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn list(v: &Value) -> Result<&[Value], String> {
|
||||
match v {
|
||||
Value::List(xs) => Ok(xs),
|
||||
_ => Err("expected list".into()),
|
||||
}
|
||||
}
|
||||
fn record(v: &Value) -> Result<&[(String, Value)], String> {
|
||||
match v {
|
||||
Value::Map(m) => Ok(m),
|
||||
_ => Err("expected record map".into()),
|
||||
}
|
||||
}
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
record(v)?
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| format!("missing field {key}"))
|
||||
}
|
||||
fn strings(v: &Value) -> Result<Vec<String>, String> {
|
||||
list(v)?
|
||||
.iter()
|
||||
.map(|v| as_text(v, "key").map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
fn integer(v: &Value) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err("expected integer".into()),
|
||||
}
|
||||
}
|
||||
fn number(v: &Value) -> Result<f64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n as f64),
|
||||
Value::Num(n) if n.is_finite() => Ok(*n),
|
||||
_ => Err("expected finite number".into()),
|
||||
}
|
||||
}
|
||||
fn row(fields: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
// Structural equality is type-sensitive and map-order-sensitive, like Value::eq.
|
||||
// Fingerprints accelerate buckets; equality is still checked inside each bucket.
|
||||
pub(super) fn fingerprint(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Num(n) if *n == 0.0 => "Num(0)".into(),
|
||||
Value::List(xs) => format!("List{:?}", xs.iter().map(fingerprint).collect::<Vec<_>>()),
|
||||
Value::Map(xs) => format!(
|
||||
"Map{:?}",
|
||||
xs.iter()
|
||||
.map(|(k, v)| (k, fingerprint(v)))
|
||||
.collect::<Vec<_>>()
|
||||
),
|
||||
Value::Formula(formula) => format!("Formula{}", formula.as_display()),
|
||||
_ => format!("{v:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::ListRange => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let end = integer(arg(b, "end")?)?;
|
||||
let step = integer(arg(b, "step")?)?;
|
||||
if step == 0 {
|
||||
return Err("range step cannot be zero".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut n = start;
|
||||
while if step > 0 { n < end } else { n > end } {
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("range exceeds 1000000 items".into());
|
||||
}
|
||||
out.push(Value::Int(n));
|
||||
match n.checked_add(step) {
|
||||
Some(next) => n = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListEnumerate => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
let index = start
|
||||
.checked_add(i as i64)
|
||||
.ok_or("enumerate index overflow")?;
|
||||
Ok(row(vec![
|
||||
("index", Value::Int(index)),
|
||||
("value", v.clone()),
|
||||
]))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListPluck => {
|
||||
let key = text(b, "key")?;
|
||||
Ok(Value::List(
|
||||
list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| field(v, key).cloned())
|
||||
.collect::<Result<_, _>>()?,
|
||||
))
|
||||
}
|
||||
HostFn::ListProject => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
if keys.iter().collect::<HashSet<_>>().len() != keys.len() {
|
||||
return Err("project keys must be unique".into());
|
||||
}
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| {
|
||||
keys.iter()
|
||||
.map(|k| Ok((k.clone(), field(v, k)?.clone())))
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
.map(Value::Map)
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListWhere => {
|
||||
let key = text(b, "key")?;
|
||||
let op = text(b, "op")?;
|
||||
let wanted = arg(b, "value")?;
|
||||
if !matches!(
|
||||
op,
|
||||
"eq" | "ne" | "gt" | "ge" | "lt" | "le" | "contains" | "in"
|
||||
) {
|
||||
return Err(format!("unknown where operator {op}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let got = field(v, key)?;
|
||||
let yes = match op {
|
||||
"eq" => got == wanted,
|
||||
"ne" => got != wanted,
|
||||
"gt" | "ge" | "lt" | "le" => {
|
||||
let order = match (got, wanted) {
|
||||
(Value::Text(a), Value::Text(b)) => a.cmp(b),
|
||||
_ => number(got)?
|
||||
.partial_cmp(&number(wanted)?)
|
||||
.ok_or("unordered comparison")?,
|
||||
};
|
||||
match op {
|
||||
"gt" => order.is_gt(),
|
||||
"ge" => order.is_ge(),
|
||||
"lt" => order.is_lt(),
|
||||
_ => order.is_le(),
|
||||
}
|
||||
}
|
||||
"contains" => match got {
|
||||
Value::List(xs) => xs.contains(wanted),
|
||||
Value::Text(s) => s.contains(as_text(wanted, "value")?),
|
||||
_ => return Err("contains needs text or list".into()),
|
||||
},
|
||||
"in" => list(wanted)?.contains(got),
|
||||
_ => return Err(format!("unknown where operator {op}")),
|
||||
};
|
||||
if yes {
|
||||
out.push(v.clone())
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListGroupBy | HostFn::ListUniqueBy => {
|
||||
let key = text(b, "key")?;
|
||||
let mut groups: Vec<(Value, Vec<Value>)> = Vec::new();
|
||||
let mut index: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let k = field(v, key)?;
|
||||
let fp = fingerprint(k);
|
||||
let bucket = index.entry(fp).or_default();
|
||||
if let Some(i) = bucket.iter().find(|i| groups[**i].0 == *k) {
|
||||
groups[*i].1.push(v.clone());
|
||||
} else {
|
||||
bucket.push(groups.len());
|
||||
groups.push((k.clone(), vec![v.clone()]));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
groups
|
||||
.into_iter()
|
||||
.map(|(key, rows)| {
|
||||
if id == HostFn::ListUniqueBy {
|
||||
rows.into_iter().next().unwrap()
|
||||
} else {
|
||||
row(vec![
|
||||
("key", key),
|
||||
("count", Value::Int(rows.len() as i64)),
|
||||
("rows", Value::List(rows)),
|
||||
])
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListAggregate => {
|
||||
let xs = list(arg(b, "list")?)?;
|
||||
let op = text(b, "op")?;
|
||||
if op == "count" {
|
||||
return Ok(Value::Int(xs.len() as i64));
|
||||
}
|
||||
let key = arg(b, "key")?;
|
||||
let values = xs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
if matches!(key, Value::None) {
|
||||
Ok(v)
|
||||
} else {
|
||||
field(v, as_text(key, "key")?)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
if op == "sum" && values.iter().all(|v| matches!(v, Value::Int(_))) {
|
||||
let sum = values.into_iter().try_fold(0i64, |sum, v| {
|
||||
sum.checked_add(integer(v)?)
|
||||
.ok_or_else(|| "sum integer overflow".to_string())
|
||||
})?;
|
||||
return Ok(Value::Int(sum));
|
||||
}
|
||||
let nums = values
|
||||
.into_iter()
|
||||
.map(number)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let n = match op {
|
||||
"sum" => nums.iter().sum(),
|
||||
"mean" if !nums.is_empty() => nums.iter().sum::<f64>() / nums.len() as f64,
|
||||
"min" if !nums.is_empty() => nums.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
"max" if !nums.is_empty() => nums.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
_ => {
|
||||
return Err(
|
||||
"aggregate needs sum/count/min/max/mean; empty min/max/mean is invalid"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("aggregate overflow".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
HostFn::ListSortKeys => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
let descending = matches!(arg(b, "descending")?, Value::Bool(true));
|
||||
let mut xs = list(arg(b, "list")?)?.to_vec();
|
||||
for v in &xs {
|
||||
for k in &keys {
|
||||
field(v, k)?;
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| {
|
||||
let mut order = std::cmp::Ordering::Equal;
|
||||
for k in &keys {
|
||||
order = cmp_value(field(a, k).unwrap(), field(b, k).unwrap());
|
||||
if !order.is_eq() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if descending {
|
||||
order.reverse()
|
||||
} else {
|
||||
order
|
||||
}
|
||||
});
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
HostFn::ListRename => {
|
||||
let names = record(arg(b, "fields")?)?;
|
||||
for (_, v) in names {
|
||||
as_text(v, "new field name")?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let mut seen = HashSet::new();
|
||||
let mut fields = Vec::new();
|
||||
for (k, v) in record(v)? {
|
||||
let name = names
|
||||
.iter()
|
||||
.find(|(old, _)| old == k)
|
||||
.map(|(_, v)| as_text(v, "name").unwrap())
|
||||
.unwrap_or(k);
|
||||
if !seen.insert(name) {
|
||||
return Err(format!("rename conflict: {name}"));
|
||||
}
|
||||
fields.push((name.into(), v.clone()));
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableFromColumns => {
|
||||
let columns = record(arg(b, "columns")?)?;
|
||||
let n = columns
|
||||
.first()
|
||||
.map(|(_, v)| list(v).map(|xs| xs.len()))
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
for (_, v) in columns {
|
||||
if list(v)?.len() != n {
|
||||
return Err("column lengths differ".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
Value::Map(
|
||||
columns
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), list(v).unwrap()[i].clone()))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::TableToColumns => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
if rows.is_empty() {
|
||||
return Ok(Value::Map(vec![]));
|
||||
}
|
||||
let keys: Vec<_> = record(&rows[0])?.iter().map(|(k, _)| k.clone()).collect();
|
||||
for v in rows {
|
||||
let fields = record(v)?;
|
||||
if fields.len() != keys.len()
|
||||
|| keys.iter().any(|k| !fields.iter().any(|(f, _)| f == k))
|
||||
{
|
||||
return Err("rows have different fields".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(
|
||||
keys.into_iter()
|
||||
.map(|k| {
|
||||
let values = rows.iter().map(|v| field(v, &k).unwrap().clone()).collect();
|
||||
(k, Value::List(values))
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListJoin => {
|
||||
let a = list(arg(b, "a")?)?;
|
||||
let b_rows = list(arg(b, "b")?)?;
|
||||
let key = text(b, "key")?;
|
||||
let right_key = text(b, "right_key")?;
|
||||
let mode = text(b, "mode")?;
|
||||
if !matches!(mode, "inner" | "left") {
|
||||
return Err("join mode must be inner or left".into());
|
||||
}
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in b_rows {
|
||||
index
|
||||
.entry(fingerprint(field(v, right_key)?))
|
||||
.or_default()
|
||||
.push(v);
|
||||
}
|
||||
let right_fields: Vec<_> = b_rows
|
||||
.first()
|
||||
.map(|v| record(v).map(|m| m.iter().map(|(k, _)| k.clone()).collect()))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
for right in b_rows {
|
||||
let fields = record(right)?;
|
||||
if fields.len() != right_fields.len()
|
||||
|| right_fields
|
||||
.iter()
|
||||
.any(|key| !fields.iter().any(|(k, _)| k == key))
|
||||
{
|
||||
return Err("join right rows have different fields".into());
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for left in a {
|
||||
let left_key = field(left, key)?;
|
||||
let hits = index.get(&fingerprint(left_key));
|
||||
let matches: Vec<Option<&Value>> = match hits {
|
||||
Some(h) => {
|
||||
let values: Vec<_> = h
|
||||
.iter()
|
||||
.filter(|v| field(v, right_key).is_ok_and(|key| key == left_key))
|
||||
.map(|v| Some(*v))
|
||||
.collect();
|
||||
if values.is_empty() && mode == "left" {
|
||||
vec![None]
|
||||
} else {
|
||||
values
|
||||
}
|
||||
}
|
||||
None if mode == "left" => vec![None],
|
||||
_ => vec![],
|
||||
};
|
||||
for hit in matches {
|
||||
let mut fields = record(left)?.to_vec();
|
||||
let source = hit.map(record).transpose()?;
|
||||
for k in &right_fields {
|
||||
if k == right_key && key == right_key {
|
||||
continue;
|
||||
}
|
||||
let name = if fields.iter().any(|(f, _)| f == k) {
|
||||
format!("right_{k}")
|
||||
} else {
|
||||
k.clone()
|
||||
};
|
||||
if fields.iter().any(|(f, _)| f == &name) {
|
||||
return Err(format!("join field conflict: {name}"));
|
||||
}
|
||||
let value = source
|
||||
.and_then(|m| m.iter().find(|(f, _)| f == k))
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None);
|
||||
fields.push((name, value));
|
||||
}
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("join exceeds 1000000 rows".into());
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableCast => {
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut out = Vec::new();
|
||||
for (i, v) in list(arg(b, "rows")?)?.iter().enumerate() {
|
||||
let mut fields = record(v)?.to_vec();
|
||||
for (k, ty) in schema {
|
||||
let value = field(v, k)?;
|
||||
let ty = as_text(ty, "type")?;
|
||||
let cast = cast(value, ty).map_err(|e| format!("row {i} field {k}: {e}"))?;
|
||||
fields.iter_mut().find(|(name, _)| name == k).unwrap().1 = cast;
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableSummarize => {
|
||||
let groups = call(_ctx, HostFn::ListGroupBy, b)?;
|
||||
let field_name = text(b, "field")?;
|
||||
let op = text(b, "op")?;
|
||||
let mut out = Vec::new();
|
||||
for group in list(&groups)? {
|
||||
let rows = field(group, "rows")?;
|
||||
let mut args = HashMap::new();
|
||||
args.insert("list".into(), rows.clone());
|
||||
args.insert("key".into(), Value::Text(field_name.into()));
|
||||
args.insert("op".into(), Value::Text(op.into()));
|
||||
let value = call(_ctx, HostFn::ListAggregate, &args)?;
|
||||
out.push(row(vec![
|
||||
("key", field(group, "key")?.clone()),
|
||||
("count", field(group, "count")?.clone()),
|
||||
("value", value),
|
||||
]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableTryCast => {
|
||||
let answer =
|
||||
call(_ctx, HostFn::TableCast, b).map_err(|e| format!("validation_failed: {e}"));
|
||||
Ok(super::result::capture("table.cast", answer))
|
||||
}
|
||||
HostFn::TableValidate => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut errors = Vec::new();
|
||||
for (index, value) in rows.iter().enumerate() {
|
||||
let fields = record(value)?;
|
||||
for (key, ty) in schema {
|
||||
let name = as_text(ty, "type")?;
|
||||
let ty = crate::contract::Ty::parse(name);
|
||||
let got = fields.iter().find(|(k, _)| k == key).map(|(_, v)| v);
|
||||
if !got.is_some_and(|v| ty.matches_value(v)) {
|
||||
errors.push(row(vec![
|
||||
("row", Value::Int(index as i64)),
|
||||
("field", Value::Text(key.clone())),
|
||||
("expected", Value::Text(name.into())),
|
||||
(
|
||||
"actual",
|
||||
Value::Text(
|
||||
got.map(crate::contract::type_of)
|
||||
.unwrap_or("missing")
|
||||
.into(),
|
||||
),
|
||||
),
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(super::result::capture(
|
||||
"table.validate",
|
||||
Ok(arg(b, "rows")?.clone()),
|
||||
))
|
||||
} else {
|
||||
let mut result = super::result::capture(
|
||||
"table.validate",
|
||||
Err("validation_failed: records do not match schema".into()),
|
||||
);
|
||||
if let Value::Map(fields) = &mut result {
|
||||
if let Some((_, Value::Map(error))) =
|
||||
fields.iter_mut().find(|(k, _)| k == "error")
|
||||
{
|
||||
error.push(("details".into(), Value::List(errors)));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
HostFn::ListUnion | HostFn::ListIntersection | HostFn::ListDifference => {
|
||||
let left = list(arg(b, "a")?)?;
|
||||
let right = list(arg(b, "b")?)?;
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in right {
|
||||
index.entry(fingerprint(v)).or_default().push(v)
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
for v in left {
|
||||
let contains = index
|
||||
.get(&fingerprint(v))
|
||||
.is_some_and(|bucket| bucket.iter().any(|r| *r == v));
|
||||
if id == HostFn::ListUnion
|
||||
|| (id == HostFn::ListIntersection && contains)
|
||||
|| (id == HostFn::ListDifference && !contains)
|
||||
{
|
||||
values.push(v.clone())
|
||||
}
|
||||
}
|
||||
if id == HostFn::ListUnion {
|
||||
values.extend_from_slice(right)
|
||||
}
|
||||
super::collection::list_unique(&Value::List(values))
|
||||
}
|
||||
_ => Err("not a collection transform".into()),
|
||||
}
|
||||
}
|
||||
fn cast(v: &Value, ty: &str) -> Result<Value, String> {
|
||||
match ty {
|
||||
"text" => Ok(Value::Text(v.as_display())),
|
||||
"int" => match v {
|
||||
Value::Int(_) => Ok(v.clone()),
|
||||
Value::Text(s) => s
|
||||
.parse::<i64>()
|
||||
.map(Value::Int)
|
||||
.map_err(|_| "invalid integer".into()),
|
||||
_ => Err("int expects integer or text".into()),
|
||||
},
|
||||
"number" => {
|
||||
let n = match v {
|
||||
Value::Text(s) => s.parse::<f64>().map_err(|_| "invalid number")?,
|
||||
_ => number(v)?,
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("non-finite number".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
"bool" => match v {
|
||||
Value::Bool(_) => Ok(v.clone()),
|
||||
Value::Text(s) => match s.as_str() {
|
||||
"true" | "True" => Ok(Value::Bool(true)),
|
||||
"false" | "False" => Ok(Value::Bool(false)),
|
||||
_ => Err("invalid bool".into()),
|
||||
},
|
||||
_ => Err("bool expects bool or text".into()),
|
||||
},
|
||||
"any" => Ok(v.clone()),
|
||||
_ => Err(format!("unknown cast type {ty}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Recoverable parsing and timezone operations at the public data boundary.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
_ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::TomlStringify => super::toml_ops::stringify(arg(b, "value")?),
|
||||
HostFn::TomlTryParse => Ok(super::result::capture(
|
||||
"toml.parse",
|
||||
super::toml_ops::parse(arg(b, "text")?).map_err(|e| format!("invalid_toml: {e}")),
|
||||
)),
|
||||
HostFn::DatetimeLocal => Ok(super::result::capture(
|
||||
"datetime.parse_local",
|
||||
super::datetime::local(arg(b, "text")?, arg(b, "zone")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
HostFn::DatetimeCalendarAdd => Ok(super::result::capture(
|
||||
"datetime.add_calendar",
|
||||
super::datetime::calendar_add(arg(b, "dt")?, arg(b, "days")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
_ => Err("not a data operation".into()),
|
||||
}
|
||||
}
|
||||
+60
-20
@@ -1,10 +1,11 @@
|
||||
//! Calendar / timezone subset for Mid2 M7 (`lib/datetime`).
|
||||
//! Calendar moments with fixed offsets or embedded IANA timezone rules.
|
||||
//!
|
||||
//! Moments are plain maps: `{unix, zone, iso}`. Zone is a fixed offset (`+08:00`)
|
||||
//! or alias (`UTC`); a few fixed-offset IANA names are accepted. Full tzdb is out of scope.
|
||||
//! Moments retain `{unix, zone, iso}`; `zone` is the numeric offset.
|
||||
//! Named zones additionally retain `timezone`, so future instants and calendar
|
||||
//! arithmetic recompute offsets using embedded IANA/DST rules.
|
||||
|
||||
use crate::host::as_text;
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc, Offset, LocalResult};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
@@ -126,7 +127,11 @@ fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> {
|
||||
}
|
||||
}
|
||||
let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?;
|
||||
Ok((unix, zone_of_moment(entries)?))
|
||||
let offset = if let Some((_, Value::Text(zone))) = entries.iter().find(|(k,_)|k=="timezone") {
|
||||
let zone: chrono_tz::Tz = zone.parse().map_err(|_| format!("unknown IANA timezone {zone}"))?;
|
||||
zone.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.offset().fix()
|
||||
} else { zone_of_moment(entries)? };
|
||||
Ok((unix, offset))
|
||||
}
|
||||
Value::Text(s) => {
|
||||
// Treat bare ISO/RFC3339 text as a moment.
|
||||
@@ -151,11 +156,10 @@ pub fn now() -> Result<Value, String> {
|
||||
|
||||
pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
let off = match zone {
|
||||
None | Some(Value::None) => FixedOffset::east_opt(0).unwrap(),
|
||||
Some(z) => parse_zone(as_text(z, "zone")?)?,
|
||||
};
|
||||
moment(secs, off)
|
||||
match zone {
|
||||
None | Some(Value::None) => moment(secs, FixedOffset::east_opt(0).unwrap()),
|
||||
Some(zone) => moment_in_zone(secs, as_text(zone,"zone")?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_unix(dt: &Value) -> Result<Value, String> {
|
||||
@@ -241,20 +245,56 @@ pub fn add(
|
||||
let hours = optional_i64(hours, "hours")?;
|
||||
let minutes = optional_i64(minutes, "minutes")?;
|
||||
let seconds = optional_i64(seconds, "seconds")?;
|
||||
let delta = Duration::days(days)
|
||||
+ Duration::hours(hours)
|
||||
+ Duration::minutes(minutes)
|
||||
+ Duration::seconds(seconds);
|
||||
let new_secs = secs
|
||||
.checked_add(delta.num_seconds())
|
||||
.ok_or_else(|| "datetime.add overflow".to_string())?;
|
||||
moment(new_secs, zone)
|
||||
let delta = days.checked_mul(86400).and_then(|n|hours.checked_mul(3600).and_then(|h|n.checked_add(h)))
|
||||
.and_then(|n|minutes.checked_mul(60).and_then(|m|n.checked_add(m))).and_then(|n|n.checked_add(seconds))
|
||||
.ok_or("datetime.add overflow")?;
|
||||
let new_secs = secs.checked_add(delta).ok_or("datetime.add overflow")?;
|
||||
if let Some(zone) = named_zone(dt) { moment_in_zone(new_secs,zone) } else { moment(new_secs,zone) }
|
||||
}
|
||||
|
||||
pub fn in_zone(dt: &Value, zone: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
let off = parse_zone(as_text(zone, "zone")?)?;
|
||||
moment(secs, off)
|
||||
moment_in_zone(secs, as_text(zone,"zone")?)
|
||||
}
|
||||
|
||||
fn named_zone(dt:&Value)->Option<&str>{
|
||||
let Value::Map(fields)=dt else{return None};
|
||||
fields.iter().find_map(|(k,v)|if k=="timezone"{if let Value::Text(zone)=v{Some(zone.as_str())}else{None}}else{None})
|
||||
}
|
||||
fn moment_in_zone(unix:i64,zone:&str)->Result<Value,String>{
|
||||
if let Ok(tz)=zone.parse::<chrono_tz::Tz>(){
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?;
|
||||
let mut value=moment(unix,local.offset().fix())?;
|
||||
if let Value::Map(fields)=&mut value{fields.push(("timezone".into(),Value::Text(zone.into())));}
|
||||
Ok(value)
|
||||
}else{moment(unix,parse_zone(zone)?)}
|
||||
}
|
||||
fn choose_local(tz:chrono_tz::Tz,local:NaiveDateTime,ambiguity:&str)->Result<i64,String>{
|
||||
if !matches!(ambiguity,"reject"|"earliest"|"latest"){return Err("ambiguity must be reject/earliest/latest".into())}
|
||||
match tz.from_local_datetime(&local){
|
||||
LocalResult::Single(dt)=>Ok(dt.timestamp()),
|
||||
LocalResult::None=>Err("nonexistent_time: local time is in a DST gap".into()),
|
||||
LocalResult::Ambiguous(a,b)=>match ambiguity{
|
||||
"earliest"=>Ok(a.timestamp().min(b.timestamp())),
|
||||
"latest"=>Ok(a.timestamp().max(b.timestamp())),
|
||||
_=>Err("ambiguous_time: DST fold; select earliest or latest".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn local(text:&Value,zone:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let source=as_text(text,"text")?.replace('T'," ");
|
||||
let local=NaiveDateTime::parse_from_str(&source,"%Y-%m-%d %H:%M:%S").map_err(|e|format!("datetime.parse_local: {e}"))?;
|
||||
let zone=as_text(zone,"zone")?;let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
moment_in_zone(choose_local(tz,local,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
pub(super) fn calendar_add(dt:&Value,days:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let (unix,_)=unix_of_value(dt)?;let days=as_i64(days,"days")?;
|
||||
let Some(zone)=named_zone(dt) else{return add(dt,Some(&Value::Int(days)),None,None,None)};
|
||||
let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.naive_local();
|
||||
let duration=Duration::try_days(days).ok_or("calendar day overflow")?;
|
||||
let next=local.checked_add_signed(duration).ok_or("calendar date overflow")?;
|
||||
moment_in_zone(choose_local(tz,next,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -222,6 +222,74 @@ pub enum HostFn {
|
||||
Access = 212,
|
||||
OracleJournal = 213,
|
||||
OracleReplayCheck = 214,
|
||||
ListRange = 215,
|
||||
ListEnumerate = 216,
|
||||
ListPluck = 217,
|
||||
ListProject = 218,
|
||||
ListWhere = 219,
|
||||
ListGroupBy = 220,
|
||||
ListUniqueBy = 221,
|
||||
ListAggregate = 222,
|
||||
ListSortKeys = 223,
|
||||
ListRename = 224,
|
||||
TableFromColumns = 225,
|
||||
TableToColumns = 226,
|
||||
ListJoin = 227,
|
||||
TableCast = 228,
|
||||
FsTryReadText = 229,
|
||||
FsTryWriteText = 230,
|
||||
TryJsonParse = 231,
|
||||
TryCsvParse = 232,
|
||||
BytesFromText = 233,
|
||||
BytesFromBase64 = 234,
|
||||
BytesToText = 235,
|
||||
BytesToBase64 = 236,
|
||||
BytesLen = 237,
|
||||
BytesSlice = 238,
|
||||
FsReadBytes = 239,
|
||||
FsWriteBytes = 240,
|
||||
FsReadChunk = 241,
|
||||
FsAppendBytes = 242,
|
||||
FsAtomicWrite = 243,
|
||||
FsWriteChanged = 244,
|
||||
FsWriteChecked = 245,
|
||||
FsReadLines = 246,
|
||||
FsWriteLines = 247,
|
||||
FsRemoveFile = 248,
|
||||
FsRemoveEmptyDir = 249,
|
||||
FsTempDir = 250,
|
||||
FsFileHash = 251,
|
||||
FsFind = 252,
|
||||
FsCopyTree = 253,
|
||||
FsSyncTree = 254,
|
||||
FsRenameMany = 255,
|
||||
PathRelative = 256,
|
||||
PathWithExtension = 257,
|
||||
DocumentSections = 258,
|
||||
DocumentSection = 259,
|
||||
DocumentReplaceSection = 260,
|
||||
DocumentTables = 261,
|
||||
DocumentReplaceTable = 262,
|
||||
DocumentLinks = 263,
|
||||
DocumentCodeBlocks = 264,
|
||||
HttpRequestResult = 265,
|
||||
HttpDownload = 266,
|
||||
TomlStringify = 267,
|
||||
TomlTryParse = 268,
|
||||
DatetimeLocal = 269,
|
||||
DatetimeCalendarAdd = 270,
|
||||
SubtaskWaitTimeout = 271,
|
||||
SubtaskCancelAll = 272,
|
||||
SubtaskRunMany = 273,
|
||||
HttpGetResult = 274,
|
||||
ZipPack = 275,
|
||||
ZipUnpack = 276,
|
||||
TableTryCast = 277,
|
||||
TableValidate = 278,
|
||||
ListUnion = 279,
|
||||
ListIntersection = 280,
|
||||
ListDifference = 281,
|
||||
TableSummarize = 282,
|
||||
}
|
||||
|
||||
/// Single source of truth for every host function. `<TAB>` slimming
|
||||
@@ -442,6 +510,74 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[
|
||||
HostFnDef { id: 212, f: HostFn::Access, name: "host_access", required: &["value", "key"], optional: &[] },
|
||||
HostFnDef { id: 213, f: HostFn::OracleJournal, name: "host_oracle_journal", required: &[], optional: &[] },
|
||||
HostFnDef { id: 214, f: HostFn::OracleReplayCheck, name: "host_oracle_replay_check", required: &["expected", "observed"], optional: &[] },
|
||||
HostFnDef { id: 215, f: HostFn::ListRange, name: "host_table_range", required: &["start", "end"], optional: &["step"] },
|
||||
HostFnDef { id: 216, f: HostFn::ListEnumerate, name: "host_table_enumerate", required: &["list"], optional: &["start"] },
|
||||
HostFnDef { id: 217, f: HostFn::ListPluck, name: "host_table_pluck", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 218, f: HostFn::ListProject, name: "host_table_project", required: &["list", "keys"], optional: &[] },
|
||||
HostFnDef { id: 219, f: HostFn::ListWhere, name: "host_table_where", required: &["list", "key", "value"], optional: &["op"] },
|
||||
HostFnDef { id: 220, f: HostFn::ListGroupBy, name: "host_table_group_by", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 221, f: HostFn::ListUniqueBy, name: "host_table_unique_by", required: &["list", "key"], optional: &[] },
|
||||
HostFnDef { id: 222, f: HostFn::ListAggregate, name: "host_table_aggregate", required: &["list"], optional: &["key", "op"] },
|
||||
HostFnDef { id: 223, f: HostFn::ListSortKeys, name: "host_table_sort_keys", required: &["list", "keys"], optional: &["descending"] },
|
||||
HostFnDef { id: 224, f: HostFn::ListRename, name: "host_table_rename", required: &["list", "fields"], optional: &[] },
|
||||
HostFnDef { id: 225, f: HostFn::TableFromColumns, name: "host_table_from_columns", required: &["columns"], optional: &[] },
|
||||
HostFnDef { id: 226, f: HostFn::TableToColumns, name: "host_table_to_columns", required: &["rows"], optional: &[] },
|
||||
HostFnDef { id: 227, f: HostFn::ListJoin, name: "host_table_join", required: &["a", "b", "key", "right_key"], optional: &["mode"] },
|
||||
HostFnDef { id: 228, f: HostFn::TableCast, name: "host_table_cast", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 229, f: HostFn::FsTryReadText, name: "host_fs_try_read_text", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 230, f: HostFn::FsTryWriteText, name: "host_fs_try_write_text", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 231, f: HostFn::TryJsonParse, name: "host_try_json_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 232, f: HostFn::TryCsvParse, name: "host_try_csv_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 233, f: HostFn::BytesFromText, name: "host_bytes_from_text", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 234, f: HostFn::BytesFromBase64, name: "host_bytes_from_base64", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 235, f: HostFn::BytesToText, name: "host_bytes_to_text", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 236, f: HostFn::BytesToBase64, name: "host_bytes_to_base64", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 237, f: HostFn::BytesLen, name: "host_bytes_len", required: &["data"], optional: &[] },
|
||||
HostFnDef { id: 238, f: HostFn::BytesSlice, name: "host_bytes_slice", required: &["data", "start", "end"], optional: &[] },
|
||||
HostFnDef { id: 239, f: HostFn::FsReadBytes, name: "host_fs_read_bytes", required: &["path"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 240, f: HostFn::FsWriteBytes, name: "host_fs_write_bytes", required: &["path", "data"], optional: &[] },
|
||||
HostFnDef { id: 241, f: HostFn::FsReadChunk, name: "host_fs_read_chunk", required: &["path"], optional: &["offset", "size"] },
|
||||
HostFnDef { id: 242, f: HostFn::FsAppendBytes, name: "host_fs_append_bytes", required: &["path", "data"], optional: &[] },
|
||||
HostFnDef { id: 243, f: HostFn::FsAtomicWrite, name: "host_fs_atomic_write", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 244, f: HostFn::FsWriteChanged, name: "host_fs_write_changed", required: &["path", "text"], optional: &[] },
|
||||
HostFnDef { id: 245, f: HostFn::FsWriteChecked, name: "host_fs_write_checked", required: &["path", "text", "expected_sha256"], optional: &[] },
|
||||
HostFnDef { id: 246, f: HostFn::FsReadLines, name: "host_fs_read_lines", required: &["path"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 247, f: HostFn::FsWriteLines, name: "host_fs_write_lines", required: &["path", "lines"], optional: &[] },
|
||||
HostFnDef { id: 248, f: HostFn::FsRemoveFile, name: "host_fs_remove_file", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 249, f: HostFn::FsRemoveEmptyDir, name: "host_fs_remove_empty_dir", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 250, f: HostFn::FsTempDir, name: "host_fs_temp_dir", required: &[], optional: &["prefix"] },
|
||||
HostFnDef { id: 251, f: HostFn::FsFileHash, name: "host_fs_file_hash", required: &["path"], optional: &[] },
|
||||
HostFnDef { id: 252, f: HostFn::FsFind, name: "host_fs_find", required: &["path"], optional: &["pattern", "exclude", "max_depth", "kind"] },
|
||||
HostFnDef { id: 253, f: HostFn::FsCopyTree, name: "host_fs_copy_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] },
|
||||
HostFnDef { id: 254, f: HostFn::FsSyncTree, name: "host_fs_sync_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] },
|
||||
HostFnDef { id: 255, f: HostFn::FsRenameMany, name: "host_fs_rename_many", required: &["moves"], optional: &["dry_run"] },
|
||||
HostFnDef { id: 256, f: HostFn::PathRelative, name: "host_path_relative", required: &["path", "base"], optional: &[] },
|
||||
HostFnDef { id: 257, f: HostFn::PathWithExtension, name: "host_path_with_extension", required: &["path", "extension"], optional: &[] },
|
||||
HostFnDef { id: 258, f: HostFn::DocumentSections, name: "host_document_sections", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 259, f: HostFn::DocumentSection, name: "host_document_section", required: &["text", "title"], optional: &[] },
|
||||
HostFnDef { id: 260, f: HostFn::DocumentReplaceSection, name: "host_document_replace_section", required: &["text", "title", "body"], optional: &["expected_sha256"] },
|
||||
HostFnDef { id: 261, f: HostFn::DocumentTables, name: "host_document_tables", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 262, f: HostFn::DocumentReplaceTable, name: "host_document_replace_table", required: &["text", "index", "headers", "rows"], optional: &["expected_sha256"] },
|
||||
HostFnDef { id: 263, f: HostFn::DocumentLinks, name: "host_document_links", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 264, f: HostFn::DocumentCodeBlocks, name: "host_document_code_blocks", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 265, f: HostFn::HttpRequestResult, name: "host_http_request_result", required: &["method", "url"], optional: &["body", "headers", "timeout_ms", "max_bytes", "response"] },
|
||||
HostFnDef { id: 266, f: HostFn::HttpDownload, name: "host_http_download", required: &["url", "path"], optional: &["headers", "timeout_ms", "max_bytes"] },
|
||||
HostFnDef { id: 267, f: HostFn::TomlStringify, name: "host_toml_stringify", required: &["value"], optional: &[] },
|
||||
HostFnDef { id: 268, f: HostFn::TomlTryParse, name: "host_toml_try_parse", required: &["text"], optional: &[] },
|
||||
HostFnDef { id: 269, f: HostFn::DatetimeLocal, name: "host_datetime_local", required: &["text", "zone"], optional: &["ambiguity"] },
|
||||
HostFnDef { id: 270, f: HostFn::DatetimeCalendarAdd, name: "host_datetime_calendar_add", required: &["dt", "days"], optional: &["ambiguity"] },
|
||||
HostFnDef { id: 271, f: HostFn::SubtaskWaitTimeout, name: "host_subtask_wait_timeout", required: &["id"], optional: &["timeout_ms", "cancel"] },
|
||||
HostFnDef { id: 272, f: HostFn::SubtaskCancelAll, name: "host_subtask_cancel_all", required: &[], optional: &[] },
|
||||
HostFnDef { id: 273, f: HostFn::SubtaskRunMany, name: "host_subtask_run_many", required: &["tasks"], optional: &["limit", "timeout_ms"] },
|
||||
HostFnDef { id: 274, f: HostFn::HttpGetResult, name: "host_http_get_result", required: &["url"], optional: &["headers", "timeout_ms", "max_bytes", "response"] },
|
||||
HostFnDef { id: 275, f: HostFn::ZipPack, name: "host_zip_pack", required: &["src", "dest"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 276, f: HostFn::ZipUnpack, name: "host_zip_unpack", required: &["src", "dest"], optional: &["max_bytes"] },
|
||||
HostFnDef { id: 277, f: HostFn::TableTryCast, name: "host_table_try_cast", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 278, f: HostFn::TableValidate, name: "host_table_validate", required: &["rows", "schema"], optional: &[] },
|
||||
HostFnDef { id: 279, f: HostFn::ListUnion, name: "host_table_union", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] },
|
||||
HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] },
|
||||
];
|
||||
|
||||
|
||||
@@ -452,6 +588,74 @@ impl HostFn {
|
||||
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"host_table_summarize" => Self::TableSummarize,
|
||||
"host_table_difference" => Self::ListDifference,
|
||||
"host_table_intersection" => Self::ListIntersection,
|
||||
"host_table_union" => Self::ListUnion,
|
||||
"host_table_validate" => Self::TableValidate,
|
||||
"host_table_try_cast" => Self::TableTryCast,
|
||||
"host_zip_unpack" => Self::ZipUnpack,
|
||||
"host_zip_pack" => Self::ZipPack,
|
||||
"host_http_get_result" => Self::HttpGetResult,
|
||||
"host_subtask_run_many" => Self::SubtaskRunMany,
|
||||
"host_subtask_cancel_all" => Self::SubtaskCancelAll,
|
||||
"host_subtask_wait_timeout" => Self::SubtaskWaitTimeout,
|
||||
"host_datetime_calendar_add" => Self::DatetimeCalendarAdd,
|
||||
"host_datetime_local" => Self::DatetimeLocal,
|
||||
"host_toml_try_parse" => Self::TomlTryParse,
|
||||
"host_toml_stringify" => Self::TomlStringify,
|
||||
"host_http_download" => Self::HttpDownload,
|
||||
"host_http_request_result" => Self::HttpRequestResult,
|
||||
"host_document_code_blocks" => Self::DocumentCodeBlocks,
|
||||
"host_document_links" => Self::DocumentLinks,
|
||||
"host_document_replace_table" => Self::DocumentReplaceTable,
|
||||
"host_document_tables" => Self::DocumentTables,
|
||||
"host_document_replace_section" => Self::DocumentReplaceSection,
|
||||
"host_document_section" => Self::DocumentSection,
|
||||
"host_document_sections" => Self::DocumentSections,
|
||||
"host_path_with_extension" => Self::PathWithExtension,
|
||||
"host_path_relative" => Self::PathRelative,
|
||||
"host_fs_rename_many" => Self::FsRenameMany,
|
||||
"host_fs_sync_tree" => Self::FsSyncTree,
|
||||
"host_fs_copy_tree" => Self::FsCopyTree,
|
||||
"host_fs_find" => Self::FsFind,
|
||||
"host_fs_file_hash" => Self::FsFileHash,
|
||||
"host_fs_temp_dir" => Self::FsTempDir,
|
||||
"host_fs_remove_empty_dir" => Self::FsRemoveEmptyDir,
|
||||
"host_fs_remove_file" => Self::FsRemoveFile,
|
||||
"host_fs_write_lines" => Self::FsWriteLines,
|
||||
"host_fs_read_lines" => Self::FsReadLines,
|
||||
"host_fs_write_checked" => Self::FsWriteChecked,
|
||||
"host_fs_write_changed" => Self::FsWriteChanged,
|
||||
"host_fs_atomic_write" => Self::FsAtomicWrite,
|
||||
"host_fs_append_bytes" => Self::FsAppendBytes,
|
||||
"host_fs_read_chunk" => Self::FsReadChunk,
|
||||
"host_fs_write_bytes" => Self::FsWriteBytes,
|
||||
"host_fs_read_bytes" => Self::FsReadBytes,
|
||||
"host_bytes_slice" => Self::BytesSlice,
|
||||
"host_bytes_len" => Self::BytesLen,
|
||||
"host_bytes_to_base64" => Self::BytesToBase64,
|
||||
"host_bytes_to_text" => Self::BytesToText,
|
||||
"host_bytes_from_base64" => Self::BytesFromBase64,
|
||||
"host_bytes_from_text" => Self::BytesFromText,
|
||||
"host_try_csv_parse" => Self::TryCsvParse,
|
||||
"host_try_json_parse" => Self::TryJsonParse,
|
||||
"host_fs_try_write_text" => Self::FsTryWriteText,
|
||||
"host_fs_try_read_text" => Self::FsTryReadText,
|
||||
"host_table_cast" => Self::TableCast,
|
||||
"host_table_join" => Self::ListJoin,
|
||||
"host_table_to_columns" => Self::TableToColumns,
|
||||
"host_table_from_columns" => Self::TableFromColumns,
|
||||
"host_table_rename" => Self::ListRename,
|
||||
"host_table_sort_keys" => Self::ListSortKeys,
|
||||
"host_table_aggregate" => Self::ListAggregate,
|
||||
"host_table_unique_by" => Self::ListUniqueBy,
|
||||
"host_table_group_by" => Self::ListGroupBy,
|
||||
"host_table_where" => Self::ListWhere,
|
||||
"host_table_project" => Self::ListProject,
|
||||
"host_table_pluck" => Self::ListPluck,
|
||||
"host_table_enumerate" => Self::ListEnumerate,
|
||||
"host_table_range" => Self::ListRange,
|
||||
"host_read_text" => Self::ReadText,
|
||||
"host_write_text" => Self::WriteText,
|
||||
"host_append_text" => Self::AppendText,
|
||||
@@ -664,6 +868,281 @@ impl HostFn {
|
||||
})
|
||||
}
|
||||
|
||||
/// Effects belong to resolved host identities, never import spellings.
|
||||
/// Exhaustive match forces every new primitive to declare its effects.
|
||||
pub fn effects(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::TableSummarize => &["pure"],
|
||||
Self::DotenvLoad => &["fs.read", "environment.write"],
|
||||
Self::ForeignLoadConfig => &["fs.read"],
|
||||
Self::ExtNativePath => &["plugin.call"],
|
||||
Self::ListDifference => &["pure"],
|
||||
Self::ListIntersection => &["pure"],
|
||||
Self::ListUnion => &["pure"],
|
||||
Self::TableValidate => &["pure"],
|
||||
Self::TableTryCast => &["pure"],
|
||||
Self::ZipUnpack => &["fs.write"],
|
||||
Self::ZipPack => &["fs.write"],
|
||||
Self::HttpGetResult => &["network.read"],
|
||||
Self::SubtaskRunMany => &["process.exec"],
|
||||
Self::SubtaskCancelAll => &["process.exec"],
|
||||
Self::SubtaskWaitTimeout => &["process.exec"],
|
||||
Self::DatetimeCalendarAdd => &["pure"],
|
||||
Self::DatetimeLocal => &["pure"],
|
||||
Self::TomlTryParse => &["pure"],
|
||||
Self::TomlStringify => &["pure"],
|
||||
Self::HttpDownload => &["network.read", "fs.write"],
|
||||
Self::HttpRequestResult => &["network.write"],
|
||||
Self::DocumentCodeBlocks => &["pure"],
|
||||
Self::DocumentLinks => &["pure"],
|
||||
Self::DocumentReplaceTable => &["pure"],
|
||||
Self::DocumentTables => &["pure"],
|
||||
Self::DocumentReplaceSection => &["pure"],
|
||||
Self::DocumentSection => &["pure"],
|
||||
Self::DocumentSections => &["pure"],
|
||||
Self::PathWithExtension => &["pure"],
|
||||
Self::PathRelative => &["pure"],
|
||||
Self::FsRenameMany => &["fs.write"],
|
||||
Self::FsSyncTree => &["fs.write"],
|
||||
Self::FsCopyTree => &["fs.write"],
|
||||
Self::FsFind => &["fs.read"],
|
||||
Self::FsFileHash => &["fs.read"],
|
||||
Self::FsTempDir => &["fs.write"],
|
||||
Self::FsRemoveEmptyDir => &["fs.write"],
|
||||
Self::FsRemoveFile => &["fs.write"],
|
||||
Self::FsWriteLines => &["fs.write"],
|
||||
Self::FsReadLines => &["fs.read"],
|
||||
Self::FsWriteChecked => &["fs.write"],
|
||||
Self::FsWriteChanged => &["fs.write"],
|
||||
Self::FsAtomicWrite => &["fs.write"],
|
||||
Self::FsAppendBytes => &["fs.write"],
|
||||
Self::FsReadChunk => &["fs.read"],
|
||||
Self::FsWriteBytes => &["fs.write"],
|
||||
Self::FsReadBytes => &["fs.read"],
|
||||
Self::BytesSlice => &["pure"],
|
||||
Self::BytesLen => &["pure"],
|
||||
Self::BytesToBase64 => &["pure"],
|
||||
Self::BytesToText => &["pure"],
|
||||
Self::BytesFromBase64 => &["pure"],
|
||||
Self::BytesFromText => &["pure"],
|
||||
Self::TryCsvParse => &["pure"],
|
||||
Self::TryJsonParse => &["pure"],
|
||||
Self::FsTryWriteText => &["fs.write"],
|
||||
Self::FsTryReadText => &["fs.read"],
|
||||
Self::TableCast => &["pure"],
|
||||
Self::ListJoin => &["pure"],
|
||||
Self::TableToColumns => &["pure"],
|
||||
Self::TableFromColumns => &["pure"],
|
||||
Self::ListRename => &["pure"],
|
||||
Self::ListSortKeys => &["pure"],
|
||||
Self::ListAggregate => &["pure"],
|
||||
Self::ListUniqueBy => &["pure"],
|
||||
Self::ListGroupBy => &["pure"],
|
||||
Self::ListWhere => &["pure"],
|
||||
Self::ListProject => &["pure"],
|
||||
Self::ListPluck => &["pure"],
|
||||
Self::ListEnumerate => &["pure"],
|
||||
Self::ListRange => &["pure"],
|
||||
Self::ReadText
|
||||
| Self::Exists
|
||||
| Self::ListDir
|
||||
| Self::FsStat
|
||||
| Self::FsWalk
|
||||
| Self::WritebackGet
|
||||
| Self::WritebackList
|
||||
| Self::WritebackScanPath => &["fs.read"],
|
||||
Self::WriteText
|
||||
| Self::AppendText
|
||||
| Self::MakeDir
|
||||
| Self::Remove
|
||||
| Self::FsCopyFile
|
||||
| Self::FsMove
|
||||
| Self::FsMakeTemp
|
||||
| Self::FsMakeDirs
|
||||
| Self::FsRemoveTree
|
||||
| Self::TextPatch
|
||||
| Self::ApplyPatchBlocks
|
||||
| Self::WritebackRecord
|
||||
| Self::WritebackClear
|
||||
| Self::WritebackEnsure => &["fs.write"],
|
||||
Self::HttpGet => &["network.read"],
|
||||
Self::HttpRequest => &["network.write"],
|
||||
Self::HttpPost | Self::HttpPostSse => &["network.write"],
|
||||
Self::Exec
|
||||
| Self::SubtaskSpawn
|
||||
| Self::SubtaskPoll
|
||||
| Self::SubtaskJoin
|
||||
| Self::SubtaskKill
|
||||
| Self::SubtaskWaitAll
|
||||
| Self::ForeignRun
|
||||
| Self::ForeignRunLang
|
||||
| Self::ForeignInvoke
|
||||
| Self::ForeignProbe
|
||||
| Self::ForeignCall
|
||||
| Self::ForeignRunMany
|
||||
| Self::ForeignCallMany
|
||||
| Self::ForeignSessionOpen
|
||||
| Self::ForeignSessionEval
|
||||
| Self::ForeignSessionSet
|
||||
| Self::ForeignSessionGet
|
||||
| Self::ForeignSessionNames
|
||||
| Self::ForeignSessionClose
|
||||
| Self::ForeignSessionList
|
||||
| Self::ForeignSessionInterrupt => &["process.exec"],
|
||||
Self::PluginLoad | Self::PluginUnload => &["plugin.call"],
|
||||
Self::LogLine
|
||||
| Self::StreamPublish
|
||||
| Self::Plot
|
||||
| Self::PlotPoints
|
||||
| Self::PlotConic => &["output.write"],
|
||||
Self::NowUnix | Self::NowMs | Self::DatetimeNow => &["time.read"],
|
||||
Self::Random
|
||||
| Self::RandomInt
|
||||
| Self::SecretsTokenHex
|
||||
| Self::SecretsTokenUrlsafe
|
||||
| Self::UuidV4 => &["random.read"],
|
||||
Self::EnvGet => &["environment.read"],
|
||||
Self::EnvSet => &["environment.write"],
|
||||
Self::Exit | Self::SleepMs => &["process.control"],
|
||||
Self::FormatTime
|
||||
| Self::ParseTime
|
||||
| Self::Args
|
||||
| Self::Cwd
|
||||
| Self::JsonParse
|
||||
| Self::JsonStringify
|
||||
| Self::JsonGet
|
||||
| Self::JsonKeys
|
||||
| Self::UrlEncode
|
||||
| Self::Pi
|
||||
| Self::EConst
|
||||
| Self::Num
|
||||
| Self::MathAdd
|
||||
| Self::MathSub
|
||||
| Self::MathMul
|
||||
| Self::MathDiv
|
||||
| Self::MathPow
|
||||
| Self::MathNeg
|
||||
| Self::MathSin
|
||||
| Self::MathCos
|
||||
| Self::MathTan
|
||||
| Self::MathAsin
|
||||
| Self::MathAcos
|
||||
| Self::MathAtan
|
||||
| Self::MathSqrt
|
||||
| Self::MathAbs
|
||||
| Self::MathLn
|
||||
| Self::MathExp
|
||||
| Self::MathFloor
|
||||
| Self::MathCeil
|
||||
| Self::MathMin
|
||||
| Self::MathMax
|
||||
| Self::Seed
|
||||
| Self::Formula
|
||||
| Self::Simplify
|
||||
| Self::Expand
|
||||
| Self::Diff
|
||||
| Self::Subs
|
||||
| Self::Eval
|
||||
| Self::Solve
|
||||
| Self::ForeignSetCmd
|
||||
| Self::ForeignLangs
|
||||
| Self::JsonQuote
|
||||
| Self::PluginList
|
||||
| Self::MapSet
|
||||
| Self::ListAppend
|
||||
| Self::OuterCallLine
|
||||
| Self::OpenAiSseParse
|
||||
| Self::CollectionPut
|
||||
| Self::ListPrepend
|
||||
| Self::ListConcat
|
||||
| Self::ListInsert
|
||||
| Self::ListSetAt
|
||||
| Self::ListRemoveAt
|
||||
| Self::ListSlice
|
||||
| Self::ListContains
|
||||
| Self::ListIndexOf
|
||||
| Self::ListReverse
|
||||
| Self::ListFirst
|
||||
| Self::ListLast
|
||||
| Self::MapGet
|
||||
| Self::MapDelete
|
||||
| Self::MapHas
|
||||
| Self::MapKeys
|
||||
| Self::MapValues
|
||||
| Self::MapItems
|
||||
| Self::MapMerge
|
||||
| Self::MapSize
|
||||
| Self::CollectionClear
|
||||
| Self::CookieParse
|
||||
| Self::MultipartParse
|
||||
| Self::MarkdownParse
|
||||
| Self::ReIsMatch
|
||||
| Self::ReFind
|
||||
| Self::ReFindAll
|
||||
| Self::ReReplace
|
||||
| Self::ReSplit
|
||||
| Self::EncodingBase64Encode
|
||||
| Self::EncodingBase64Decode
|
||||
| Self::EncodingHexEncode
|
||||
| Self::EncodingHexDecode
|
||||
| Self::PathJoin
|
||||
| Self::PathSplit
|
||||
| Self::PathFileName
|
||||
| Self::PathParent
|
||||
| Self::PathExtension
|
||||
| Self::PathNormalize
|
||||
| Self::PathIsAbsolute
|
||||
| Self::HashSha256
|
||||
| Self::HashSha1
|
||||
| Self::HashMd5
|
||||
| Self::HashHmacSha256
|
||||
| Self::TextContains
|
||||
| Self::TextStartsWith
|
||||
| Self::TextEndsWith
|
||||
| Self::TextReplace
|
||||
| Self::TextToUpper
|
||||
| Self::TextToLower
|
||||
| Self::TextRepeat
|
||||
| Self::TextPad
|
||||
| Self::CsvParse
|
||||
| Self::CsvStringify
|
||||
| Self::ListSort
|
||||
| Self::ListSortBy
|
||||
| Self::ListUnique
|
||||
| Self::ListChunk
|
||||
| Self::ListZip
|
||||
| Self::ListFlatten
|
||||
| Self::CliParse
|
||||
| Self::LogSetLevel
|
||||
| Self::DatetimeFromUnix
|
||||
| Self::DatetimeToUnix
|
||||
| Self::DatetimeParse
|
||||
| Self::DatetimeFormat
|
||||
| Self::DatetimeAdd
|
||||
| Self::DatetimeInZone
|
||||
| Self::UrlParse
|
||||
| Self::UrlQueryParse
|
||||
| Self::UrlQueryStringify
|
||||
| Self::TomlParse
|
||||
| Self::HtmlEscape
|
||||
| Self::HtmlUnescape
|
||||
| Self::EncodingBase32Encode
|
||||
| Self::EncodingBase32Decode
|
||||
| Self::StatsMean
|
||||
| Self::StatsMedian
|
||||
| Self::StatsStdev
|
||||
| Self::Meta
|
||||
| Self::MetaGet
|
||||
| Self::ModuleSource
|
||||
| Self::ArtifactKind
|
||||
| Self::ForeignRegister
|
||||
| Self::ForeignUnset
|
||||
| Self::Access
|
||||
| Self::OracleJournal
|
||||
| Self::OracleReplayCheck => &["pure"],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_u16(self) -> u16 {
|
||||
self as u16
|
||||
}
|
||||
@@ -705,6 +1184,74 @@ pub fn call_host(
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match fn_id {
|
||||
HostFn::TableSummarize => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListDifference => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListIntersection => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListUnion => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableValidate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableTryCast => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ZipUnpack => super::archive::call(ctx, fn_id, bound),
|
||||
HostFn::ZipPack => super::archive::call(ctx, fn_id, bound),
|
||||
HostFn::HttpGetResult => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskRunMany => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskCancelAll => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::SubtaskWaitTimeout => super::task_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DatetimeCalendarAdd => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DatetimeLocal => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TomlTryParse => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TomlStringify => super::data_ops::call(ctx, fn_id, bound),
|
||||
HostFn::HttpDownload => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::HttpRequestResult => super::net_ops::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentCodeBlocks => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentTables => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentSection => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::DocumentSections => super::document::call(ctx, fn_id, bound),
|
||||
HostFn::PathWithExtension => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::PathRelative => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRenameMany => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsSyncTree => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsCopyTree => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsFind => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsFileHash => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTempDir => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRemoveEmptyDir => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsRemoveFile => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteLines => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadLines => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteChecked => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteChanged => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsAtomicWrite => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsAppendBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadChunk => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsWriteBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsReadBytes => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesSlice => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesLen => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesToBase64 => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesToText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesFromBase64 => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::BytesFromText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TryCsvParse => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TryJsonParse => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTryWriteText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::FsTryReadText => super::fs_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableCast => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListJoin => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableToColumns => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::TableFromColumns => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListRename => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListSortKeys => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListAggregate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListUniqueBy => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListGroupBy => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListWhere => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListProject => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListPluck => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListEnumerate => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::ListRange => super::collection_ops::call(ctx, fn_id, bound),
|
||||
HostFn::Access => {
|
||||
let base = require(bound, "value")?;
|
||||
let key = match require(bound, "key")? {
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Inert Markdown structure using the same pulldown-cmark parser as rendering.
|
||||
//! Byte ranges always refer to the original UTF-8 source; nothing is executed.
|
||||
use super::{as_text, result};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn map(values: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(values.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
fn string(v: impl Into<String>) -> Value {
|
||||
Value::Text(v.into())
|
||||
}
|
||||
fn num(v: usize) -> Value {
|
||||
Value::Int(v as i64)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Section {
|
||||
title: String,
|
||||
level: usize,
|
||||
start: usize,
|
||||
body: usize,
|
||||
end: usize,
|
||||
}
|
||||
fn sections(text: &str) -> Vec<Section> {
|
||||
let mut out: Vec<Section> = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Heading { level, .. }) => {
|
||||
let n = level as usize;
|
||||
for section in &mut out {
|
||||
if section.end == text.len() && section.level >= n {
|
||||
section.end = range.start
|
||||
}
|
||||
}
|
||||
out.push(Section {
|
||||
title: String::new(),
|
||||
level: n,
|
||||
start: range.start,
|
||||
body: range.end,
|
||||
end: text.len(),
|
||||
});
|
||||
active = Some(out.len() - 1);
|
||||
}
|
||||
Event::End(TagEnd::Heading(_)) => {
|
||||
if let Some(i) = active.take() {
|
||||
out[i].body = range.end
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push(' ')
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn unique_section<'a>(sections: &'a [Section], title: &str) -> Result<&'a Section, String> {
|
||||
let hits: Vec<_> = sections.iter().filter(|s| s.title == title).collect();
|
||||
match hits.as_slice() {
|
||||
[s] => Ok(s),
|
||||
[] => Err(format!("section not found: {title}")),
|
||||
_ => Err(format!("ambiguous section: {title}")),
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Table {
|
||||
start: usize,
|
||||
end: usize,
|
||||
headers: Vec<String>,
|
||||
rows: Vec<Vec<String>>,
|
||||
}
|
||||
fn tables(text: &str) -> Vec<Table> {
|
||||
let mut out = Vec::new();
|
||||
let mut table: Option<Table> = None;
|
||||
let mut header = false;
|
||||
let mut row = Vec::new();
|
||||
let mut cell: Option<String> = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Table(_)) => {
|
||||
table = Some(Table {
|
||||
start: range.start,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
Event::Start(Tag::TableHead) => {
|
||||
header = true;
|
||||
row.clear()
|
||||
}
|
||||
Event::End(TagEnd::TableHead) => {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.headers = std::mem::take(&mut row)
|
||||
}
|
||||
header = false
|
||||
}
|
||||
Event::Start(Tag::TableRow) => row.clear(),
|
||||
Event::End(TagEnd::TableRow) => {
|
||||
if !header {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.rows.push(std::mem::take(&mut row));
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Start(Tag::TableCell) => cell = Some(String::new()),
|
||||
Event::End(TagEnd::TableCell) => {
|
||||
if let Some(c) = cell.take() {
|
||||
row.push(c)
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push('\n')
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Table) => {
|
||||
if let Some(mut t) = table.take() {
|
||||
t.end = range.end;
|
||||
out.push(t)
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn check_digest(b: &Args, text: &str) -> Result<(), String> {
|
||||
if let Some(Value::Text(expected)) = b.get("expected_sha256") {
|
||||
if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected {
|
||||
return Err("conflict: document content changed".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let source = text(b, "text")?;
|
||||
match id {
|
||||
HostFn::DocumentSections => Ok(Value::List(
|
||||
sections(source)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
map(vec![
|
||||
("title", string(s.title)),
|
||||
("level", num(s.level)),
|
||||
("start", num(s.start)),
|
||||
("body_start", num(s.body)),
|
||||
("end", num(s.end)),
|
||||
("text", string(&source[s.body..s.end])),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentSection => {
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
Ok(string(&source[section.body..section.end]))
|
||||
}
|
||||
HostFn::DocumentReplaceSection => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
let mut out = source[..section.body].to_string();
|
||||
let body = text(b, "body")?;
|
||||
if !out.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push('\n');
|
||||
out.push_str(body);
|
||||
if !body.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push_str(&source[section.end..]);
|
||||
Ok(string(out))
|
||||
})();
|
||||
Ok(result::capture("document.replace_section", change))
|
||||
}
|
||||
HostFn::DocumentTables => Ok(Value::List(
|
||||
tables(source)
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
map(vec![
|
||||
("start", num(t.start)),
|
||||
("end", num(t.end)),
|
||||
(
|
||||
"headers",
|
||||
Value::List(t.headers.into_iter().map(string).collect()),
|
||||
),
|
||||
(
|
||||
"rows",
|
||||
Value::List(
|
||||
t.rows
|
||||
.into_iter()
|
||||
.map(|r| Value::List(r.into_iter().map(string).collect()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentReplaceTable => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let index = match arg(b, "index")? {
|
||||
Value::Int(n) if *n >= 0 => *n as usize,
|
||||
_ => return Err("table index is zero-based nonnegative integer".into()),
|
||||
};
|
||||
let tables = tables(source);
|
||||
let table = tables.get(index).ok_or("table index out of range")?;
|
||||
fn cells(v: &Value) -> Result<Vec<String>, String> {
|
||||
let Value::List(xs) = v else {
|
||||
return Err("cells must be list of text".into());
|
||||
};
|
||||
xs.iter()
|
||||
.map(|v| {
|
||||
as_text(v, "cell").map(|s| {
|
||||
s.replace('\\', "\\\\")
|
||||
.replace('|', "\\|")
|
||||
.replace('\n', "<br>")
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let headers = cells(arg(b, "headers")?)?;
|
||||
if headers.is_empty() {
|
||||
return Err("table needs headers".into());
|
||||
}
|
||||
let Value::List(rows) = arg(b, "rows")? else {
|
||||
return Err("rows must be list".into());
|
||||
};
|
||||
let mut rendered = format!(
|
||||
"| {} |\n| {} |\n",
|
||||
headers.join(" | "),
|
||||
vec!["---"; headers.len()].join(" | ")
|
||||
);
|
||||
for row in rows {
|
||||
let row = cells(row)?;
|
||||
if row.len() != headers.len() {
|
||||
return Err("table row length differs from header".into());
|
||||
}
|
||||
rendered.push_str(&format!("| {} |\n", row.join(" | ")))
|
||||
}
|
||||
Ok(string(format!(
|
||||
"{}{}{}",
|
||||
&source[..table.start],
|
||||
rendered,
|
||||
&source[table.end..]
|
||||
)))
|
||||
})();
|
||||
Ok(result::capture("document.replace_table", change))
|
||||
}
|
||||
HostFn::DocumentLinks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active: Vec<(String, String, usize)> = Vec::new();
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||
active.push((dest_url.into_string(), String::new(), range.start))
|
||||
}
|
||||
Event::Text(s) | Event::Code(s) => {
|
||||
if let Some((_, text, _)) = active.last_mut() {
|
||||
text.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Link) => {
|
||||
if let Some((url, text, start)) = active.pop() {
|
||||
out.push(map(vec![
|
||||
("label", string(text)),
|
||||
("target", string(url)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::DocumentCodeBlocks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::CodeBlock(kind)) => {
|
||||
let lang = match kind {
|
||||
CodeBlockKind::Fenced(s) => s.into_string(),
|
||||
CodeBlockKind::Indented => String::new(),
|
||||
};
|
||||
active = Some((lang, String::new(), range.start));
|
||||
}
|
||||
Event::Text(s) => {
|
||||
if let Some((_, body, _)) = active.as_mut() {
|
||||
body.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::CodeBlock) => {
|
||||
if let Some((lang, body, start)) = active.take() {
|
||||
out.push(map(vec![
|
||||
("language", string(lang)),
|
||||
("text", string(body)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
_ => Err("not a document operation".into()),
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ fn from_hex(b: u8) -> Result<u8, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_base64(input: &[u8]) -> String {
|
||||
pub(super) fn encode_base64(input: &[u8]) -> String {
|
||||
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= input.len() {
|
||||
@@ -153,7 +153,7 @@ fn encode_base64(input: &[u8]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
pub(super) fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
let raw = input.as_bytes();
|
||||
if raw.len() % 4 != 0 {
|
||||
return Err("base64_decode: length must be multiple of 4".into());
|
||||
|
||||
+52
-10
@@ -62,6 +62,17 @@ pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Valu
|
||||
return Err("append_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut current = match read_text(ctx,path) {
|
||||
Ok(Value::Text(text)) => text,
|
||||
Err(_) if !matches!(exists(ctx,path),Ok(Value::Bool(true))) => String::new(),
|
||||
Err(e) => return Err(e),
|
||||
_ => return Err("append_text needs UTF-8".into()),
|
||||
};
|
||||
current.push_str(text_body(text)?);
|
||||
crate::host::sandbox_fs::cow_write_text(ctx,&p,¤t)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
@@ -99,6 +110,7 @@ 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());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dir directory state in CoW sandbox".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)
|
||||
@@ -109,6 +121,7 @@ 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());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dirs directory state in CoW sandbox".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)
|
||||
@@ -119,6 +132,9 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
return Err("remove denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() && p.is_dir() {
|
||||
return Err("unsupported: recursive directory removal in CoW sandbox".into());
|
||||
}
|
||||
if crate::host::sandbox_fs::cow_remove(ctx, &p)? {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
@@ -135,6 +151,7 @@ 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());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: remove_tree directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if !p.exists() {
|
||||
return Err(format!("remove_tree: not found: {}", p.display()));
|
||||
@@ -210,6 +227,18 @@ pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value,
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Err("conflict: copy source equals destination".into()); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
use std::io::Read;
|
||||
let bytes = match crate::host::sandbox_fs::cow_read_bytes(ctx,&from)? {
|
||||
Some(bytes) => bytes,
|
||||
None => { let mut bytes=Vec::new();fs::File::open(&from).map_err(|e|e.to_string())?
|
||||
.take(64*1024*1024+1).read_to_end(&mut bytes).map_err(|e|e.to_string())?;bytes },
|
||||
};
|
||||
if bytes.len()>64*1024*1024 { return Err("resource_limit: CoW copy exceeds 64 MiB".into()); }
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&to,&bytes)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?;
|
||||
}
|
||||
@@ -223,6 +252,12 @@ pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value,
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Ok(Value::None); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
copy_file(ctx,src,dest)?;
|
||||
crate::host::sandbox_fs::cow_remove(ctx,&from)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("move mkdir: {e}"))?;
|
||||
}
|
||||
@@ -248,6 +283,13 @@ pub fn make_temp(ctx: &HostContext, prefix: Option<&Value>) -> Result<Value, Str
|
||||
.unwrap_or(0);
|
||||
let name = format!("{pref}-{stamp}");
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
if matches!(exists(ctx,&Value::Text(name.clone()))?,Value::Bool(true)) {
|
||||
return Err("conflict: temporary path exists".into());
|
||||
}
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&p,&[])?;
|
||||
return Ok(Value::Text(name));
|
||||
}
|
||||
if let Some(parent) = p.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("make_temp mkdir: {e}"))?;
|
||||
}
|
||||
@@ -264,28 +306,28 @@ pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("text_patch denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let display = text_path(path)?;
|
||||
let find = text_body(find)?;
|
||||
let replace = text_body(replace)?;
|
||||
if find.is_empty() {
|
||||
return Err("text_patch: find must be non-empty".into());
|
||||
}
|
||||
let src = fs::read_to_string(&p).map_err(|e| format!("text_patch {}: {e}", p.display()))?;
|
||||
let Value::Text(src) = read_text(ctx,path)? else { return Err("text_patch needs text".into()); };
|
||||
let count = src.matches(find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"text_patch: find not found in {}",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"text_patch: find matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
let next = src.replacen(find, replace, 1);
|
||||
fs::write(&p, next).map_err(|e| format!("text_patch write {}: {e}", p.display()))?;
|
||||
write_text(ctx,path,&Value::Text(next))?;
|
||||
Ok(Value::Int(1))
|
||||
}
|
||||
|
||||
@@ -362,8 +404,8 @@ fn apply_patch_blocks_inner(
|
||||
if blocks.is_empty() {
|
||||
return Ok(Value::Int(0));
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let mut src = fs::read_to_string(&p).map_err(|e| format!("apply_patch_blocks {}: {e}", p.display()))?;
|
||||
let display = text_path(path)?;
|
||||
let Value::Text(mut src) = read_text(ctx,path)? else { return Err("apply_patch_blocks needs text".into()); };
|
||||
let mut applied = 0i64;
|
||||
for (find, replace) in blocks {
|
||||
if find.is_empty() {
|
||||
@@ -379,19 +421,19 @@ fn apply_patch_blocks_inner(
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND not found in {}",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
display
|
||||
));
|
||||
}
|
||||
src = src.replacen(&find, &replace, 1);
|
||||
applied += 1;
|
||||
}
|
||||
fs::write(&p, src).map_err(|e| format!("apply_patch_blocks write {}: {e}", p.display()))?;
|
||||
write_text(ctx,path,&Value::Text(src))?;
|
||||
Ok(Value::Int(applied))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,681 @@
|
||||
//! Bounded filesystem tasks. Public authors use lib/fs, lib/path and lib/bytes.
|
||||
use super::{as_text, encoding, fs as legacy, result, sandbox_fs};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
const MAX_READ: usize = 64 * 1024 * 1024;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn number(b: &Args, k: &str) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
fn flag(b: &Args, k: &str) -> bool {
|
||||
matches!(b.get(k), Some(Value::Bool(true)))
|
||||
}
|
||||
fn native(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.sandbox_session.is_some() {
|
||||
Err("operation unavailable in CoW sandbox; use write_text/remove_file".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn writable(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.allow_fs_write() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("filesystem write denied by host policy".into())
|
||||
}
|
||||
}
|
||||
fn path(ctx: &HostContext, b: &Args, k: &str) -> Result<PathBuf, String> {
|
||||
ctx.resolve_path(text(b, k)?)
|
||||
}
|
||||
fn ioerr(e: std::io::Error) -> String {
|
||||
let code = match e.kind() {
|
||||
std::io::ErrorKind::NotFound => "not_found",
|
||||
std::io::ErrorKind::PermissionDenied => "permission_denied",
|
||||
std::io::ErrorKind::AlreadyExists => "conflict",
|
||||
_ => "operation_failed",
|
||||
};
|
||||
format!("{code}: {e}")
|
||||
}
|
||||
fn limit(b: &Args, k: &str) -> Result<usize, String> {
|
||||
let n = number(b, k)?;
|
||||
if n == 0 || n > MAX_READ as u64 {
|
||||
return Err(format!("{k} must be 1..{MAX_READ}"));
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
pub(super) fn bytes_value(bytes: &[u8]) -> Value {
|
||||
Value::Map(vec![
|
||||
("_type".into(), Value::Text("bytes".into())),
|
||||
("base64".into(), Value::Text(encoding::encode_base64(bytes))),
|
||||
])
|
||||
}
|
||||
pub(super) fn bytes(v: &Value) -> Result<Vec<u8>, String> {
|
||||
let Value::Map(fields) = v else {
|
||||
return Err("expected bytes record from lib/bytes or fs.read_bytes".into());
|
||||
};
|
||||
if !fields
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_type" && v == &Value::Text("bytes".into()))
|
||||
{
|
||||
return Err("expected _type bytes".into());
|
||||
}
|
||||
let text = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == "base64")
|
||||
.ok_or("missing bytes.base64")?;
|
||||
encoding::decode_base64(as_text(&text.1, "base64")?)
|
||||
}
|
||||
fn read(ctx: &HostContext, p: &Path, max: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, p)? {
|
||||
if bytes.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
return Ok(bytes);
|
||||
}
|
||||
fs::File::open(p)
|
||||
.map_err(ioerr)?
|
||||
.take(max as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(ioerr)?;
|
||||
if out.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn atomic(ctx: &HostContext, p: &Path, body: &[u8]) -> Result<(), String> {
|
||||
writable(ctx)?;
|
||||
if sandbox_fs::cow_write_bytes(ctx, p, body)? {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = p.parent().ok_or("file needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
// create_new reserves the sibling name. Never truncate an existing temp file.
|
||||
let mut reserved = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = entropy
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-{name}.tmp"));
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
{
|
||||
Ok(file) => {
|
||||
reserved = Some((temp, file));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
let (temp, mut file) = reserved.ok_or("cannot reserve atomic write file")?;
|
||||
let result = (|| {
|
||||
file.write_all(body).map_err(ioerr)?;
|
||||
file.sync_all().map_err(ioerr)?;
|
||||
drop(file);
|
||||
fs::rename(&temp, p).map_err(ioerr)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let answer = match id {
|
||||
HostFn::FsTryReadText => {
|
||||
let answer = (|| {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, 8 * 1024 * 1024)?;
|
||||
String::from_utf8(data)
|
||||
.map(Value::Text)
|
||||
.map_err(|e| format!("invalid_encoding: {e}"))
|
||||
})();
|
||||
return Ok(result::capture("fs.read_text", answer));
|
||||
}
|
||||
HostFn::FsTryWriteText => {
|
||||
return Ok(result::capture(
|
||||
"fs.write_text",
|
||||
legacy::write_text(ctx, arg(b, "path")?, arg(b, "text")?),
|
||||
))
|
||||
}
|
||||
HostFn::TryJsonParse => {
|
||||
return Ok(result::capture(
|
||||
"json.parse",
|
||||
super::json::parse(arg(b, "text")?).map_err(|e| format!("invalid_json: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::TryCsvParse => {
|
||||
return Ok(result::capture(
|
||||
"csv.parse",
|
||||
super::csv::parse(arg(b, "text")?).map_err(|e| format!("invalid_csv: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::BytesFromText => bytes_value(text(b, "text")?.as_bytes()),
|
||||
HostFn::BytesFromBase64 => bytes_value(&encoding::decode_base64(text(b, "text")?)?),
|
||||
HostFn::BytesToText => Value::Text(
|
||||
String::from_utf8(bytes(arg(b, "data")?)?)
|
||||
.map_err(|e| format!("bytes are not UTF-8: {e}"))?,
|
||||
),
|
||||
HostFn::BytesToBase64 => Value::Text(encoding::encode_base64(&bytes(arg(b, "data")?)?)),
|
||||
HostFn::BytesLen => Value::Int(bytes(arg(b, "data")?)?.len() as i64),
|
||||
HostFn::BytesSlice => {
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
let start = usize::try_from(number(b, "start")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
let end = usize::try_from(number(b, "end")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
bytes_value(if start > end { &[] } else { &data[start..end] })
|
||||
}
|
||||
HostFn::FsReadBytes => {
|
||||
bytes_value(&read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?)
|
||||
}
|
||||
HostFn::FsWriteBytes => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
atomic(ctx, &p, &bytes(arg(b, "data")?)?)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsReadChunk => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let offset = number(b, "offset")?;
|
||||
let size = limit(b, "size")?;
|
||||
let mut data = vec![0u8; size];
|
||||
let (n, total) = if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
let start = usize::try_from(offset)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(bytes.len());
|
||||
let end = start.saturating_add(size).min(bytes.len());
|
||||
data[..end - start].copy_from_slice(&bytes[start..end]);
|
||||
(end - start, bytes.len() as u64)
|
||||
} else {
|
||||
let mut file = fs::File::open(&p).map_err(ioerr)?;
|
||||
let total = file.metadata().map_err(ioerr)?.len();
|
||||
file.seek(SeekFrom::Start(offset)).map_err(ioerr)?;
|
||||
let n = file.take(size as u64).read(&mut data).map_err(ioerr)?;
|
||||
(n, total)
|
||||
};
|
||||
data.truncate(n);
|
||||
let next = offset.checked_add(n as u64).ok_or("offset overflow")?;
|
||||
Value::Map(vec![
|
||||
("data".into(), bytes_value(&data)),
|
||||
("next_offset".into(), Value::Int(next as i64)),
|
||||
("eof".into(), Value::Bool(next >= total)),
|
||||
])
|
||||
}
|
||||
HostFn::FsAppendBytes => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut body = read(ctx, &p, MAX_READ).or_else(|e| {
|
||||
if matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(false))) {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})?;
|
||||
body.extend_from_slice(&data);
|
||||
sandbox_fs::cow_write_bytes(ctx, &p, &body)?;
|
||||
} else {
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&p)
|
||||
.map_err(ioerr)?;
|
||||
f.write_all(&data).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsAtomicWrite | HostFn::FsWriteChanged => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let body = text(b, "text")?.as_bytes();
|
||||
if id == HostFn::FsWriteChanged && read(ctx, &p, MAX_READ).ok().as_deref() == Some(body)
|
||||
{
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
atomic(ctx, &p, body)?;
|
||||
if id == HostFn::FsWriteChanged {
|
||||
Value::Bool(true)
|
||||
} else {
|
||||
Value::None
|
||||
}
|
||||
}
|
||||
HostFn::FsWriteChecked => {
|
||||
let change = (|| {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let expected = text(b, "expected_sha256")?;
|
||||
let current = read(ctx, &p, MAX_READ)?;
|
||||
let actual = format!("{:x}", Sha256::digest(¤t));
|
||||
if actual != expected {
|
||||
return Err("conflict: file content changed".into());
|
||||
}
|
||||
atomic(ctx, &p, text(b, "text")?.as_bytes()).map(|_| Value::None)
|
||||
})();
|
||||
return Ok(result::capture("fs.write_checked", change));
|
||||
}
|
||||
HostFn::FsReadLines => {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?;
|
||||
let text = String::from_utf8(data).map_err(|e| format!("file is not UTF-8: {e}"))?;
|
||||
Value::List(text.lines().map(|s| Value::Text(s.into())).collect())
|
||||
}
|
||||
HostFn::FsWriteLines => {
|
||||
let Value::List(lines) = arg(b, "lines")? else {
|
||||
return Err("lines must be list of text".into());
|
||||
};
|
||||
let lines = lines
|
||||
.iter()
|
||||
.map(|v| as_text(v, "line"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut body = lines.join("\n");
|
||||
if !lines.is_empty() {
|
||||
body.push('\n')
|
||||
};
|
||||
atomic(ctx, &path(ctx, b, "path")?, body.as_bytes())?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveFile => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
if p.is_dir() {
|
||||
return Err("remove_file refuses directory".into());
|
||||
}
|
||||
if !matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(true))) {
|
||||
return Err("not_found: remove_file target absent".into());
|
||||
}
|
||||
if !sandbox_fs::cow_remove(ctx, &p)? {
|
||||
fs::remove_file(p).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveEmptyDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
fs::remove_dir(path(ctx, b, "path")?).map_err(ioerr)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsTempDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let prefix = text(b, "prefix")?;
|
||||
if prefix.contains('/') || prefix.contains('\\') || prefix.contains("..") {
|
||||
return Err("temp prefix must be simple name".into());
|
||||
}
|
||||
let mut created = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = format!(
|
||||
"{prefix}-{}",
|
||||
entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>()
|
||||
);
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
match fs::create_dir(p) {
|
||||
Ok(()) => {
|
||||
created = Some(Value::Text(name));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
created.ok_or("unable to reserve temporary directory")?
|
||||
}
|
||||
HostFn::FsFileHash => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let mut hasher = Sha256::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
hasher.update(bytes)
|
||||
} else {
|
||||
let mut f = fs::File::open(p).map_err(ioerr)?;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = f.read(&mut buffer).map_err(ioerr)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..n]);
|
||||
}
|
||||
}
|
||||
Value::Text(format!("{:x}", hasher.finalize()))
|
||||
}
|
||||
HostFn::FsFind => {
|
||||
let root = path(ctx, b, "path")?;
|
||||
let pattern = glob(text(b, "pattern")?)?;
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let max_depth = number(b, "max_depth")? as usize;
|
||||
let kind = text(b, "kind")?;
|
||||
if !matches!(kind, "file" | "dir" | "all") {
|
||||
return Err("find kind must be file/dir/all".into());
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&root,
|
||||
Path::new(""),
|
||||
&pattern,
|
||||
&excluded,
|
||||
max_depth,
|
||||
kind,
|
||||
&mut files,
|
||||
)?;
|
||||
Value::List(files)
|
||||
}
|
||||
HostFn::FsCopyTree | HostFn::FsSyncTree => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let src = path(ctx, b, "src")?;
|
||||
let dest = path(ctx, b, "dest")?;
|
||||
if dest.starts_with(&src) || src.starts_with(&dest) {
|
||||
return Err("copy/sync trees must be disjoint".into());
|
||||
}
|
||||
if !src.is_dir() {
|
||||
return Err("src must be directory".into());
|
||||
}
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&src,
|
||||
Path::new(""),
|
||||
&glob("**")?,
|
||||
&excluded,
|
||||
256,
|
||||
"file",
|
||||
&mut files,
|
||||
)?;
|
||||
let mut jobs = Vec::new();
|
||||
for name in files {
|
||||
let name = as_text(&name, "name")?;
|
||||
let from = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let to = ctx.resolve_path(dest.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
if to.exists() {
|
||||
if id == HostFn::FsSyncTree && files_equal(&from, &to)? {
|
||||
continue;
|
||||
}
|
||||
if !flag(b, "overwrite") {
|
||||
return Err(format!("destination conflict: {}", to.display()));
|
||||
}
|
||||
}
|
||||
jobs.push((from, to, name.to_string()));
|
||||
}
|
||||
let dry = flag(b, "dry_run");
|
||||
let mut changed = Vec::new();
|
||||
for (from, to, name) in jobs {
|
||||
if !dry {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::copy(from, to).map_err(ioerr)?;
|
||||
}
|
||||
changed.push(Value::Text(name));
|
||||
}
|
||||
Value::List(changed)
|
||||
}
|
||||
HostFn::FsRenameMany => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let Value::List(rows) = arg(b, "moves")? else {
|
||||
return Err("moves must be record list".into());
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
let mut destinations = std::collections::HashSet::new();
|
||||
let mut sources = std::collections::HashSet::new();
|
||||
for row in rows {
|
||||
let Value::Map(fields) = row else {
|
||||
return Err("move needs src,dest".into());
|
||||
};
|
||||
let mut paths = Vec::new();
|
||||
for key in ["src", "dest"] {
|
||||
let value = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.ok_or("move needs src,dest")?;
|
||||
paths.push(ctx.resolve_path(as_text(&value.1, key)?)?);
|
||||
}
|
||||
if !paths[0].is_file() {
|
||||
return Err("rename_many source must be file".into());
|
||||
}
|
||||
if !sources.insert(paths[0].clone()) {
|
||||
return Err("conflict: repeated rename source".into());
|
||||
}
|
||||
if paths[1].exists() || !destinations.insert(paths[1].clone()) {
|
||||
return Err("rename_many destination conflict".into());
|
||||
}
|
||||
jobs.push((paths.remove(0), paths.remove(0)));
|
||||
}
|
||||
// Preflight all paths. Execution is ordered and deliberately not transactional.
|
||||
if !flag(b, "dry_run") {
|
||||
for (from, to) in &jobs {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::rename(from, to).map_err(ioerr)?;
|
||||
}
|
||||
}
|
||||
Value::Int(jobs.len() as i64)
|
||||
}
|
||||
HostFn::PathRelative => {
|
||||
let normalized = super::path::normalize(arg(b, "path")?)?;
|
||||
let normalized_base = super::path::normalize(arg(b, "base")?)?;
|
||||
let path = PathBuf::from(as_text(&normalized, "path")?);
|
||||
let base = PathBuf::from(as_text(&normalized_base, "base")?);
|
||||
if path.is_absolute() != base.is_absolute() {
|
||||
return Err("relative paths must share absolute/relative form".into());
|
||||
}
|
||||
let a: Vec<_> = path.components().collect();
|
||||
let b: Vec<_> = base.components().collect();
|
||||
if path.is_absolute() && a.first() != b.first() {
|
||||
return Err("relative paths have different roots".into());
|
||||
}
|
||||
let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
|
||||
let mut out = PathBuf::new();
|
||||
for _ in common..b.len() {
|
||||
out.push("..")
|
||||
}
|
||||
for c in &a[common..] {
|
||||
out.push(c.as_os_str())
|
||||
}
|
||||
Value::Text(if out.as_os_str().is_empty() {
|
||||
".".into()
|
||||
} else {
|
||||
out.to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
}
|
||||
HostFn::PathWithExtension => {
|
||||
let mut p = PathBuf::from(text(b, "path")?);
|
||||
let ext = text(b, "extension")?;
|
||||
if ext.contains('/') || ext.contains('\\') {
|
||||
return Err("extension cannot contain path separator".into());
|
||||
}
|
||||
p.set_extension(ext.trim_start_matches('.'));
|
||||
Value::Text(p.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
_ => return Err("not a filesystem task".into()),
|
||||
};
|
||||
Ok(answer)
|
||||
}
|
||||
fn patterns(v: &Value) -> Result<Vec<regex::Regex>, String> {
|
||||
if matches!(v, Value::None) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let Value::List(xs) = v else {
|
||||
return Err("exclude must be list of patterns".into());
|
||||
};
|
||||
xs.iter().map(|v| glob(as_text(v, "pattern")?)).collect()
|
||||
}
|
||||
fn glob(pattern: &str) -> Result<regex::Regex, String> {
|
||||
let mut out = String::from("^");
|
||||
let mut cs = pattern.chars().peekable();
|
||||
while let Some(c) = cs.next() {
|
||||
match c {
|
||||
'*' => {
|
||||
if cs.peek() == Some(&'*') {
|
||||
cs.next();
|
||||
if cs.peek() == Some(&'/') {
|
||||
cs.next();
|
||||
out.push_str("(?:.*/)?")
|
||||
} else {
|
||||
out.push_str(".*")
|
||||
}
|
||||
} else {
|
||||
out.push_str("[^/]*")
|
||||
}
|
||||
}
|
||||
'?' => out.push_str("[^/]"),
|
||||
_ => out.push_str(®ex::escape(&c.to_string())),
|
||||
}
|
||||
}
|
||||
out.push('$');
|
||||
regex::Regex::new(&out).map_err(|e| e.to_string())
|
||||
}
|
||||
fn find(
|
||||
ctx: &HostContext,
|
||||
root: &Path,
|
||||
rel: &Path,
|
||||
pattern: ®ex::Regex,
|
||||
exclude: &[regex::Regex],
|
||||
depth: usize,
|
||||
kind: &str,
|
||||
out: &mut Vec<Value>,
|
||||
) -> Result<(), String> {
|
||||
if depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let mut entries = fs::read_dir(root.join(rel))
|
||||
.map_err(ioerr)?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(ioerr)?;
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let child = rel.join(entry.file_name());
|
||||
let name = child.to_string_lossy().replace('\\', "/");
|
||||
let ty = entry.file_type().map_err(ioerr)?;
|
||||
if exclude
|
||||
.iter()
|
||||
.any(|r| r.is_match(&name) || r.is_match(&format!("{name}/")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// No symlink traversal. Reads returned by this finder still use resolve_path.
|
||||
if ty.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
ctx.resolve_path(entry.path().to_str().ok_or("non UTF-8 path")?)?;
|
||||
if pattern.is_match(&name)
|
||||
&& ((ty.is_file() && kind != "dir") || (ty.is_dir() && kind != "file"))
|
||||
{
|
||||
if out.len() >= 100_000 {
|
||||
return Err("find exceeds 100000 entries".into());
|
||||
}
|
||||
out.push(Value::Text(name))
|
||||
}
|
||||
if ty.is_dir() {
|
||||
find(ctx, root, &child, pattern, exclude, depth - 1, kind, out)?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn files_equal(a: &Path, b: &Path) -> Result<bool, String> {
|
||||
if fs::metadata(a).map_err(ioerr)?.len() != fs::metadata(b).map_err(ioerr)?.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut a = std::io::BufReader::new(fs::File::open(a).map_err(ioerr)?);
|
||||
let mut b = std::io::BufReader::new(fs::File::open(b).map_err(ioerr)?);
|
||||
use std::io::BufRead;
|
||||
loop {
|
||||
let left = a.fill_buf().map_err(ioerr)?;
|
||||
let right = b.fill_buf().map_err(ioerr)?;
|
||||
if left.is_empty() || right.is_empty() {
|
||||
return Ok(left.is_empty() && right.is_empty());
|
||||
}
|
||||
let n = left.len().min(right.len());
|
||||
if left[..n] != right[..n] {
|
||||
return Ok(false);
|
||||
}
|
||||
a.consume(n);
|
||||
b.consume(n);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod overlay_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn byte_append_copy_and_patch_stay_in_the_overlay_until_commit() {
|
||||
let root = std::env::temp_dir().join(format!("mq-byte-overlay-{}", std::process::id()));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::write(root.join("note.md"), "old text").unwrap();
|
||||
let mut ctx =
|
||||
HostContext::for_run(Some(&root.join("main.mq.md")), Default::default(), vec![]);
|
||||
let session = sandbox_fs::open(Some(root.to_str().unwrap()), &ctx).unwrap();
|
||||
let id = session["id"].as_str().unwrap().to_string();
|
||||
ctx.sandbox_session = Some(id.clone());
|
||||
legacy::text_patch(
|
||||
&ctx,
|
||||
&Value::Text("note.md".into()),
|
||||
&Value::Text("old".into()),
|
||||
&Value::Text("new".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("note.md")).unwrap(),
|
||||
"old text"
|
||||
);
|
||||
assert_eq!(
|
||||
legacy::read_text(&ctx, &Value::Text("note.md".into())).unwrap(),
|
||||
Value::Text("new text".into())
|
||||
);
|
||||
let mut args = Args::from([
|
||||
("path".into(), Value::Text("data.bin".into())),
|
||||
("data".into(), bytes_value(&[0, 255])),
|
||||
]);
|
||||
call(&mut ctx, HostFn::FsWriteBytes, &args).unwrap();
|
||||
args.insert("data".into(), bytes_value(&[128]));
|
||||
call(&mut ctx, HostFn::FsAppendBytes, &args).unwrap();
|
||||
legacy::copy_file(
|
||||
&ctx,
|
||||
&Value::Text("data.bin".into()),
|
||||
&Value::Text("copied.bin".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sandbox_fs::cow_read_bytes(&ctx, &root.join("copied.bin"))
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
[0, 255, 128]
|
||||
);
|
||||
assert!(!root.join("data.bin").exists());
|
||||
assert!(!root.join("copied.bin").exists());
|
||||
assert!(legacy::make_dirs(&ctx, &Value::Text("unsupported".into())).is_err());
|
||||
assert!(!root.join("unsupported").exists());
|
||||
sandbox_fs::discard(&id).unwrap();
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
+54
-13
@@ -276,21 +276,46 @@ impl HostContext {
|
||||
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()));
|
||||
let abs = if abs.is_absolute() { abs } else {
|
||||
std::env::current_dir().map_err(|e|e.to_string())?.join(abs)
|
||||
};
|
||||
let root = root.canonicalize().map_err(|e| format!("filesystem root: {e}"))?;
|
||||
// Normalize before checking, including destinations that do not exist yet.
|
||||
let mut lexical = PathBuf::new();
|
||||
for component in abs.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {},
|
||||
std::path::Component::ParentDir => { lexical.pop(); },
|
||||
component => lexical.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
if !lexical.is_absolute() {
|
||||
lexical = std::env::current_dir().map_err(|e| e.to_string())?.join(lexical);
|
||||
}
|
||||
if !lexical.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
// The nearest existing ancestor must also be inside root: a symlink
|
||||
// cannot authorize writes through a not-yet-existing descendant.
|
||||
let mut ancestor = lexical.as_path();
|
||||
loop {
|
||||
match ancestor.canonicalize() {
|
||||
Ok(real) => {
|
||||
if !real.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
if ancestor.symlink_metadata().is_ok() {
|
||||
return Err(format!("unresolvable symlink: {}", ancestor.display()));
|
||||
}
|
||||
ancestor = ancestor.parent().ok_or_else(|| "invalid file path".to_string())?;
|
||||
}
|
||||
Err(e) => return Err(format!("resolve path {}: {e}", abs.display())),
|
||||
}
|
||||
}
|
||||
return Ok(lexical);
|
||||
}
|
||||
Ok(abs)
|
||||
}
|
||||
@@ -320,3 +345,19 @@ pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> R
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod collection_ops;
|
||||
|
||||
mod result;
|
||||
|
||||
mod fs_ops;
|
||||
|
||||
mod document;
|
||||
|
||||
mod net_ops;
|
||||
|
||||
mod data_ops;
|
||||
|
||||
mod task_ops;
|
||||
|
||||
mod archive;
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Configurable bounded HTTP with one recoverable Result envelope.
|
||||
#[cfg(feature = "net-host")]
|
||||
use super::as_text;
|
||||
use super::result;
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
time::Duration,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = request(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("HTTP unavailable in this build".into())
|
||||
};
|
||||
Ok(result::capture(
|
||||
if id == HostFn::HttpDownload {
|
||||
"net.download"
|
||||
} else {
|
||||
"net.request"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn integer(b: &Args, k: &str, max: u64) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n > 0 && (*n as u64) <= max => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be 1..{max}")),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn request(ctx: &HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("network denied by host policy".into());
|
||||
}
|
||||
let url = as_text(arg(b, "url")?, "url")?;
|
||||
if !(url.starts_with("https://") || url.starts_with("http://")) {
|
||||
return Err("url must use http/https".into());
|
||||
}
|
||||
let timeout = Duration::from_millis(integer(b, "timeout_ms", 600000)?);
|
||||
let max = integer(b, "max_bytes", 1024 * 1024 * 1024)?;
|
||||
let method = if matches!(id, HostFn::HttpDownload | HostFn::HttpGetResult) {
|
||||
"GET"
|
||||
} else {
|
||||
as_text(arg(b, "method")?, "method")?
|
||||
};
|
||||
if !matches!(
|
||||
method,
|
||||
"GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"
|
||||
) {
|
||||
return Err("unsupported method".into());
|
||||
}
|
||||
// Reject invalid output settings and destinations before any HTTP exchange.
|
||||
let destination = if id == HostFn::HttpDownload {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("unsupported: stream download in CoW sandbox".into());
|
||||
}
|
||||
let path = ctx.resolve_path(as_text(arg(b, "path")?, "path")?)?;
|
||||
if path.is_dir() {
|
||||
return Err("invalid_argument: download destination is a directory".into());
|
||||
}
|
||||
Some(path)
|
||||
} else {
|
||||
if max > 64 * 1024 * 1024 {
|
||||
return Err(
|
||||
"resource_limit: in-memory response limit exceeds 64 MiB; use download".into(),
|
||||
);
|
||||
}
|
||||
if !matches!(as_text(arg(b, "response")?, "response")?, "text" | "bytes") {
|
||||
return Err("invalid_argument: response must be text or bytes".into());
|
||||
}
|
||||
None
|
||||
};
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(timeout)
|
||||
.timeout_connect(timeout)
|
||||
.timeout_read(timeout)
|
||||
.timeout_write(timeout)
|
||||
.build();
|
||||
let mut request = agent.request(method, url).set("User-Agent", "marqdo");
|
||||
if let Some(Value::Map(headers)) = b.get("headers") {
|
||||
for (k, v) in headers {
|
||||
request = request.set(k, as_text(v, "header value")?)
|
||||
}
|
||||
} else if !matches!(b.get("headers"), None | Some(Value::None)) {
|
||||
return Err("headers must be map or None".into());
|
||||
}
|
||||
let exchange = match b.get("body") {
|
||||
None | Some(Value::None) => request.call(),
|
||||
Some(Value::Text(text)) => request.send_bytes(text.as_bytes()),
|
||||
Some(v) => request.send_bytes(&super::fs_ops::bytes(v)?),
|
||||
};
|
||||
let response = match exchange {
|
||||
Ok(r) => r,
|
||||
Err(ureq::Error::Status(_, r)) => r,
|
||||
Err(e) => return Err(format!("transport_error: {e}")),
|
||||
};
|
||||
let status = response.status();
|
||||
let mut headers = Vec::new();
|
||||
for name in response.headers_names() {
|
||||
let values = response
|
||||
.all(&name)
|
||||
.into_iter()
|
||||
.map(|v| Value::Text(v.into()))
|
||||
.collect();
|
||||
headers.push(Value::Map(vec![
|
||||
("name".into(), Value::Text(name.to_ascii_lowercase())),
|
||||
("values".into(), Value::List(values)),
|
||||
]));
|
||||
}
|
||||
let mut reader = response.into_reader();
|
||||
if id == HostFn::HttpDownload {
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("http_status: {status}; destination unchanged"));
|
||||
}
|
||||
let path = destination.ok_or("missing validated download destination")?;
|
||||
let parent = path.parent().ok_or("destination needs parent")?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let token = entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-download-{token}"));
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let downloaded = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = reader.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
std::fs::rename(&temp, &path).map_err(|e| e.to_string())?;
|
||||
Ok(total)
|
||||
})();
|
||||
let total = match downloaded {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(temp);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
return Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("size".into(), Value::Int(total as i64)),
|
||||
("path".into(), arg(b, "path")?.clone()),
|
||||
]));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(max + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
let mode = as_text(arg(b, "response")?, "response")?;
|
||||
let body = match mode {
|
||||
"text" => Value::Text(String::from_utf8(bytes).map_err(|e| {
|
||||
format!("invalid_encoding: response is not UTF-8; request bytes instead: {e}")
|
||||
})?),
|
||||
"bytes" => super::fs_ops::bytes_value(&bytes),
|
||||
_ => return Err("response must be text or bytes".into()),
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("body".into(), body),
|
||||
]))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! A recoverable failure is data; permission errors remain explicit failures.
|
||||
use crate::value::Value;
|
||||
|
||||
pub(super) fn capture(operation: &str, result: Result<Value, String>) -> Value {
|
||||
let (ok, value, error) = match result {
|
||||
Ok(value) => (true, value, Value::None),
|
||||
Err(message) => {
|
||||
let tagged = message.split_once(':').map(|(code, _)| code);
|
||||
let code = match tagged {
|
||||
Some(
|
||||
code @ ("validation_failed" | "timed_out" | "permission_denied" | "not_found"
|
||||
| "conflict" | "invalid_encoding" | "invalid_json" | "invalid_csv"
|
||||
| "invalid_toml" | "transport_error" | "http_status" | "resource_limit"
|
||||
| "unsupported" | "invalid_argument" | "nonexistent_time"
|
||||
| "ambiguous_time"),
|
||||
) => code,
|
||||
_ if message.starts_with("path escapes sandbox root:")
|
||||
|| message.ends_with("denied by host policy") =>
|
||||
{
|
||||
"permission_denied"
|
||||
}
|
||||
_ => "operation_failed",
|
||||
};
|
||||
(
|
||||
false,
|
||||
Value::None,
|
||||
Value::Map(vec![
|
||||
("code".into(), Value::Text(code.into())),
|
||||
("message".into(), Value::Text(message)),
|
||||
("operation".into(), Value::Text(operation.into())),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
Value::Map(vec![
|
||||
("ok".into(), Value::Bool(ok)),
|
||||
("value".into(), value),
|
||||
("error".into(), error),
|
||||
])
|
||||
}
|
||||
@@ -277,6 +277,25 @@ pub fn inspect(id: &str) -> Result<serde_json::Value, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Byte-preserving overlay access shared by text and byte APIs.
|
||||
pub(super) fn cow_read_bytes(ctx: &HostContext, abs: &Path) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(None); };
|
||||
with_session(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
if session.whiteout.contains(&rel) { return Err(format!("not found (sandbox whiteout): {rel}")); }
|
||||
Ok(session.upper.get(&rel).cloned())
|
||||
})
|
||||
}
|
||||
pub(super) fn cow_write_bytes(ctx: &HostContext, abs: &Path, bytes: &[u8]) -> Result<bool, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(false); };
|
||||
with_session_mut(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
session.whiteout.remove(&rel);
|
||||
session.upper.insert(rel, bytes.to_vec());
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read file bytes through CoW for an active host sandbox session (lib/fs).
|
||||
pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result<Option<String>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
|
||||
+55
-10
@@ -302,6 +302,11 @@ fn spawn_file(
|
||||
));
|
||||
let mut cmd = Command::new(&exe);
|
||||
cmd.arg("run").arg(&file);
|
||||
if !ctx.caps.fs_write { cmd.arg("--deny-fs-write"); }
|
||||
if !ctx.caps.exec { cmd.arg("--deny-exec"); }
|
||||
if !ctx.caps.net { cmd.arg("--deny-net"); }
|
||||
if !ctx.caps.plugin { cmd.arg("--deny-plugin"); }
|
||||
if let Some(root) = &ctx.fs_root { cmd.arg("--fs-root").arg(root); }
|
||||
cmd.arg("--emit-result").arg(&result_path);
|
||||
cmd.current_dir(&ctx.cwd);
|
||||
cmd.stdin(Stdio::null());
|
||||
@@ -340,18 +345,10 @@ fn spawn_file(
|
||||
let mut stdout_pipe = child.stdout.take();
|
||||
let mut stderr_pipe = child.stderr.take();
|
||||
let stdout = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stdout_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
stdout_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
let stderr = thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(ref mut r) = stderr_pipe {
|
||||
let _ = r.read_to_end(&mut buf);
|
||||
}
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
stderr_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
(Some(stdout), Some(stderr))
|
||||
} else {
|
||||
@@ -679,6 +676,54 @@ pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(results))
|
||||
}
|
||||
|
||||
fn capture_file_io(reader:&mut impl Read)->String {
|
||||
let mut kept=Vec::new(); let mut buffer=[0u8;8192];
|
||||
loop { match reader.read(&mut buffer) {
|
||||
Ok(0)|Err(_)=>break,
|
||||
Ok(n)=>{ let take=(FILE_IO_CAP+4-kept.len()).min(n);kept.extend_from_slice(&buffer[..take]); }
|
||||
}}
|
||||
clip_io(&String::from_utf8_lossy(&kept))
|
||||
}
|
||||
|
||||
/// Timeout leaves the handle available unless cancel=True. Process cancellation
|
||||
/// reaps the OS child; function-thread cancellation is logical, as in kill().
|
||||
pub(super) fn wait_timeout(ctx:&mut HostContext,id:&Value,timeout_ms:u64,cancel:bool)->Result<Value,String>{
|
||||
let start=std::time::Instant::now();
|
||||
loop{
|
||||
let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{return join(ctx,id)}
|
||||
if start.elapsed()>=Duration::from_millis(timeout_ms){if cancel{kill(ctx,id)?;}return Err("timed_out: subtask wait deadline exceeded".into())}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
pub(super) fn run_many(ctx:&mut HostContext,tasks:&Value,limit:usize,timeout_ms:u64)->Result<Value,String>{
|
||||
let Value::List(tasks)=tasks else{return Err("tasks must be record list".into())};
|
||||
if !(1..=64).contains(&limit){return Err("limit must be 1..64".into())}
|
||||
if tasks.len()>10000{return Err("batch exceeds 10000 tasks".into())}
|
||||
// Validate the entire batch before starting any process.
|
||||
let jobs=tasks.iter().map(|task|{let Value::Map(fields)=task else{return Err("task must contain path and optional args".to_string())};
|
||||
let mut job=HashMap::new();for (key,value) in fields{if !matches!(key.as_str(),"path"|"args"){return Err(format!("unsupported batch field {key}"))}job.insert(key.clone(),value.clone());}
|
||||
let path=job.get("path").ok_or("task missing path")?;ctx.resolve_path(as_text(path,"path")?)?;Ok(job)
|
||||
}).collect::<Result<Vec<_>,String>>()?;
|
||||
let mut active:Vec<(usize,Value,std::time::Instant)>=Vec::new();let mut next=0;let mut out=vec![Value::None;jobs.len()];
|
||||
while next<jobs.len()||!active.is_empty(){
|
||||
while next<jobs.len()&&active.len()<limit{
|
||||
match spawn(ctx,&jobs[next]){Ok(id)=>active.push((next,id,std::time::Instant::now())),Err(error)=>out[next]=super::result::capture("subtask.run_many",Err(error))};next+=1;
|
||||
}
|
||||
let mut i=0;
|
||||
while i<active.len(){
|
||||
let (_,id,start)=&active[i];let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{let(index,id,_)=active.remove(i);out[index]=super::result::capture("subtask.run_many",join(ctx,&id));}
|
||||
else if start.elapsed()>=Duration::from_millis(timeout_ms){let(index,id,_)=active.remove(i);let _=kill(ctx,&id);out[index]=super::result::capture("subtask.run_many",Err("timed_out: batch task deadline exceeded".into()));}
|
||||
else{i+=1;}
|
||||
}
|
||||
if !active.is_empty(){thread::sleep(Duration::from_millis(5));}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
fn clip_io(s: &str) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(FILE_IO_CAP).collect();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Bounded orchestration over existing subtask resources.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "exec-host")]
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
fn integer(b: &HashMap<String, Value>, key: &str) -> Result<u64, String> {
|
||||
match arg(b, key)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{key} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
match id {
|
||||
HostFn::SubtaskWaitTimeout => {
|
||||
let answer = super::subtask::wait_timeout(
|
||||
ctx,
|
||||
arg(b, "id")?,
|
||||
integer(b, "timeout_ms")?,
|
||||
matches!(b.get("cancel"), Some(Value::Bool(true))),
|
||||
);
|
||||
Ok(super::result::capture("subtask.wait_timeout", answer))
|
||||
}
|
||||
HostFn::SubtaskCancelAll => {
|
||||
let count = ctx.subtasks.len();
|
||||
super::subtask::kill_all(ctx);
|
||||
Ok(Value::Int(count as i64))
|
||||
}
|
||||
HostFn::SubtaskRunMany => super::subtask::run_many(
|
||||
ctx,
|
||||
arg(b, "tasks")?,
|
||||
integer(b, "limit")? as usize,
|
||||
integer(b, "timeout_ms")?,
|
||||
),
|
||||
_ => Err("not a task operation".into()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, id, b);
|
||||
Err("subtask unavailable in this build".into())
|
||||
}
|
||||
}
|
||||
+30
-297
@@ -1,305 +1,38 @@
|
||||
//! Minimal TOML → Marqdo Value for Mid2 M8 (`lib/toml`).
|
||||
//! Subset: comments, keys, strings, ints, floats, bools, arrays of scalars,
|
||||
//! `[table]` / dotted tables. No datetime, inline tables, or array-of-tables.
|
||||
//! Standards-based TOML; datetime scalars become explicit ISO text at Value boundary.
|
||||
use crate::{host::as_text,value::Value};
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::host::json::json_to_value;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let json = toml_to_json(raw)?;
|
||||
json_to_value(&json)
|
||||
pub fn parse(text: &Value) -> Result<Value,String> {
|
||||
let parsed: toml::Value = toml::from_str(as_text(text,"text")?).map_err(|e|format!("toml.parse: {e}"))?;
|
||||
fn convert(v: toml::Value) -> Result<Value,String> {
|
||||
Ok(match v {
|
||||
toml::Value::String(s) => Value::Text(s),
|
||||
toml::Value::Integer(n) => Value::Int(n),
|
||||
toml::Value::Float(n) if n.is_finite() => Value::Num(n),
|
||||
toml::Value::Float(_) => return Err("toml: non-finite numbers unsupported".into()),
|
||||
toml::Value::Boolean(b) => Value::Bool(b),
|
||||
toml::Value::Datetime(dt) => Value::Text(dt.to_string()),
|
||||
toml::Value::Array(xs) => Value::List(xs.into_iter().map(convert).collect::<Result<_,_>>()?),
|
||||
toml::Value::Table(fields) => Value::Map(fields.into_iter().map(|(k,v)|convert(v).map(|v|(k,v))).collect::<Result<_,_>>()?),
|
||||
})
|
||||
}
|
||||
convert(parsed)
|
||||
}
|
||||
|
||||
fn toml_to_json(src: &str) -> Result<serde_json::Value, String> {
|
||||
let mut root = serde_json::Map::new();
|
||||
let mut current_path: Vec<String> = Vec::new();
|
||||
for (lineno, line) in src.lines().enumerate() {
|
||||
let line_no = lineno + 1;
|
||||
let stripped = strip_comment(line);
|
||||
let t = stripped.trim();
|
||||
if t.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if t.starts_with('[') {
|
||||
if !t.ends_with(']') {
|
||||
return Err(format!("toml.parse:{line_no}: bad table header"));
|
||||
}
|
||||
if t.starts_with("[[") {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: array-of-tables [[...]] not supported"
|
||||
));
|
||||
}
|
||||
let inner = t[1..t.len() - 1].trim();
|
||||
current_path = split_dotted_keys(inner, line_no)?;
|
||||
ensure_table_path(&mut root, ¤t_path, line_no)?;
|
||||
continue;
|
||||
}
|
||||
let (key, val) = t
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("toml.parse:{line_no}: expected key = value"))?;
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty key"));
|
||||
}
|
||||
let key_parts = split_dotted_keys(key, line_no)?;
|
||||
let value = parse_value(val.trim(), line_no)?;
|
||||
let parent = table_at_path(&mut root, ¤t_path, line_no)?;
|
||||
insert_dotted(parent, &key_parts, value, line_no)?;
|
||||
pub fn stringify(value:&Value)->Result<Value,String>{
|
||||
fn convert(v:&Value)->Result<toml::Value,String>{
|
||||
Ok(match v {
|
||||
Value::Text(s)=>toml::Value::String(s.clone()),
|
||||
Value::Int(n)=>toml::Value::Integer(*n),
|
||||
Value::Num(n) if n.is_finite()=>toml::Value::Float(*n),
|
||||
Value::Bool(b)=>toml::Value::Boolean(*b),
|
||||
Value::List(xs)=>toml::Value::Array(xs.iter().map(convert).collect::<Result<_,_>>()?),
|
||||
Value::Map(fields)=>toml::Value::Table(fields.iter().map(|(k,v)|convert(v).map(|v|(k.clone(),v))).collect::<Result<_,_>>()?),
|
||||
_=>return Err("toml.stringify supports text/finite numbers/bool/list/map; None has no TOML representation".into()),
|
||||
})
|
||||
}
|
||||
Ok(serde_json::Value::Object(root))
|
||||
if !matches!(value,Value::Map(_)){return Err("toml root must be map".into())}
|
||||
toml::to_string_pretty(&convert(value)?).map(Value::Text).map_err(|e|format!("toml.stringify: {e}"))
|
||||
}
|
||||
|
||||
fn strip_comment(line: &str) -> String {
|
||||
// Strip unquoted `#` comments.
|
||||
let mut out = String::new();
|
||||
let mut in_str = false;
|
||||
let mut chars = line.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if !in_str && c == '#' {
|
||||
break;
|
||||
}
|
||||
if c == '"' {
|
||||
out.push(c);
|
||||
in_str = !in_str;
|
||||
continue;
|
||||
}
|
||||
if in_str && c == '\\' {
|
||||
out.push(c);
|
||||
if let Some(n) = chars.next() {
|
||||
out.push(n);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn split_dotted_keys(s: &str, line_no: usize) -> Result<Vec<String>, String> {
|
||||
let mut parts = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut in_quote = false;
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '"' {
|
||||
in_quote = !in_quote;
|
||||
continue;
|
||||
}
|
||||
if c == '.' && !in_quote {
|
||||
if cur.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty key segment"));
|
||||
}
|
||||
parts.push(std::mem::take(&mut cur));
|
||||
continue;
|
||||
}
|
||||
cur.push(c);
|
||||
}
|
||||
if in_quote {
|
||||
return Err(format!("toml.parse:{line_no}: unclosed quoted key"));
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
parts.push(cur);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty path"));
|
||||
}
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
fn ensure_table_path(
|
||||
root: &mut serde_json::Map<String, serde_json::Value>,
|
||||
path: &[String],
|
||||
line_no: usize,
|
||||
) -> Result<(), String> {
|
||||
let mut cur = root;
|
||||
for seg in path {
|
||||
if !cur.contains_key(seg) {
|
||||
cur.insert(seg.clone(), serde_json::Value::Object(serde_json::Map::new()));
|
||||
}
|
||||
cur = match cur.get_mut(seg) {
|
||||
Some(serde_json::Value::Object(m)) => m,
|
||||
Some(_) => {
|
||||
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
|
||||
}
|
||||
None => unreachable!(),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn table_at_path<'a>(
|
||||
root: &'a mut serde_json::Map<String, serde_json::Value>,
|
||||
path: &[String],
|
||||
line_no: usize,
|
||||
) -> Result<&'a mut serde_json::Map<String, serde_json::Value>, String> {
|
||||
let mut cur = root;
|
||||
for seg in path {
|
||||
cur = match cur.get_mut(seg) {
|
||||
Some(serde_json::Value::Object(m)) => m,
|
||||
Some(_) => {
|
||||
return Err(format!("toml.parse:{line_no}: {seg} is not a table"));
|
||||
}
|
||||
None => {
|
||||
return Err(format!("toml.parse:{line_no}: missing table {seg}"));
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(cur)
|
||||
}
|
||||
|
||||
fn insert_dotted(
|
||||
parent: &mut serde_json::Map<String, serde_json::Value>,
|
||||
parts: &[String],
|
||||
value: serde_json::Value,
|
||||
line_no: usize,
|
||||
) -> Result<(), String> {
|
||||
if parts.len() == 1 {
|
||||
if parent.contains_key(&parts[0]) {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: duplicate key {}",
|
||||
parts[0]
|
||||
));
|
||||
}
|
||||
parent.insert(parts[0].clone(), value);
|
||||
return Ok(());
|
||||
}
|
||||
let head = &parts[0];
|
||||
let entry = parent
|
||||
.entry(head.clone())
|
||||
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
|
||||
let obj = match entry {
|
||||
serde_json::Value::Object(m) => m,
|
||||
_ => {
|
||||
return Err(format!("toml.parse:{line_no}: {head} is not a table"));
|
||||
}
|
||||
};
|
||||
insert_dotted(obj, &parts[1..], value, line_no)
|
||||
}
|
||||
|
||||
fn parse_value(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
|
||||
if s.is_empty() {
|
||||
return Err(format!("toml.parse:{line_no}: empty value"));
|
||||
}
|
||||
if s == "true" {
|
||||
return Ok(serde_json::Value::Bool(true));
|
||||
}
|
||||
if s == "false" {
|
||||
return Ok(serde_json::Value::Bool(false));
|
||||
}
|
||||
if s.starts_with('"') {
|
||||
return Ok(serde_json::Value::String(parse_basic_string(s, line_no)?));
|
||||
}
|
||||
if s.starts_with('\'') {
|
||||
return Ok(serde_json::Value::String(parse_literal_string(s, line_no)?));
|
||||
}
|
||||
if s.starts_with('[') {
|
||||
return parse_array(s, line_no);
|
||||
}
|
||||
if let Ok(i) = s.replace('_', "").parse::<i64>() {
|
||||
return Ok(serde_json::Value::Number(i.into()));
|
||||
}
|
||||
if let Ok(f) = s.replace('_', "").parse::<f64>() {
|
||||
if let Some(n) = serde_json::Number::from_f64(f) {
|
||||
return Ok(serde_json::Value::Number(n));
|
||||
}
|
||||
}
|
||||
Err(format!("toml.parse:{line_no}: unsupported value {s:?}"))
|
||||
}
|
||||
|
||||
fn parse_basic_string(s: &str, line_no: usize) -> Result<String, String> {
|
||||
if !s.ends_with('"') || s.len() < 2 {
|
||||
return Err(format!("toml.parse:{line_no}: bad string"));
|
||||
}
|
||||
let inner = &s[1..s.len() - 1];
|
||||
let mut out = String::new();
|
||||
let mut chars = inner.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
match chars.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some('\\') => out.push('\\'),
|
||||
Some('"') => out.push('"'),
|
||||
Some(other) => {
|
||||
return Err(format!(
|
||||
"toml.parse:{line_no}: bad escape \\{other}"
|
||||
));
|
||||
}
|
||||
None => return Err(format!("toml.parse:{line_no}: trailing escape")),
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn parse_literal_string(s: &str, line_no: usize) -> Result<String, String> {
|
||||
if !s.ends_with('\'') || s.len() < 2 {
|
||||
return Err(format!("toml.parse:{line_no}: bad literal string"));
|
||||
}
|
||||
Ok(s[1..s.len() - 1].to_string())
|
||||
}
|
||||
|
||||
fn parse_array(s: &str, line_no: usize) -> Result<serde_json::Value, String> {
|
||||
if !s.ends_with(']') {
|
||||
return Err(format!("toml.parse:{line_no}: bad array"));
|
||||
}
|
||||
let inner = s[1..s.len() - 1].trim();
|
||||
if inner.is_empty() {
|
||||
return Ok(serde_json::Value::Array(vec![]));
|
||||
}
|
||||
let mut items = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut depth = 0i32;
|
||||
let mut in_str = false;
|
||||
let mut str_ch = '"';
|
||||
let mut chars = inner.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if in_str {
|
||||
cur.push(c);
|
||||
if c == '\\' {
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c == str_ch {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' | '\'' => {
|
||||
in_str = true;
|
||||
str_ch = c;
|
||||
cur.push(c);
|
||||
}
|
||||
'[' => {
|
||||
depth += 1;
|
||||
cur.push(c);
|
||||
}
|
||||
']' => {
|
||||
depth -= 1;
|
||||
cur.push(c);
|
||||
}
|
||||
',' if depth == 0 => {
|
||||
items.push(parse_value(cur.trim(), line_no)?);
|
||||
cur.clear();
|
||||
}
|
||||
_ => cur.push(c),
|
||||
}
|
||||
}
|
||||
if !cur.trim().is_empty() {
|
||||
items.push(parse_value(cur.trim(), line_no)?);
|
||||
}
|
||||
Ok(serde_json::Value::Array(items))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in new issue
Block a user