Skip to main content

tinyharness_lib/tools/
write.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use crate::extract_args;
6use crate::path_guard::PathGuard;
7use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
8
9pub fn write_tool_entry(guard: Option<PathGuard>) -> crate::tools::tool::Tool {
10    make_tool(
11        "write",
12        "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Creates parent directories automatically.",
13        ToolCategory::Destructive,
14        build_string_params_schema(
15            &[
16                ("path", "The absolute path to the file to write"),
17                ("content", "The text content to write to the file"),
18            ],
19            &[],
20        ),
21        move |args| {
22            let guard = guard.clone();
23            Box::pin(write_tool_inner(args, guard))
24        },
25    )
26}
27
28pub fn write_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
29    Box::pin(write_tool_inner(args, None))
30}
31
32async fn write_tool_inner(args: HashMap<String, String>, guard: Option<PathGuard>) -> String {
33    extract_args!(args, path, content);
34
35    // Create parent directories if they don't exist. Through the guard each
36    // new directory is verified via its open descriptor, so a symlink swapped
37    // in after the argument check cannot redirect creation outside the root.
38    if let Some(parent) = Path::new(&path).parent()
39        && !parent.as_os_str().is_empty()
40    {
41        let result = match &guard {
42            Some(g) => g.create_dir_all_contained(parent),
43            None => fs::create_dir_all(parent).map_err(|e| e.to_string()),
44        };
45        if let Err(e) = result {
46            return format!("Error: Failed to create parent directories: {}", e);
47        }
48    }
49
50    let result = match &guard {
51        Some(g) => g.write_contained(Path::new(&path), &content),
52        None => fs::write(&path, &content).map_err(|e| e.to_string()),
53    };
54    match result {
55        Ok(_) => format!("Wrote {} bytes to '{}'.", content.len(), path),
56        Err(e) => format!("Error: Failed to write file: {}", e),
57    }
58}