use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
use tracing::debug;
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
pub struct EditFileTool {
max_file_size: u64,
}
impl EditFileTool {
pub fn new() -> Self {
Self {
max_file_size: MAX_FILE_SIZE,
}
}
pub fn with_max_file_size(mut self, size: u64) -> Self {
self.max_file_size = size;
self
}
}
impl Default for EditFileTool {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Deserialize)]
struct EditFileParams {
path: String,
old_string: String,
new_string: String,
#[serde(default)]
replace_all: bool,
}
#[async_trait]
impl Tool for EditFileTool {
fn name(&self) -> &str {
"edit_file"
}
fn description(&self) -> &str {
"Edit a file by replacing a specific string with new content. \
By default, the old_string must be unique in the file to prevent \
unintended changes. Use replace_all=true to replace all occurrences."
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to edit"
},
"old_string": {
"type": "string",
"description": "The exact text to find and replace"
},
"new_string": {
"type": "string",
"description": "The text to replace old_string with"
},
"replace_all": {
"type": "boolean",
"description": "If true, replace all occurrences. If false (default), old_string must be unique"
}
},
"required": ["path", "old_string", "new_string"]
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let params: EditFileParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
};
let path = Path::new(¶ms.path);
debug!(path = %path.display(), replace_all = params.replace_all, "Editing file");
if params.old_string.is_empty() {
return ToolOutput::error("old_string cannot be empty");
}
if params.old_string == params.new_string {
return ToolOutput::error("old_string and new_string must be different");
}
if !path.exists() {
return ToolOutput::error(format!("File does not exist: {}", params.path));
}
if !path.is_file() {
return ToolOutput::error(format!("Path is not a file: {}", params.path));
}
let metadata = match fs::metadata(path).await {
Ok(m) => m,
Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
};
if metadata.len() > self.max_file_size {
return ToolOutput::error(format!(
"File too large: {} bytes (max: {} bytes)",
metadata.len(),
self.max_file_size
));
}
let content = match fs::read_to_string(path).await {
Ok(c) => c,
Err(e) => return ToolOutput::error(format!("Failed to read file: {}", e)),
};
let occurrences = content.matches(¶ms.old_string).count();
if occurrences == 0 {
return ToolOutput::error(
"old_string not found in file. Make sure the text matches exactly, \
including whitespace and line endings."
);
}
if !params.replace_all && occurrences > 1 {
return ToolOutput::error(format!(
"old_string appears {} times in the file. Use replace_all=true to replace \
all occurrences, or provide a more specific old_string that is unique.",
occurrences
));
}
let old_content = content.clone();
let new_content = if params.replace_all {
content.replace(¶ms.old_string, ¶ms.new_string)
} else {
content.replacen(¶ms.old_string, ¶ms.new_string, 1)
};
if let Err(e) = fs::write(path, &new_content).await {
return ToolOutput::error(format!("Failed to write file: {}", e));
}
let action = if params.replace_all && occurrences > 1 {
format!("Replaced {} occurrences", occurrences)
} else {
"Replaced 1 occurrence".to_string()
};
ToolOutput::success(format!("{} in {}", action, path.display()))
.with_file_change(params.path, Some(old_content), new_content)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_edit_file_tool_name() {
let tool = EditFileTool::new();
assert_eq!(tool.name(), "edit_file");
}
#[test]
fn test_edit_file_schema() {
let tool = EditFileTool::new();
let schema = tool.parameters_schema();
assert_eq!(schema["type"], "object");
assert!(schema["properties"]["path"].is_object());
assert!(schema["properties"]["old_string"].is_object());
assert!(schema["properties"]["new_string"].is_object());
assert_eq!(schema["required"][0], "path");
assert_eq!(schema["required"][1], "old_string");
assert_eq!(schema["required"][2], "new_string");
}
#[tokio::test]
async fn test_edit_simple_replacement() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "World",
"new_string": "Rust"
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
assert!(output.content.contains("Replaced 1 occurrence"));
let content = fs::read_to_string(&file_path).unwrap();
assert_eq!(content, "Hello Rust");
}
#[tokio::test]
async fn test_edit_multiline() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(
&file_path,
"fn main() {\n println!(\"Hello\");\n}\n",
)
.unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": " println!(\"Hello\");",
"new_string": " println!(\"Hello, World!\");"
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
let content = fs::read_to_string(&file_path).unwrap();
assert!(content.contains("Hello, World!"));
}
#[tokio::test]
async fn test_edit_not_unique_fails() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "foo bar foo baz foo").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "foo",
"new_string": "qux"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("3 times"));
assert!(output.content.contains("replace_all=true"));
let content = fs::read_to_string(&file_path).unwrap();
assert_eq!(content, "foo bar foo baz foo");
}
#[tokio::test]
async fn test_edit_replace_all() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "foo bar foo baz foo").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "foo",
"new_string": "qux",
"replace_all": true
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
assert!(output.content.contains("Replaced 3 occurrences"));
let content = fs::read_to_string(&file_path).unwrap();
assert_eq!(content, "qux bar qux baz qux");
}
#[tokio::test]
async fn test_edit_old_string_not_found() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "Goodbye",
"new_string": "Hi"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("not found"));
}
#[tokio::test]
async fn test_edit_empty_old_string() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "",
"new_string": "Hi"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("cannot be empty"));
}
#[tokio::test]
async fn test_edit_same_strings() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "Hello",
"new_string": "Hello"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("must be different"));
}
#[tokio::test]
async fn test_edit_nonexistent_file() {
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": "/nonexistent/path/file.txt",
"old_string": "foo",
"new_string": "bar"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("does not exist"));
}
#[tokio::test]
async fn test_edit_directory_fails() {
let dir = tempdir().unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": dir.path().to_str().unwrap(),
"old_string": "foo",
"new_string": "bar"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("not a file"));
}
#[tokio::test]
async fn test_edit_file_too_large() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World").unwrap();
let tool = EditFileTool::new().with_max_file_size(5);
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "World",
"new_string": "Rust"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("too large"));
}
#[tokio::test]
async fn test_edit_invalid_params() {
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": "/tmp/test.txt"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("Invalid parameters"));
}
#[tokio::test]
async fn test_edit_preserves_other_content() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.rs");
let original = r#"fn main() {
let x = 1;
let y = 2;
println!("{}", x + y);
}
"#;
fs::write(&file_path, original).unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "let y = 2;",
"new_string": "let y = 42;"
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
let content = fs::read_to_string(&file_path).unwrap();
assert!(content.contains("let x = 1;"));
assert!(content.contains("let y = 42;"));
assert!(content.contains("println!"));
}
#[tokio::test]
async fn test_edit_with_special_chars() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Price: $100.00").unwrap();
let tool = EditFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file_path.to_str().unwrap(),
"old_string": "$100.00",
"new_string": "$200.00"
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
let content = fs::read_to_string(&file_path).unwrap();
assert_eq!(content, "Price: $200.00");
}
}