2026-03-18 22:44:52 -04:00
|
|
|
// tools/write.rs — Write file contents
|
|
|
|
|
|
|
|
|
|
use anyhow::{Context, Result};
|
2026-03-21 16:28:10 -04:00
|
|
|
use serde::Deserialize;
|
2026-03-18 22:44:52 -04:00
|
|
|
use serde_json::json;
|
|
|
|
|
use std::path::Path;
|
|
|
|
|
|
|
|
|
|
use crate::types::ToolDef;
|
|
|
|
|
|
2026-03-21 16:28:10 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
struct Args {
|
|
|
|
|
file_path: String,
|
|
|
|
|
content: String,
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-18 22:44:52 -04:00
|
|
|
pub fn definition() -> ToolDef {
|
|
|
|
|
ToolDef::new(
|
|
|
|
|
"write_file",
|
|
|
|
|
"Write content to a file. Creates the file if it doesn't exist, \
|
|
|
|
|
overwrites if it does. Creates parent directories as needed.",
|
|
|
|
|
json!({
|
|
|
|
|
"type": "object",
|
|
|
|
|
"properties": {
|
|
|
|
|
"file_path": {
|
|
|
|
|
"type": "string",
|
|
|
|
|
"description": "Absolute path to the file to write"
|
|
|
|
|
},
|
|
|
|
|
"content": {
|
|
|
|
|
"type": "string",
|
|
|
|
|
"description": "The content to write to the file"
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
"required": ["file_path", "content"]
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn write_file(args: &serde_json::Value) -> Result<String> {
|
2026-03-21 16:28:10 -04:00
|
|
|
let args: Args = serde_json::from_value(args.clone())
|
|
|
|
|
.context("invalid write_file arguments")?;
|
2026-03-18 22:44:52 -04:00
|
|
|
|
2026-03-21 16:28:10 -04:00
|
|
|
if let Some(parent) = Path::new(&args.file_path).parent() {
|
2026-03-18 22:44:52 -04:00
|
|
|
std::fs::create_dir_all(parent)
|
2026-03-21 16:28:10 -04:00
|
|
|
.with_context(|| format!("Failed to create directories for {}", args.file_path))?;
|
2026-03-18 22:44:52 -04:00
|
|
|
}
|
|
|
|
|
|
2026-03-21 16:28:10 -04:00
|
|
|
std::fs::write(&args.file_path, &args.content)
|
|
|
|
|
.with_context(|| format!("Failed to write {}", args.file_path))?;
|
2026-03-18 22:44:52 -04:00
|
|
|
|
2026-03-21 16:28:10 -04:00
|
|
|
Ok(format!("Wrote {} lines to {}", args.content.lines().count(), args.file_path))
|
2026-03-18 22:44:52 -04:00
|
|
|
}
|