use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use regex::Regex;
use serde::Deserialize;
use std::path::Path;
use tracing::debug;
use walkdir::WalkDir;
const DEFAULT_MAX_MATCHES: usize = 100;
const DEFAULT_CONTEXT_LINES: usize = 2;
pub struct GrepTool {
max_matches: usize,
context_lines: usize,
}
impl GrepTool {
pub fn new() -> Self {
Self {
max_matches: DEFAULT_MAX_MATCHES,
context_lines: DEFAULT_CONTEXT_LINES,
}
}
pub fn with_max_matches(mut self, max: usize) -> Self {
self.max_matches = max;
self
}
pub fn with_context_lines(mut self, lines: usize) -> Self {
self.context_lines = lines;
self
}
}
impl Default for GrepTool {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Deserialize)]
struct GrepParams {
pattern: String,
path: String,
#[serde(default)]
extension: Option<String>,
#[serde(default)]
case_insensitive: bool,
}
struct Match {
file: String,
line_num: usize,
line: String,
}
#[async_trait]
impl Tool for GrepTool {
fn name(&self) -> &str {
"grep"
}
fn description(&self) -> &str {
"Search for a regex pattern in files. Returns matching lines with file paths \
and line numbers. Can search a single file or recursively search a directory."
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "The regex pattern to search for"
},
"path": {
"type": "string",
"description": "File or directory to search in"
},
"extension": {
"type": "string",
"description": "Optional file extension filter (e.g., 'rs', 'py')"
},
"case_insensitive": {
"type": "boolean",
"description": "Case-insensitive search. Default: false"
}
},
"required": ["pattern", "path"]
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let params: GrepParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
};
let pattern_str = if params.case_insensitive {
format!("(?i){}", params.pattern)
} else {
params.pattern.clone()
};
let regex = match Regex::new(&pattern_str) {
Ok(r) => r,
Err(e) => return ToolOutput::error(format!("Invalid regex pattern: {}", e)),
};
let search_path = Path::new(¶ms.path);
debug!(path = %search_path.display(), pattern = %params.pattern, "Executing grep");
if !search_path.exists() {
return ToolOutput::error(format!("Path does not exist: {}", params.path));
}
let mut matches = Vec::new();
let mut files_searched = 0;
let mut truncated = false;
if search_path.is_file() {
files_searched = 1;
if let Some(file_matches) = search_file(search_path, ®ex) {
for m in file_matches {
matches.push(m);
if matches.len() >= self.max_matches {
truncated = true;
break;
}
}
}
} else {
for entry in WalkDir::new(search_path)
.follow_links(false)
.into_iter()
.filter_map(|e| e.ok())
{
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
if let Some(ref ext) = params.extension {
if path.extension().map(|e| e.to_str().unwrap_or("")) != Some(ext.as_str()) {
continue;
}
}
if is_likely_binary(path) || is_hidden(path) {
continue;
}
files_searched += 1;
if let Some(file_matches) = search_file(path, ®ex) {
for m in file_matches {
matches.push(m);
if matches.len() >= self.max_matches {
truncated = true;
break;
}
}
if truncated {
break;
}
}
}
}
if matches.is_empty() {
return ToolOutput::success(format!(
"No matches found for pattern '{}' in {} files",
params.pattern, files_searched
));
}
let mut output = format!(
"Found {} matches in {} files:\n\n",
matches.len(),
files_searched
);
let mut current_file = String::new();
for m in &matches {
if m.file != current_file {
if !current_file.is_empty() {
output.push('\n');
}
output.push_str(&format!("{}:\n", m.file));
current_file = m.file.clone();
}
output.push_str(&format!(" {}:{}\n", m.line_num, m.line));
}
if truncated {
output.push_str(&format!(
"\n(Results truncated at {} matches)",
self.max_matches
));
}
ToolOutput::success(output)
}
}
fn search_file(path: &Path, regex: &Regex) -> Option<Vec<Match>> {
let content = std::fs::read_to_string(path).ok()?;
let mut matches = Vec::new();
let file_str = path.display().to_string();
for (line_num, line) in content.lines().enumerate() {
if regex.is_match(line) {
matches.push(Match {
file: file_str.clone(),
line_num: line_num + 1,
line: line.to_string(),
});
}
}
if matches.is_empty() {
None
} else {
Some(matches)
}
}
fn is_likely_binary(path: &Path) -> bool {
let binary_extensions = [
"exe", "dll", "so", "dylib", "bin", "o", "a", "obj", "class", "jar", "war", "ear", "pyc",
"pyo", "whl", "egg", "png", "jpg", "jpeg", "gif", "ico", "bmp", "tiff", "webp", "svg",
"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "tar", "gz", "bz2", "xz", "7z",
"rar", "mp3", "mp4", "avi", "mov", "mkv", "wav", "flac", "ttf", "otf", "woff", "woff2",
"eot", "lock",
];
if let Some(ext) = path.extension() {
if let Some(ext_str) = ext.to_str() {
return binary_extensions.contains(&ext_str.to_lowercase().as_str());
}
}
false
}
fn is_hidden(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
.map(|s| s.starts_with('.'))
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_grep_tool_name() {
let tool = GrepTool::new();
assert_eq!(tool.name(), "grep");
}
#[test]
fn test_grep_schema() {
let tool = GrepTool::new();
let schema = tool.parameters_schema();
assert_eq!(schema["type"], "object");
assert!(schema["properties"]["pattern"].is_object());
assert!(schema["properties"]["path"].is_object());
assert_eq!(schema["required"][0], "pattern");
assert_eq!(schema["required"][1], "path");
}
#[tokio::test]
async fn test_grep_single_file() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "line 1\nfind me here\nline 3\nfind me again\n").unwrap();
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "find me",
"path": file_path.to_str().unwrap()
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("Found 2 matches"));
assert!(output.content.contains("find me here"));
assert!(output.content.contains("find me again"));
}
#[tokio::test]
async fn test_grep_directory() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("file1.txt"), "hello world\n").unwrap();
fs::write(dir.path().join("file2.txt"), "goodbye world\n").unwrap();
fs::write(dir.path().join("file3.txt"), "hello again\n").unwrap();
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "hello",
"path": dir.path().to_str().unwrap()
}))
.await;
assert!(output.is_success());
assert!(
output.content.contains("hello world") && output.content.contains("hello again"),
"Expected to find both 'hello' matches. Output: {}",
output.content
);
}
#[tokio::test]
async fn test_grep_with_extension_filter() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("file.rs"), "fn main() {}\n").unwrap();
fs::write(dir.path().join("file.py"), "def main():\n").unwrap();
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "main",
"path": dir.path().to_str().unwrap(),
"extension": "rs"
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
assert!(
output.content.contains("fn main()"),
"Expected to find 'fn main()'. Output: {}",
output.content
);
assert!(output.content.contains("file.rs"));
assert!(!output.content.contains("file.py"));
}
#[tokio::test]
async fn test_grep_case_insensitive() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "Hello World\nhello world\nHELLO WORLD\n").unwrap();
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "hello",
"path": file_path.to_str().unwrap(),
"case_insensitive": true
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("Found 3 matches"));
}
#[tokio::test]
async fn test_grep_no_matches() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("file.txt"), "hello world\n").unwrap();
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "notfound",
"path": dir.path().to_str().unwrap()
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("No matches found"));
}
#[tokio::test]
async fn test_grep_invalid_regex() {
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "[invalid",
"path": "/tmp"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("Invalid regex"));
}
#[tokio::test]
async fn test_grep_nonexistent_path() {
let tool = GrepTool::new();
let output = tool
.execute(serde_json::json!({
"pattern": "test",
"path": "/nonexistent/path/12345"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("does not exist"));
}
#[tokio::test]
async fn test_grep_max_matches() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test.txt");
let content = "match\n".repeat(20);
fs::write(&file_path, content).unwrap();
let tool = GrepTool::new().with_max_matches(5);
let output = tool
.execute(serde_json::json!({
"pattern": "match",
"path": file_path.to_str().unwrap()
}))
.await;
assert!(output.is_success(), "Output: {}", output.content);
let match_count = output.content.matches(":match").count();
assert_eq!(
match_count, 5,
"Expected 5 matches but got {}. Output: {}",
match_count, output.content
);
assert!(
output.content.contains("truncated"),
"Expected 'truncated' in output: {}",
output.content
);
}
#[test]
fn test_is_likely_binary() {
assert!(is_likely_binary(Path::new("file.exe")));
assert!(is_likely_binary(Path::new("image.png")));
assert!(is_likely_binary(Path::new("archive.zip")));
assert!(!is_likely_binary(Path::new("code.rs")));
assert!(!is_likely_binary(Path::new("readme.md")));
}
#[test]
fn test_is_hidden() {
assert!(is_hidden(Path::new(".gitignore")));
assert!(is_hidden(Path::new("path/to/.hidden")));
assert!(!is_hidden(Path::new("normal/path/file.txt")));
assert!(!is_hidden(Path::new(".git/config")));
}
}