tinyharness_lib/tools/
edit.rs1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use crate::extract_args;
6use crate::path_guard::PathGuard;
7use crate::tools::read::read_string_guarded;
8use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
9
10pub fn edit_tool_entry(guard: Option<PathGuard>) -> crate::tools::tool::Tool {
11 make_tool(
12 "edit",
13 "Edit a file by finding an exact string and replacing it with new text. The old_str must appear exactly once in the file. Use this for targeted edits instead of rewriting the entire file.",
14 ToolCategory::Destructive,
15 build_string_params_schema(
16 &[
17 ("path", "The absolute path to the file to edit"),
18 (
19 "old_str",
20 "The exact string to find in the file (must appear exactly once)",
21 ),
22 ("new_str", "The replacement string"),
23 ],
24 &[],
25 ),
26 move |args| {
27 let guard = guard.clone();
28 Box::pin(edit_tool_inner(args, guard))
29 },
30 )
31}
32
33pub fn edit_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
34 Box::pin(edit_tool_inner(args, None))
35}
36
37async fn edit_tool_inner(args: HashMap<String, String>, guard: Option<PathGuard>) -> String {
38 extract_args!(args, path, old_str, new_str);
39
40 let content = match read_string_guarded(&path, guard.as_ref()) {
42 Ok(c) => c,
43 Err(e) => return format!("Error: Failed to read file '{}': {}", path, e),
44 };
45
46 let count = content.matches(&old_str).count();
48
49 if count == 0 {
50 return format!(
51 "Error: 'old_str' not found in '{}'. The exact text to replace must appear in the file.",
52 path
53 );
54 }
55
56 if count > 1 {
57 return format!(
58 "Error: 'old_str' appears {} times in '{}'. The old_str must appear exactly once. Found {} occurrences.",
59 count, path, count
60 );
61 }
62
63 let new_content = content.replace(&old_str, &new_str);
65
66 let result = match &guard {
68 Some(g) => g.write_contained(Path::new(&path), &new_content),
69 None => fs::write(&path, &new_content).map_err(|e| e.to_string()),
70 };
71 match result {
72 Ok(_) => format!("Edited '{}' ({} chars replaced).", path, old_str.len()),
73 Err(e) => format!("Error: Failed to write file '{}': {}", path, e),
74 }
75}