1use codive_core::tool::{Tool, ToolOutput};
6use async_trait::async_trait;
7use regex::Regex;
8use serde::Deserialize;
9use std::path::Path;
10use tracing::debug;
11use walkdir::WalkDir;
12
13const DEFAULT_MAX_MATCHES: usize = 100;
15
16const DEFAULT_CONTEXT_LINES: usize = 2;
18
19pub struct GrepTool {
21 max_matches: usize,
23 context_lines: usize,
25}
26
27impl GrepTool {
28 pub fn new() -> Self {
30 Self {
31 max_matches: DEFAULT_MAX_MATCHES,
32 context_lines: DEFAULT_CONTEXT_LINES,
33 }
34 }
35
36 pub fn with_max_matches(mut self, max: usize) -> Self {
38 self.max_matches = max;
39 self
40 }
41
42 pub fn with_context_lines(mut self, lines: usize) -> Self {
44 self.context_lines = lines;
45 self
46 }
47}
48
49impl Default for GrepTool {
50 fn default() -> Self {
51 Self::new()
52 }
53}
54
55#[derive(Debug, Deserialize)]
57struct GrepParams {
58 pattern: String,
60 path: String,
62 #[serde(default)]
64 extension: Option<String>,
65 #[serde(default)]
67 case_insensitive: bool,
68}
69
70struct Match {
72 file: String,
73 line_num: usize,
74 line: String,
75}
76
77#[async_trait]
78impl Tool for GrepTool {
79 fn name(&self) -> &str {
80 "grep"
81 }
82
83 fn description(&self) -> &str {
84 "Search for a regex pattern in files. Returns matching lines with file paths \
85 and line numbers. Can search a single file or recursively search a directory."
86 }
87
88 fn parameters_schema(&self) -> serde_json::Value {
89 serde_json::json!({
90 "type": "object",
91 "properties": {
92 "pattern": {
93 "type": "string",
94 "description": "The regex pattern to search for"
95 },
96 "path": {
97 "type": "string",
98 "description": "File or directory to search in"
99 },
100 "extension": {
101 "type": "string",
102 "description": "Optional file extension filter (e.g., 'rs', 'py')"
103 },
104 "case_insensitive": {
105 "type": "boolean",
106 "description": "Case-insensitive search. Default: false"
107 }
108 },
109 "required": ["pattern", "path"]
110 })
111 }
112
113 async fn execute(&self, params: serde_json::Value) -> ToolOutput {
114 let params: GrepParams = match serde_json::from_value(params) {
116 Ok(p) => p,
117 Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
118 };
119
120 let pattern_str = if params.case_insensitive {
122 format!("(?i){}", params.pattern)
123 } else {
124 params.pattern.clone()
125 };
126
127 let regex = match Regex::new(&pattern_str) {
128 Ok(r) => r,
129 Err(e) => return ToolOutput::error(format!("Invalid regex pattern: {}", e)),
130 };
131
132 let search_path = Path::new(¶ms.path);
133 debug!(path = %search_path.display(), pattern = %params.pattern, "Executing grep");
134
135 if !search_path.exists() {
136 return ToolOutput::error(format!("Path does not exist: {}", params.path));
137 }
138
139 let mut matches = Vec::new();
141 let mut files_searched = 0;
142 let mut truncated = false;
143
144 if search_path.is_file() {
146 files_searched = 1;
148 if let Some(file_matches) = search_file(search_path, ®ex) {
149 for m in file_matches {
150 matches.push(m);
151 if matches.len() >= self.max_matches {
152 truncated = true;
153 break;
154 }
155 }
156 }
157 } else {
158 for entry in WalkDir::new(search_path)
160 .follow_links(false)
161 .into_iter()
162 .filter_map(|e| e.ok())
163 {
164 if !entry.file_type().is_file() {
165 continue;
166 }
167
168 let path = entry.path();
169
170 if let Some(ref ext) = params.extension {
172 if path.extension().map(|e| e.to_str().unwrap_or("")) != Some(ext.as_str()) {
173 continue;
174 }
175 }
176
177 if is_likely_binary(path) || is_hidden(path) {
179 continue;
180 }
181
182 files_searched += 1;
183 if let Some(file_matches) = search_file(path, ®ex) {
184 for m in file_matches {
185 matches.push(m);
186 if matches.len() >= self.max_matches {
187 truncated = true;
188 break;
189 }
190 }
191 if truncated {
192 break;
193 }
194 }
195 }
196 }
197
198 if matches.is_empty() {
200 return ToolOutput::success(format!(
201 "No matches found for pattern '{}' in {} files",
202 params.pattern, files_searched
203 ));
204 }
205
206 let mut output = format!(
207 "Found {} matches in {} files:\n\n",
208 matches.len(),
209 files_searched
210 );
211
212 let mut current_file = String::new();
213 for m in &matches {
214 if m.file != current_file {
215 if !current_file.is_empty() {
216 output.push('\n');
217 }
218 output.push_str(&format!("{}:\n", m.file));
219 current_file = m.file.clone();
220 }
221 output.push_str(&format!(" {}:{}\n", m.line_num, m.line));
222 }
223
224 if truncated {
225 output.push_str(&format!(
226 "\n(Results truncated at {} matches)",
227 self.max_matches
228 ));
229 }
230
231 ToolOutput::success(output)
232 }
233}
234
235fn search_file(path: &Path, regex: &Regex) -> Option<Vec<Match>> {
237 let content = std::fs::read_to_string(path).ok()?;
238
239 let mut matches = Vec::new();
240 let file_str = path.display().to_string();
241
242 for (line_num, line) in content.lines().enumerate() {
243 if regex.is_match(line) {
244 matches.push(Match {
245 file: file_str.clone(),
246 line_num: line_num + 1,
247 line: line.to_string(),
248 });
249 }
250 }
251
252 if matches.is_empty() {
253 None
254 } else {
255 Some(matches)
256 }
257}
258
259fn is_likely_binary(path: &Path) -> bool {
261 let binary_extensions = [
262 "exe", "dll", "so", "dylib", "bin", "o", "a", "obj", "class", "jar", "war", "ear", "pyc",
263 "pyo", "whl", "egg", "png", "jpg", "jpeg", "gif", "ico", "bmp", "tiff", "webp", "svg",
264 "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "tar", "gz", "bz2", "xz", "7z",
265 "rar", "mp3", "mp4", "avi", "mov", "mkv", "wav", "flac", "ttf", "otf", "woff", "woff2",
266 "eot", "lock",
267 ];
268
269 if let Some(ext) = path.extension() {
270 if let Some(ext_str) = ext.to_str() {
271 return binary_extensions.contains(&ext_str.to_lowercase().as_str());
272 }
273 }
274 false
275}
276
277fn is_hidden(path: &Path) -> bool {
280 path.file_name()
281 .and_then(|n| n.to_str())
282 .map(|s| s.starts_with('.'))
283 .unwrap_or(false)
284}
285
286#[cfg(test)]
291mod tests {
292 use super::*;
293 use std::fs;
294 use tempfile::tempdir;
295
296 #[test]
297 fn test_grep_tool_name() {
298 let tool = GrepTool::new();
299 assert_eq!(tool.name(), "grep");
300 }
301
302 #[test]
303 fn test_grep_schema() {
304 let tool = GrepTool::new();
305 let schema = tool.parameters_schema();
306 assert_eq!(schema["type"], "object");
307 assert!(schema["properties"]["pattern"].is_object());
308 assert!(schema["properties"]["path"].is_object());
309 assert_eq!(schema["required"][0], "pattern");
310 assert_eq!(schema["required"][1], "path");
311 }
312
313 #[tokio::test]
314 async fn test_grep_single_file() {
315 let dir = tempdir().unwrap();
316 let file_path = dir.path().join("test.txt");
317 fs::write(&file_path, "line 1\nfind me here\nline 3\nfind me again\n").unwrap();
318
319 let tool = GrepTool::new();
320 let output = tool
321 .execute(serde_json::json!({
322 "pattern": "find me",
323 "path": file_path.to_str().unwrap()
324 }))
325 .await;
326
327 assert!(output.is_success());
328 assert!(output.content.contains("Found 2 matches"));
329 assert!(output.content.contains("find me here"));
330 assert!(output.content.contains("find me again"));
331 }
332
333 #[tokio::test]
334 async fn test_grep_directory() {
335 let dir = tempdir().unwrap();
336 fs::write(dir.path().join("file1.txt"), "hello world\n").unwrap();
337 fs::write(dir.path().join("file2.txt"), "goodbye world\n").unwrap();
338 fs::write(dir.path().join("file3.txt"), "hello again\n").unwrap();
339
340 let tool = GrepTool::new();
341 let output = tool
342 .execute(serde_json::json!({
343 "pattern": "hello",
344 "path": dir.path().to_str().unwrap()
345 }))
346 .await;
347
348 assert!(output.is_success());
349 assert!(
351 output.content.contains("hello world") && output.content.contains("hello again"),
352 "Expected to find both 'hello' matches. Output: {}",
353 output.content
354 );
355 }
356
357 #[tokio::test]
358 async fn test_grep_with_extension_filter() {
359 let dir = tempdir().unwrap();
360 fs::write(dir.path().join("file.rs"), "fn main() {}\n").unwrap();
361 fs::write(dir.path().join("file.py"), "def main():\n").unwrap();
362
363 let tool = GrepTool::new();
364 let output = tool
365 .execute(serde_json::json!({
366 "pattern": "main",
367 "path": dir.path().to_str().unwrap(),
368 "extension": "rs"
369 }))
370 .await;
371
372 assert!(output.is_success(), "Output: {}", output.content);
373 assert!(
374 output.content.contains("fn main()"),
375 "Expected to find 'fn main()'. Output: {}",
376 output.content
377 );
378 assert!(output.content.contains("file.rs"));
379 assert!(!output.content.contains("file.py"));
380 }
381
382 #[tokio::test]
383 async fn test_grep_case_insensitive() {
384 let dir = tempdir().unwrap();
385 let file_path = dir.path().join("test.txt");
386 fs::write(&file_path, "Hello World\nhello world\nHELLO WORLD\n").unwrap();
387
388 let tool = GrepTool::new();
389 let output = tool
390 .execute(serde_json::json!({
391 "pattern": "hello",
392 "path": file_path.to_str().unwrap(),
393 "case_insensitive": true
394 }))
395 .await;
396
397 assert!(output.is_success());
398 assert!(output.content.contains("Found 3 matches"));
399 }
400
401 #[tokio::test]
402 async fn test_grep_no_matches() {
403 let dir = tempdir().unwrap();
404 fs::write(dir.path().join("file.txt"), "hello world\n").unwrap();
405
406 let tool = GrepTool::new();
407 let output = tool
408 .execute(serde_json::json!({
409 "pattern": "notfound",
410 "path": dir.path().to_str().unwrap()
411 }))
412 .await;
413
414 assert!(output.is_success());
415 assert!(output.content.contains("No matches found"));
416 }
417
418 #[tokio::test]
419 async fn test_grep_invalid_regex() {
420 let tool = GrepTool::new();
421 let output = tool
422 .execute(serde_json::json!({
423 "pattern": "[invalid",
424 "path": "/tmp"
425 }))
426 .await;
427
428 assert!(output.is_error);
429 assert!(output.content.contains("Invalid regex"));
430 }
431
432 #[tokio::test]
433 async fn test_grep_nonexistent_path() {
434 let tool = GrepTool::new();
435 let output = tool
436 .execute(serde_json::json!({
437 "pattern": "test",
438 "path": "/nonexistent/path/12345"
439 }))
440 .await;
441
442 assert!(output.is_error);
443 assert!(output.content.contains("does not exist"));
444 }
445
446 #[tokio::test]
447 async fn test_grep_max_matches() {
448 let dir = tempdir().unwrap();
449 let file_path = dir.path().join("test.txt");
450 let content = "match\n".repeat(20);
451 fs::write(&file_path, content).unwrap();
452
453 let tool = GrepTool::new().with_max_matches(5);
454 let output = tool
455 .execute(serde_json::json!({
456 "pattern": "match",
457 "path": file_path.to_str().unwrap()
458 }))
459 .await;
460
461 assert!(output.is_success(), "Output: {}", output.content);
462 let match_count = output.content.matches(":match").count();
464 assert_eq!(
465 match_count, 5,
466 "Expected 5 matches but got {}. Output: {}",
467 match_count, output.content
468 );
469 assert!(
470 output.content.contains("truncated"),
471 "Expected 'truncated' in output: {}",
472 output.content
473 );
474 }
475
476 #[test]
477 fn test_is_likely_binary() {
478 assert!(is_likely_binary(Path::new("file.exe")));
479 assert!(is_likely_binary(Path::new("image.png")));
480 assert!(is_likely_binary(Path::new("archive.zip")));
481 assert!(!is_likely_binary(Path::new("code.rs")));
482 assert!(!is_likely_binary(Path::new("readme.md")));
483 }
484
485 #[test]
486 fn test_is_hidden() {
487 assert!(is_hidden(Path::new(".gitignore")));
488 assert!(is_hidden(Path::new("path/to/.hidden")));
489 assert!(!is_hidden(Path::new("normal/path/file.txt")));
490 assert!(!is_hidden(Path::new(".git/config")));
492 }
493}