Skip to main content

codive_tools/
write_file.rs

1//! WriteFile tool for writing content to files
2//!
3//! This tool writes content to files, creating parent directories if needed.
4
5use codive_core::tool::{Tool, ToolOutput};
6use async_trait::async_trait;
7use serde::Deserialize;
8use std::path::Path;
9use tokio::fs;
10use tracing::debug;
11
12/// Maximum content size to write (10MB)
13const MAX_CONTENT_SIZE: usize = 10 * 1024 * 1024;
14
15/// Tool for writing file contents
16pub struct WriteFileTool {
17    /// Maximum content size to write
18    max_content_size: usize,
19    /// Whether to create parent directories
20    create_parents: bool,
21}
22
23impl WriteFileTool {
24    /// Create a new WriteFileTool with default settings
25    pub fn new() -> Self {
26        Self {
27            max_content_size: MAX_CONTENT_SIZE,
28            create_parents: true,
29        }
30    }
31
32    /// Set the maximum content size
33    pub fn with_max_content_size(mut self, size: usize) -> Self {
34        self.max_content_size = size;
35        self
36    }
37
38    /// Set whether to create parent directories
39    pub fn with_create_parents(mut self, create: bool) -> Self {
40        self.create_parents = create;
41        self
42    }
43}
44
45impl Default for WriteFileTool {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51/// Parameters for the write_file tool
52#[derive(Debug, Deserialize)]
53struct WriteFileParams {
54    /// Path to the file to write
55    path: String,
56    /// Content to write to the file
57    content: String,
58    /// Whether to append instead of overwrite (default: false)
59    #[serde(default)]
60    append: bool,
61}
62
63#[async_trait]
64impl Tool for WriteFileTool {
65    fn name(&self) -> &str {
66        "write_file"
67    }
68
69    fn description(&self) -> &str {
70        "Write content to a file. Creates the file if it doesn't exist. \
71         Parent directories are created automatically. \
72         Use append=true to append instead of overwriting."
73    }
74
75    fn parameters_schema(&self) -> serde_json::Value {
76        serde_json::json!({
77            "type": "object",
78            "properties": {
79                "path": {
80                    "type": "string",
81                    "description": "The path to the file to write"
82                },
83                "content": {
84                    "type": "string",
85                    "description": "The content to write to the file"
86                },
87                "append": {
88                    "type": "boolean",
89                    "description": "If true, append to the file instead of overwriting. Default: false"
90                }
91            },
92            "required": ["path", "content"]
93        })
94    }
95
96    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
97        // Parse parameters
98        let params: WriteFileParams = match serde_json::from_value(params) {
99            Ok(p) => p,
100            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
101        };
102
103        // Check content size
104        if params.content.len() > self.max_content_size {
105            return ToolOutput::error(format!(
106                "Content too large: {} bytes (max: {} bytes)",
107                params.content.len(),
108                self.max_content_size
109            ));
110        }
111
112        let path = Path::new(&params.path);
113        debug!(path = %path.display(), append = params.append, "Writing file");
114
115        // Create parent directories if needed
116        if self.create_parents {
117            if let Some(parent) = path.parent() {
118                if !parent.exists() {
119                    if let Err(e) = fs::create_dir_all(parent).await {
120                        return ToolOutput::error(format!(
121                            "Failed to create parent directories: {}",
122                            e
123                        ));
124                    }
125                }
126            }
127        }
128
129        // Capture old content for diff (before any writes)
130        let old_content = fs::read_to_string(path).await.ok();
131
132        // Write or append to the file
133        let (result, final_content) = if params.append {
134            // Read existing content and append
135            let existing = old_content.clone().unwrap_or_default();
136            let new_content = format!("{}{}", existing, params.content);
137            let res = fs::write(path, &new_content).await;
138            (res, new_content)
139        } else {
140            let res = fs::write(path, &params.content).await;
141            (res, params.content.clone())
142        };
143
144        match result {
145            Ok(()) => {
146                let bytes = params.content.len();
147                let action = if params.append { "Appended" } else { "Wrote" };
148                ToolOutput::success(format!("{} {} bytes to {}", action, bytes, path.display()))
149                    .with_file_change(params.path, old_content, final_content)
150            }
151            Err(e) => ToolOutput::error(format!("Failed to write file: {}", e)),
152        }
153    }
154}
155
156// ============================================================================
157// Tests
158// ============================================================================
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use tempfile::{tempdir, NamedTempFile};
164
165    #[test]
166    fn test_write_file_tool_name() {
167        let tool = WriteFileTool::new();
168        assert_eq!(tool.name(), "write_file");
169    }
170
171    #[test]
172    fn test_write_file_schema() {
173        let tool = WriteFileTool::new();
174        let schema = tool.parameters_schema();
175        assert_eq!(schema["type"], "object");
176        assert!(schema["properties"]["path"].is_object());
177        assert!(schema["properties"]["content"].is_object());
178        assert_eq!(schema["required"][0], "path");
179        assert_eq!(schema["required"][1], "content");
180    }
181
182    #[tokio::test]
183    async fn test_write_new_file() {
184        let dir = tempdir().unwrap();
185        let file_path = dir.path().join("test.txt");
186
187        let tool = WriteFileTool::new();
188        let output = tool
189            .execute(serde_json::json!({
190                "path": file_path.to_str().unwrap(),
191                "content": "hello world"
192            }))
193            .await;
194
195        assert!(output.is_success());
196        assert!(output.content.contains("Wrote"));
197        assert!(output.content.contains("11 bytes"));
198
199        // Verify file content
200        let content = std::fs::read_to_string(&file_path).unwrap();
201        assert_eq!(content, "hello world");
202    }
203
204    #[tokio::test]
205    async fn test_write_overwrite() {
206        let file = NamedTempFile::new().unwrap();
207        std::fs::write(file.path(), "old content").unwrap();
208
209        let tool = WriteFileTool::new();
210        let output = tool
211            .execute(serde_json::json!({
212                "path": file.path().to_str().unwrap(),
213                "content": "new content"
214            }))
215            .await;
216
217        assert!(output.is_success());
218
219        let content = std::fs::read_to_string(file.path()).unwrap();
220        assert_eq!(content, "new content");
221    }
222
223    #[tokio::test]
224    async fn test_write_append() {
225        let file = NamedTempFile::new().unwrap();
226        std::fs::write(file.path(), "hello").unwrap();
227
228        let tool = WriteFileTool::new();
229        let output = tool
230            .execute(serde_json::json!({
231                "path": file.path().to_str().unwrap(),
232                "content": " world",
233                "append": true
234            }))
235            .await;
236
237        assert!(output.is_success());
238        assert!(output.content.contains("Appended"));
239
240        let content = std::fs::read_to_string(file.path()).unwrap();
241        assert_eq!(content, "hello world");
242    }
243
244    #[tokio::test]
245    async fn test_write_create_parents() {
246        let dir = tempdir().unwrap();
247        let file_path = dir.path().join("nested").join("dir").join("file.txt");
248
249        let tool = WriteFileTool::new();
250        let output = tool
251            .execute(serde_json::json!({
252                "path": file_path.to_str().unwrap(),
253                "content": "test"
254            }))
255            .await;
256
257        assert!(output.is_success());
258        assert!(file_path.exists());
259    }
260
261    #[tokio::test]
262    async fn test_write_content_too_large() {
263        let dir = tempdir().unwrap();
264        let file_path = dir.path().join("test.txt");
265
266        let tool = WriteFileTool::new().with_max_content_size(10);
267        let output = tool
268            .execute(serde_json::json!({
269                "path": file_path.to_str().unwrap(),
270                "content": "this content is too large"
271            }))
272            .await;
273
274        assert!(output.is_error);
275        assert!(output.content.contains("too large"));
276    }
277
278    #[tokio::test]
279    async fn test_write_invalid_params() {
280        let tool = WriteFileTool::new();
281        let output = tool
282            .execute(serde_json::json!({
283                "path": "/tmp/test.txt"
284            }))
285            .await;
286
287        assert!(output.is_error);
288        assert!(output.content.contains("Invalid parameters"));
289    }
290
291    #[tokio::test]
292    async fn test_write_empty_content() {
293        let dir = tempdir().unwrap();
294        let file_path = dir.path().join("empty.txt");
295
296        let tool = WriteFileTool::new();
297        let output = tool
298            .execute(serde_json::json!({
299                "path": file_path.to_str().unwrap(),
300                "content": ""
301            }))
302            .await;
303
304        assert!(output.is_success());
305        assert!(output.content.contains("0 bytes"));
306    }
307}