use async_trait::async_trait;
use clap::{CommandFactory, Parser};
use std::path::Path;
use crate::ast::Value;
use crate::interpreter::{ExecResult, OutputData};
use crate::operation::KernelOperation;
use crate::tools::builtin::get_path_string;
use crate::tools::{schema_from_clap, ExecContext, ToolCtx, GlobalFlags, Tool, ToolArgs, ToolSchema};
pub struct Write;
#[derive(Parser, Debug)]
#[command(name = "write", about = "Write content to a file")]
struct WriteArgs {
#[arg(long)]
path: Option<String>,
#[arg(long)]
content: Option<String>,
#[command(flatten)]
global: GlobalFlags,
args: Vec<String>,
}
#[async_trait]
impl Tool for Write {
fn name(&self) -> &str {
"write"
}
fn schema(&self) -> ToolSchema {
schema_from_clap(
&WriteArgs::command(),
"write",
"Write content to a file",
[
("Write to a file", "write output.txt \"hello world\""),
("Pipe into write", "echo content | write file.txt"),
],
)
.with_operations([KernelOperation::FsOverwrite.as_str()])
}
async fn execute(&self, args: ToolArgs, ctx: &mut dyn ToolCtx) -> ExecResult {
let Some(ctx) = ctx.as_any_mut().downcast_mut::<ExecContext>() else {
return ExecResult::failure(1, "internal error: kernel builtin requires ExecContext");
};
let argv = match args.to_argv_excluding(&["content"]) {
Ok(v) => v,
Err(e) => return ExecResult::failure(2, format!("write: {e}")),
};
let parsed = match WriteArgs::try_parse_from(
std::iter::once("write".to_string()).chain(argv),
) {
Ok(p) => p,
Err(e) => return ExecResult::failure(2, format!("write: {e}")),
};
parsed.global.apply(ctx);
let path = match get_path_string(&args, "path", 0) {
Ok(Some(p)) => p,
Ok(None) => return ExecResult::failure(1, "write: missing path argument"),
Err(e) => return ExecResult::failure(1, format!("write: {e}")),
};
let resolved = ctx.resolve_path(&path);
let snapshots = match ctx
.snapshot_overwrites("write",
&[(path.clone(), false)])
.await
{
Ok(s) => s,
Err(blocked) => return blocked,
};
let content: Vec<u8> = if let Some(v) = args.named.get("content") {
value_to_bytes(v)
} else if let Some(v) = args.positional.get(1) {
value_to_bytes(v)
} else {
match ctx.read_stdin_to_bytes().await {
Some(bytes) => bytes,
None => return ExecResult::failure(1, "write: missing content argument"),
}
};
let expected = snapshots.get(&resolved);
match ctx.overwrite_checked(Path::new(&resolved), &content, expected).await {
Ok(()) => ExecResult::with_output(OutputData::text(format!("Wrote {} bytes to {}", content.len(), path))),
Err(e) => ExecResult::failure(1, format!("write: {}: {}", path, e)),
}
}
}
fn value_to_bytes(value: &Value) -> Vec<u8> {
match value {
Value::Bytes(b) => b.clone(),
Value::String(s) => s.clone().into_bytes(),
Value::Int(i) => i.to_string().into_bytes(),
Value::Float(f) => f.to_string().into_bytes(),
Value::Bool(b) => b.to_string().into_bytes(),
Value::Null => b"null".to_vec(),
Value::Json(json) => json.to_string().into_bytes(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vfs::{MemoryFs, VfsRouter};
use std::sync::Arc;
async fn make_ctx() -> ExecContext {
let mut vfs = VfsRouter::new();
vfs.mount("/", MemoryFs::new());
ExecContext::new(Arc::new(vfs))
}
#[tokio::test]
async fn test_write_simple() {
let mut ctx = make_ctx().await;
let mut args = ToolArgs::new();
args.positional.push(Value::String("/test.txt".into()));
args.positional.push(Value::String("hello world".into()));
let result = Write.execute(args, &mut ctx).await;
assert!(result.ok());
let data = ctx.backend.read(Path::new("/test.txt"), None).await.unwrap();
assert_eq!(String::from_utf8(data).unwrap(), "hello world");
}
#[tokio::test]
async fn test_write_named() {
let mut ctx = make_ctx().await;
let mut args = ToolArgs::new();
args.positional.push(Value::String("/test.txt".into()));
args.named.insert("content".to_string(), Value::String("named content".into()));
let result = Write.execute(args, &mut ctx).await;
assert!(result.ok());
let data = ctx.backend.read(Path::new("/test.txt"), None).await.unwrap();
assert_eq!(String::from_utf8(data).unwrap(), "named content");
}
#[tokio::test]
async fn test_write_nested() {
let mut ctx = make_ctx().await;
let mut args = ToolArgs::new();
args.positional.push(Value::String("/a/b/c.txt".into()));
args.positional.push(Value::String("nested".into()));
let result = Write.execute(args, &mut ctx).await;
assert!(result.ok());
let data = ctx.backend.read(Path::new("/a/b/c.txt"), None).await.unwrap();
assert_eq!(String::from_utf8(data).unwrap(), "nested");
}
#[tokio::test]
async fn test_write_no_path() {
let mut ctx = make_ctx().await;
let args = ToolArgs::new();
let result = Write.execute(args, &mut ctx).await;
assert!(!result.ok());
assert!(result.err.contains("missing path"));
}
}