1use codive_core::tool::{Tool, ToolOutput};
13use async_trait::async_trait;
14use serde::Deserialize;
15use std::path::Path;
16use tokio::fs;
17use tracing::debug;
18
19const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
21
22pub struct EditFileTool {
24 max_file_size: u64,
26}
27
28impl EditFileTool {
29 pub fn new() -> Self {
31 Self {
32 max_file_size: MAX_FILE_SIZE,
33 }
34 }
35
36 pub fn with_max_file_size(mut self, size: u64) -> Self {
38 self.max_file_size = size;
39 self
40 }
41}
42
43impl Default for EditFileTool {
44 fn default() -> Self {
45 Self::new()
46 }
47}
48
49#[derive(Debug, Deserialize)]
51struct EditFileParams {
52 path: String,
54 old_string: String,
56 new_string: String,
58 #[serde(default)]
61 replace_all: bool,
62}
63
64#[async_trait]
65impl Tool for EditFileTool {
66 fn name(&self) -> &str {
67 "edit_file"
68 }
69
70 fn description(&self) -> &str {
71 "Edit a file by replacing a specific string with new content. \
72 By default, the old_string must be unique in the file to prevent \
73 unintended changes. Use replace_all=true to replace all occurrences."
74 }
75
76 fn parameters_schema(&self) -> serde_json::Value {
77 serde_json::json!({
78 "type": "object",
79 "properties": {
80 "path": {
81 "type": "string",
82 "description": "The path to the file to edit"
83 },
84 "old_string": {
85 "type": "string",
86 "description": "The exact text to find and replace"
87 },
88 "new_string": {
89 "type": "string",
90 "description": "The text to replace old_string with"
91 },
92 "replace_all": {
93 "type": "boolean",
94 "description": "If true, replace all occurrences. If false (default), old_string must be unique"
95 }
96 },
97 "required": ["path", "old_string", "new_string"]
98 })
99 }
100
101 async fn execute(&self, params: serde_json::Value) -> ToolOutput {
102 let params: EditFileParams = match serde_json::from_value(params) {
104 Ok(p) => p,
105 Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
106 };
107
108 let path = Path::new(¶ms.path);
109 debug!(path = %path.display(), replace_all = params.replace_all, "Editing file");
110
111 if params.old_string.is_empty() {
113 return ToolOutput::error("old_string cannot be empty");
114 }
115
116 if params.old_string == params.new_string {
118 return ToolOutput::error("old_string and new_string must be different");
119 }
120
121 if !path.exists() {
123 return ToolOutput::error(format!("File does not exist: {}", params.path));
124 }
125
126 if !path.is_file() {
128 return ToolOutput::error(format!("Path is not a file: {}", params.path));
129 }
130
131 let metadata = match fs::metadata(path).await {
133 Ok(m) => m,
134 Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
135 };
136
137 if metadata.len() > self.max_file_size {
138 return ToolOutput::error(format!(
139 "File too large: {} bytes (max: {} bytes)",
140 metadata.len(),
141 self.max_file_size
142 ));
143 }
144
145 let content = match fs::read_to_string(path).await {
147 Ok(c) => c,
148 Err(e) => return ToolOutput::error(format!("Failed to read file: {}", e)),
149 };
150
151 let occurrences = content.matches(¶ms.old_string).count();
153
154 if occurrences == 0 {
155 return ToolOutput::error(
156 "old_string not found in file. Make sure the text matches exactly, \
157 including whitespace and line endings."
158 );
159 }
160
161 if !params.replace_all && occurrences > 1 {
163 return ToolOutput::error(format!(
164 "old_string appears {} times in the file. Use replace_all=true to replace \
165 all occurrences, or provide a more specific old_string that is unique.",
166 occurrences
167 ));
168 }
169
170 let old_content = content.clone();
172
173 let new_content = if params.replace_all {
175 content.replace(¶ms.old_string, ¶ms.new_string)
176 } else {
177 content.replacen(¶ms.old_string, ¶ms.new_string, 1)
178 };
179
180 if let Err(e) = fs::write(path, &new_content).await {
182 return ToolOutput::error(format!("Failed to write file: {}", e));
183 }
184
185 let action = if params.replace_all && occurrences > 1 {
187 format!("Replaced {} occurrences", occurrences)
188 } else {
189 "Replaced 1 occurrence".to_string()
190 };
191
192 ToolOutput::success(format!("{} in {}", action, path.display()))
193 .with_file_change(params.path, Some(old_content), new_content)
194 }
195}
196
197#[cfg(test)]
202mod tests {
203 use super::*;
204 use std::fs;
205 use tempfile::tempdir;
206
207 #[test]
208 fn test_edit_file_tool_name() {
209 let tool = EditFileTool::new();
210 assert_eq!(tool.name(), "edit_file");
211 }
212
213 #[test]
214 fn test_edit_file_schema() {
215 let tool = EditFileTool::new();
216 let schema = tool.parameters_schema();
217 assert_eq!(schema["type"], "object");
218 assert!(schema["properties"]["path"].is_object());
219 assert!(schema["properties"]["old_string"].is_object());
220 assert!(schema["properties"]["new_string"].is_object());
221 assert_eq!(schema["required"][0], "path");
222 assert_eq!(schema["required"][1], "old_string");
223 assert_eq!(schema["required"][2], "new_string");
224 }
225
226 #[tokio::test]
227 async fn test_edit_simple_replacement() {
228 let dir = tempdir().unwrap();
229 let file_path = dir.path().join("test.txt");
230 fs::write(&file_path, "Hello World").unwrap();
231
232 let tool = EditFileTool::new();
233 let output = tool
234 .execute(serde_json::json!({
235 "path": file_path.to_str().unwrap(),
236 "old_string": "World",
237 "new_string": "Rust"
238 }))
239 .await;
240
241 assert!(output.is_success(), "Output: {}", output.content);
242 assert!(output.content.contains("Replaced 1 occurrence"));
243
244 let content = fs::read_to_string(&file_path).unwrap();
245 assert_eq!(content, "Hello Rust");
246 }
247
248 #[tokio::test]
249 async fn test_edit_multiline() {
250 let dir = tempdir().unwrap();
251 let file_path = dir.path().join("test.txt");
252 fs::write(
253 &file_path,
254 "fn main() {\n println!(\"Hello\");\n}\n",
255 )
256 .unwrap();
257
258 let tool = EditFileTool::new();
259 let output = tool
260 .execute(serde_json::json!({
261 "path": file_path.to_str().unwrap(),
262 "old_string": " println!(\"Hello\");",
263 "new_string": " println!(\"Hello, World!\");"
264 }))
265 .await;
266
267 assert!(output.is_success(), "Output: {}", output.content);
268
269 let content = fs::read_to_string(&file_path).unwrap();
270 assert!(content.contains("Hello, World!"));
271 }
272
273 #[tokio::test]
274 async fn test_edit_not_unique_fails() {
275 let dir = tempdir().unwrap();
276 let file_path = dir.path().join("test.txt");
277 fs::write(&file_path, "foo bar foo baz foo").unwrap();
278
279 let tool = EditFileTool::new();
280 let output = tool
281 .execute(serde_json::json!({
282 "path": file_path.to_str().unwrap(),
283 "old_string": "foo",
284 "new_string": "qux"
285 }))
286 .await;
287
288 assert!(output.is_error);
289 assert!(output.content.contains("3 times"));
290 assert!(output.content.contains("replace_all=true"));
291
292 let content = fs::read_to_string(&file_path).unwrap();
294 assert_eq!(content, "foo bar foo baz foo");
295 }
296
297 #[tokio::test]
298 async fn test_edit_replace_all() {
299 let dir = tempdir().unwrap();
300 let file_path = dir.path().join("test.txt");
301 fs::write(&file_path, "foo bar foo baz foo").unwrap();
302
303 let tool = EditFileTool::new();
304 let output = tool
305 .execute(serde_json::json!({
306 "path": file_path.to_str().unwrap(),
307 "old_string": "foo",
308 "new_string": "qux",
309 "replace_all": true
310 }))
311 .await;
312
313 assert!(output.is_success(), "Output: {}", output.content);
314 assert!(output.content.contains("Replaced 3 occurrences"));
315
316 let content = fs::read_to_string(&file_path).unwrap();
317 assert_eq!(content, "qux bar qux baz qux");
318 }
319
320 #[tokio::test]
321 async fn test_edit_old_string_not_found() {
322 let dir = tempdir().unwrap();
323 let file_path = dir.path().join("test.txt");
324 fs::write(&file_path, "Hello World").unwrap();
325
326 let tool = EditFileTool::new();
327 let output = tool
328 .execute(serde_json::json!({
329 "path": file_path.to_str().unwrap(),
330 "old_string": "Goodbye",
331 "new_string": "Hi"
332 }))
333 .await;
334
335 assert!(output.is_error);
336 assert!(output.content.contains("not found"));
337 }
338
339 #[tokio::test]
340 async fn test_edit_empty_old_string() {
341 let dir = tempdir().unwrap();
342 let file_path = dir.path().join("test.txt");
343 fs::write(&file_path, "Hello World").unwrap();
344
345 let tool = EditFileTool::new();
346 let output = tool
347 .execute(serde_json::json!({
348 "path": file_path.to_str().unwrap(),
349 "old_string": "",
350 "new_string": "Hi"
351 }))
352 .await;
353
354 assert!(output.is_error);
355 assert!(output.content.contains("cannot be empty"));
356 }
357
358 #[tokio::test]
359 async fn test_edit_same_strings() {
360 let dir = tempdir().unwrap();
361 let file_path = dir.path().join("test.txt");
362 fs::write(&file_path, "Hello World").unwrap();
363
364 let tool = EditFileTool::new();
365 let output = tool
366 .execute(serde_json::json!({
367 "path": file_path.to_str().unwrap(),
368 "old_string": "Hello",
369 "new_string": "Hello"
370 }))
371 .await;
372
373 assert!(output.is_error);
374 assert!(output.content.contains("must be different"));
375 }
376
377 #[tokio::test]
378 async fn test_edit_nonexistent_file() {
379 let tool = EditFileTool::new();
380 let output = tool
381 .execute(serde_json::json!({
382 "path": "/nonexistent/path/file.txt",
383 "old_string": "foo",
384 "new_string": "bar"
385 }))
386 .await;
387
388 assert!(output.is_error);
389 assert!(output.content.contains("does not exist"));
390 }
391
392 #[tokio::test]
393 async fn test_edit_directory_fails() {
394 let dir = tempdir().unwrap();
395
396 let tool = EditFileTool::new();
397 let output = tool
398 .execute(serde_json::json!({
399 "path": dir.path().to_str().unwrap(),
400 "old_string": "foo",
401 "new_string": "bar"
402 }))
403 .await;
404
405 assert!(output.is_error);
406 assert!(output.content.contains("not a file"));
407 }
408
409 #[tokio::test]
410 async fn test_edit_file_too_large() {
411 let dir = tempdir().unwrap();
412 let file_path = dir.path().join("test.txt");
413 fs::write(&file_path, "Hello World").unwrap();
414
415 let tool = EditFileTool::new().with_max_file_size(5);
416 let output = tool
417 .execute(serde_json::json!({
418 "path": file_path.to_str().unwrap(),
419 "old_string": "World",
420 "new_string": "Rust"
421 }))
422 .await;
423
424 assert!(output.is_error);
425 assert!(output.content.contains("too large"));
426 }
427
428 #[tokio::test]
429 async fn test_edit_invalid_params() {
430 let tool = EditFileTool::new();
431 let output = tool
432 .execute(serde_json::json!({
433 "path": "/tmp/test.txt"
434 }))
435 .await;
436
437 assert!(output.is_error);
438 assert!(output.content.contains("Invalid parameters"));
439 }
440
441 #[tokio::test]
442 async fn test_edit_preserves_other_content() {
443 let dir = tempdir().unwrap();
444 let file_path = dir.path().join("test.rs");
445 let original = r#"fn main() {
446 let x = 1;
447 let y = 2;
448 println!("{}", x + y);
449}
450"#;
451 fs::write(&file_path, original).unwrap();
452
453 let tool = EditFileTool::new();
454 let output = tool
455 .execute(serde_json::json!({
456 "path": file_path.to_str().unwrap(),
457 "old_string": "let y = 2;",
458 "new_string": "let y = 42;"
459 }))
460 .await;
461
462 assert!(output.is_success(), "Output: {}", output.content);
463
464 let content = fs::read_to_string(&file_path).unwrap();
465 assert!(content.contains("let x = 1;"));
466 assert!(content.contains("let y = 42;"));
467 assert!(content.contains("println!"));
468 }
469
470 #[tokio::test]
471 async fn test_edit_with_special_chars() {
472 let dir = tempdir().unwrap();
473 let file_path = dir.path().join("test.txt");
474 fs::write(&file_path, "Price: $100.00").unwrap();
475
476 let tool = EditFileTool::new();
477 let output = tool
478 .execute(serde_json::json!({
479 "path": file_path.to_str().unwrap(),
480 "old_string": "$100.00",
481 "new_string": "$200.00"
482 }))
483 .await;
484
485 assert!(output.is_success(), "Output: {}", output.content);
486
487 let content = fs::read_to_string(&file_path).unwrap();
488 assert_eq!(content, "Price: $200.00");
489 }
490}