Skip to main content

matrixcode_core/tools/
grep.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use super::{Tool, ToolDefinition};
6
7/// Grep search options bundled into a single struct.
8struct GrepOptions {
9    pattern: String,
10    path: String,
11    glob_pattern: Option<String>,
12    file_type: Option<String>,
13    output_mode: String,
14    case_insensitive: bool,
15    show_line_numbers: bool,
16    context_lines: usize,
17    head_limit: usize,
18}
19
20impl GrepOptions {
21    fn from_params(params: &Value) -> Result<Self> {
22        let pattern = params["pattern"]
23            .as_str()
24            .ok_or_else(|| anyhow::anyhow!("missing 'pattern'"))?
25            .to_string();
26        let path = params["path"].as_str().unwrap_or(".").to_string();
27        let glob_pattern = params["glob"].as_str().map(|s| s.to_string());
28        let file_type = params["type"].as_str().map(|s| s.to_string());
29        let output_mode = params["output_mode"]
30            .as_str()
31            .unwrap_or("content")
32            .to_string();
33        let case_insensitive = params["-i"].as_bool().unwrap_or(false);
34        let show_line_numbers = params["-n"].as_bool().unwrap_or(true);
35        let context_lines = params["-C"].as_u64().unwrap_or(0) as usize;
36        let head_limit = params["head_limit"].as_u64().unwrap_or(100) as usize;
37
38        Ok(Self {
39            pattern,
40            path,
41            glob_pattern,
42            file_type,
43            output_mode,
44            case_insensitive,
45            show_line_numbers,
46            context_lines,
47            head_limit,
48        })
49    }
50}
51
52/// High-performance grep tool with advanced filtering options
53pub struct GrepTool;
54
55#[async_trait]
56impl Tool for GrepTool {
57    fn definition(&self) -> ToolDefinition {
58        ToolDefinition {
59            name: "grep".to_string(),
60            description: "高性能内容搜索工具,适用于任意规模代码库。支持正则表达式、文件类型过滤和多种输出模式。".to_string(),
61            parameters: json!({
62                "type": "object",
63                "properties": {
64                    "pattern": {
65                        "type": "string",
66                        "description": "要搜索的正则表达式模式"
67                    },
68                    "path": {
69                        "type": "string",
70                        "description": "搜索的文件或目录(默认当前目录)"
71                    },
72                    "glob": {
73                        "type": "string",
74                        "description": "Glob 文件过滤模式(如 '*.ts'、'**/*.rs')"
75                    },
76                    "type": {
77                        "type": "string",
78                        "enum": ["js", "ts", "py", "rs", "go", "java", "c", "cpp", "md", "json", "yaml", "html", "css"],
79                        "description": "按文件类型搜索(映射到常用扩展名)"
80                    },
81                    "output_mode": {
82                        "type": "string",
83                        "enum": ["content", "files_with_matches", "count"],
84                        "default": "content",
85                        "description": "输出模式:'content' 显示匹配行,'files_with_matches' 列出文件,'count' 显示匹配数"
86                    },
87                    "-i": {
88                        "type": "boolean",
89                        "default": false,
90                        "description": "忽略大小写"
91                    },
92                    "-n": {
93                        "type": "boolean",
94                        "default": true,
95                        "description": "显示行号"
96                    },
97                    "-C": {
98                        "type": "integer",
99                        "default": 0,
100                        "description": "匹配行前后显示的上下文行数"
101                    },
102                    "head_limit": {
103                        "type": "integer",
104                        "default": 100,
105                        "description": "最大返回结果数"
106                    }
107                },
108                "required": ["pattern"]
109            }),
110        }
111    }
112
113    async fn execute(&self, params: Value) -> Result<String> {
114        let opts = GrepOptions::from_params(&params)?;
115
116        tokio::task::spawn_blocking(move || grep_search(&opts)).await?
117    }
118}
119
120/// File type to extension mapping
121fn get_extensions_for_type(file_type: &str) -> Vec<&'static str> {
122    match file_type {
123        "js" => vec!["js", "jsx", "mjs", "cjs"],
124        "ts" => vec!["ts", "tsx", "mts", "cts"],
125        "py" => vec!["py", "pyw", "pyi"],
126        "rs" => vec!["rs"],
127        "go" => vec!["go"],
128        "java" => vec!["java"],
129        "c" => vec!["c", "h"],
130        "cpp" => vec!["cpp", "cc", "cxx", "hpp", "hh", "hxx"],
131        "md" => vec!["md", "markdown"],
132        "json" => vec!["json", "json5", "jsonc"],
133        "yaml" => vec!["yaml", "yml"],
134        "html" => vec!["html", "htm", "xhtml"],
135        "css" => vec!["css", "scss", "sass", "less"],
136        _ => vec![],
137    }
138}
139
140fn grep_search(opts: &GrepOptions) -> Result<String> {
141    use std::fs;
142    use std::path::Path;
143
144    // Build regex with case-insensitive option
145    let regex_pattern = if opts.case_insensitive {
146        regex::RegexBuilder::new(&opts.pattern)
147            .case_insensitive(true)
148            .build()?
149    } else {
150        regex::Regex::new(&opts.pattern)?
151    };
152
153    let root = Path::new(&opts.path);
154    let mut results: Vec<String> = Vec::new();
155    let mut match_count = 0;
156    let mut files_with_matches: Vec<String> = Vec::new();
157
158    // Get file extensions for type filter
159    let type_extensions = opts.file_type.as_deref().map(get_extensions_for_type);
160
161    let entries = collect_grep_files(
162        root,
163        opts.glob_pattern.as_deref(),
164        type_extensions.as_deref(),
165    )?;
166
167    for file_path in entries {
168        if results.len() >= opts.head_limit && opts.output_mode == "content" {
169            results.push(format!("... (limited to {} results)", opts.head_limit));
170            break;
171        }
172
173        let content = match fs::read_to_string(&file_path) {
174            Ok(c) => c,
175            Err(_) => continue,
176        };
177
178        let lines: Vec<&str> = content.lines().collect();
179        let mut file_has_match = false;
180        let mut file_match_count = 0;
181
182        for (line_idx, line) in lines.iter().enumerate() {
183            if regex_pattern.is_match(line) {
184                file_has_match = true;
185                file_match_count += 1;
186                match_count += 1;
187
188                if opts.output_mode == "content" && results.len() < opts.head_limit {
189                    // Add context lines before the match
190                    if opts.context_lines > 0 {
191                        let start_ctx = line_idx.saturating_sub(opts.context_lines);
192                        for (ctx_idx, ctx_line) in lines
193                            .iter()
194                            .enumerate()
195                            .skip(start_ctx)
196                            .take(line_idx - start_ctx)
197                        {
198                            results.push(format_line(
199                                &file_path,
200                                ctx_idx + 1,
201                                ctx_line,
202                                opts.show_line_numbers,
203                                true,
204                            ));
205                        }
206                    }
207
208                    // Add the matching line
209                    results.push(format_line(
210                        &file_path,
211                        line_idx + 1,
212                        line,
213                        opts.show_line_numbers,
214                        false,
215                    ));
216
217                    // Add context lines after the match
218                    if opts.context_lines > 0 {
219                        let end_ctx = (line_idx + opts.context_lines).min(lines.len() - 1);
220                        for (ctx_idx, ctx_line) in lines
221                            .iter()
222                            .enumerate()
223                            .skip(line_idx + 1)
224                            .take(end_ctx - line_idx)
225                        {
226                            results.push(format_line(
227                                &file_path,
228                                ctx_idx + 1,
229                                ctx_line,
230                                opts.show_line_numbers,
231                                true,
232                            ));
233                        }
234                    }
235                }
236            }
237        }
238
239        if file_has_match && opts.output_mode == "files_with_matches" {
240            files_with_matches.push(file_path.display().to_string());
241        }
242
243        if opts.output_mode == "count" && file_match_count > 0 {
244            results.push(format!(
245                "{}: {} matches",
246                file_path.display(),
247                file_match_count
248            ));
249        }
250    }
251
252    // Format output based on mode
253    match opts.output_mode.as_str() {
254        "files_with_matches" => {
255            if files_with_matches.is_empty() {
256                Ok("No files matched.".to_string())
257            } else {
258                Ok(files_with_matches.join("\n"))
259            }
260        }
261        "count" => {
262            if results.is_empty() {
263                Ok("No matches found.".to_string())
264            } else {
265                Ok(format!(
266                    "Total: {} matches\n{}",
267                    match_count,
268                    results.join("\n")
269                ))
270            }
271        }
272        _ => {
273            // content
274            if results.is_empty() {
275                Ok("No matches found.".to_string())
276            } else {
277                Ok(results.join("\n"))
278            }
279        }
280    }
281}
282
283/// Format a single line with optional line number and context marker.
284fn format_line(
285    file_path: &std::path::Path,
286    line_num: usize,
287    line: &str,
288    show_line_numbers: bool,
289    is_context: bool,
290) -> String {
291    let marker = if is_context { "-" } else { ":" };
292    if show_line_numbers {
293        format!(
294            "{}:{}{} {}",
295            file_path.display(),
296            line_num,
297            marker,
298            line.trim()
299        )
300    } else {
301        format!("{}{} {}", file_path.display(), marker, line.trim())
302    }
303}
304
305fn collect_grep_files(
306    root: &std::path::Path,
307    glob_pattern: Option<&str>,
308    type_extensions: Option<&[&str]>,
309) -> Result<Vec<std::path::PathBuf>> {
310    let mut files = Vec::new();
311
312    if root.is_file() {
313        files.push(root.to_path_buf());
314        return Ok(files);
315    }
316
317    // Build glob matcher
318    let glob_matcher = glob_pattern.map(glob::Pattern::new).transpose()?;
319
320    let walker = walkdir_grep(root)?;
321
322    for entry in walker {
323        let path = entry;
324
325        // Check glob pattern
326        if let Some(ref matcher) = glob_matcher {
327            let relative = path.strip_prefix(root).unwrap_or(&path);
328            let relative_str = relative.to_string_lossy();
329            if !matcher.matches(&relative_str) {
330                // Also try just the filename
331                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
332                    if !matcher.matches(name) {
333                        continue;
334                    }
335                } else {
336                    continue;
337                }
338            }
339        }
340
341        // Check file type extensions
342        if let Some(extensions) = type_extensions {
343            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
344            if !extensions.contains(&ext) {
345                continue;
346            }
347        }
348
349        files.push(path);
350    }
351
352    Ok(files)
353}
354
355fn walkdir_grep(root: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
356    use std::fs;
357
358    let mut files = Vec::new();
359    let mut stack = vec![root.to_path_buf()];
360
361    // Directories to skip
362    const SKIP_DIRS: &[&str] = &[
363        ".git",
364        ".svn",
365        ".hg",
366        "node_modules",
367        "vendor",
368        "target",
369        "build",
370        "dist",
371        "out",
372        ".cache",
373        ".npm",
374        ".cargo",
375        "__pycache__",
376        ".venv",
377        "venv",
378        ".idea",
379        ".vscode",
380    ];
381
382    while let Some(dir) = stack.pop() {
383        let entries = match fs::read_dir(&dir) {
384            Ok(e) => e,
385            Err(_) => continue,
386        };
387
388        for entry in entries.flatten() {
389            let path = entry.path();
390            let name = entry.file_name();
391            let name_str = name.to_string_lossy();
392
393            // Skip hidden files and known directories
394            if name_str.starts_with('.') || SKIP_DIRS.contains(&name_str.as_ref()) {
395                continue;
396            }
397
398            if path.is_dir() {
399                stack.push(path);
400            } else if path.is_file() {
401                files.push(path);
402            }
403        }
404    }
405
406    Ok(files)
407}