Skip to main content

matrixcode_core/tools/
write.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use super::{Tool, ToolDefinition};
6use crate::approval::RiskLevel;
7
8pub struct WriteTool;
9
10#[async_trait]
11impl Tool for WriteTool {
12    fn definition(&self) -> ToolDefinition {
13        ToolDefinition {
14            name: "write".to_string(),
15            description: "Write content to a file, creating it if it doesn't exist".to_string(),
16            parameters: json!({
17                "type": "object",
18                "properties": {
19                    "path": {
20                        "type": "string",
21                        "description": "The file path to write to"
22                    },
23                    "content": {
24                        "type": "string",
25                        "description": "The content to write"
26                    }
27                },
28                "required": ["path", "content"]
29            }),
30        }
31    }
32
33    async fn execute(&self, params: Value) -> Result<String> {
34        let path = params["path"].as_str().ok_or_else(|| anyhow::anyhow!("missing 'path'"))?;
35        let content = params["content"].as_str().ok_or_else(|| anyhow::anyhow!("missing 'content'"))?;
36
37        // Create spinner immediately at the start to fill the gap before actual operation
38        // let mut spinner = ToolSpinner::new(&format!("preparing write to {}", path));
39
40        // Create parent directories if needed
41        if let Some(parent) = std::path::Path::new(path).parent() {
42            tokio::fs::create_dir_all(parent).await?;
43        }
44
45        let total_bytes = content.len();
46
47        // Update spinner message for the actual write operation
48        // spinner.set_message(&format!("writing to {}", path));
49
50        // Write the file
51        tokio::fs::write(path, content).await?;
52
53        // spinner.finish_success(&format!("wrote {} bytes", total_bytes));
54
55        Ok(format!("Successfully wrote {} bytes to {}", total_bytes, path))
56    }
57
58    fn risk_level(&self) -> RiskLevel {
59        RiskLevel::Mutating
60    }
61}