tinyharness_lib/tools/
edit.rs1use std::collections::HashMap;
2use std::fs;
3
4use crate::extract_args;
5use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
6
7pub fn edit_tool_entry() -> crate::tools::tool::Tool {
8 make_tool(
9 "edit",
10 "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.",
11 ToolCategory::Destructive,
12 build_string_params_schema(
13 &[
14 ("path", "The absolute path to the file to edit"),
15 (
16 "old_str",
17 "The exact string to find in the file (must appear exactly once)",
18 ),
19 ("new_str", "The replacement string"),
20 ],
21 &[],
22 ),
23 |args| Box::pin(edit_tool(args)),
24 )
25}
26
27pub fn edit_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
28 Box::pin(async move {
29 extract_args!(args, path, old_str, new_str);
30
31 let content = match fs::read_to_string(&path) {
33 Ok(c) => c,
34 Err(e) => return format!("Error: Failed to read file '{}': {}", path, e),
35 };
36
37 let count = content.matches(&old_str).count();
39
40 if count == 0 {
41 return format!(
42 "Error: 'old_str' not found in '{}'. The exact text to replace must appear in the file.",
43 path
44 );
45 }
46
47 if count > 1 {
48 return format!(
49 "Error: 'old_str' appears {} times in '{}'. The old_str must appear exactly once. Found {} occurrences.",
50 count, path, count
51 );
52 }
53
54 let new_content = content.replace(&old_str, &new_str);
56
57 match fs::write(&path, &new_content) {
59 Ok(_) => format!("Edited '{}' ({} chars replaced).", path, old_str.len()),
60 Err(e) => format!("Error: Failed to write file '{}': {}", path, e),
61 }
62 })
63}