Skip to main content

tinyharness_lib/tools/
grep.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use regex::Regex;
6
7use crate::extract_args;
8use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
9
10pub fn grep_tool_entry() -> crate::tools::tool::Tool {
11    make_tool(
12        "grep",
13        "Search for a regex pattern across files in a directory. Returns matching lines with file paths and line numbers. Use 'include' to filter by file extension (e.g. '.rs' for Rust files). Skips hidden directories, node_modules, target, and binary files.",
14        ToolCategory::ReadOnly,
15        build_string_params_schema(
16            &[("pattern", "The regex pattern to search for")],
17            &[
18                (
19                    "path",
20                    "The directory to search in (defaults to current directory)",
21                    ".",
22                ),
23                (
24                    "include",
25                    "Only search files whose path contains this string (e.g. '.rs' for Rust files)",
26                    "",
27                ),
28            ],
29        ),
30        |args| Box::pin(grep_tool(args)),
31    )
32}
33
34pub fn grep_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
35    Box::pin(async move {
36        extract_args!(args, pattern);
37
38        let path = args.get("path").cloned().unwrap_or_else(|| ".".to_string());
39        let include_pattern = args.get("include").map(|s| s.as_str());
40
41        let regex = match Regex::new(&pattern) {
42            Ok(r) => r,
43            Err(e) => return format!("Error: Invalid regex pattern '{}': {}", pattern, e),
44        };
45
46        let root = Path::new(&path);
47        if !root.exists() {
48            return format!("Error: Path '{}' does not exist", path);
49        }
50        if !root.is_dir() {
51            return format!("Error: '{}' is not a directory", path);
52        }
53
54        let mut results: Vec<String> = Vec::new();
55        let mut total_matches = 0;
56
57        if let Err(e) = walk_dir(
58            root,
59            &regex,
60            include_pattern,
61            &mut results,
62            &mut total_matches,
63        ) {
64            return format!("Error: {}", e);
65        }
66
67        if results.is_empty() {
68            return format!("No matches found for pattern '{}'", pattern);
69        }
70
71        // Limit output to avoid huge responses
72        const MAX_LINES: usize = 200;
73        let mut output = String::new();
74
75        let file_count = results
76            .iter()
77            .map(|line| line.split(':').next().unwrap_or(""))
78            .collect::<std::collections::HashSet<&str>>()
79            .len();
80
81        output.push_str(&format!(
82            "{} matches in {} files\n",
83            total_matches, file_count
84        ));
85
86        for (line_count, line) in results.iter().enumerate() {
87            if line_count >= MAX_LINES {
88                output.push_str(&format!(
89                    "... and {} more (truncated)\n",
90                    total_matches - line_count
91                ));
92                break;
93            }
94            output.push_str(line);
95            output.push('\n');
96        }
97
98        output.trim_end().to_string()
99    })
100}
101
102fn walk_dir(
103    dir: &Path,
104    regex: &Regex,
105    include_pattern: Option<&str>,
106    results: &mut Vec<String>,
107    total_matches: &mut usize,
108) -> Result<(), String> {
109    let entries = match fs::read_dir(dir) {
110        Ok(e) => e,
111        Err(e) => {
112            return Err(format!(
113                "Failed to read directory '{}': {}",
114                dir.display(),
115                e
116            ));
117        }
118    };
119
120    for entry in entries.flatten() {
121        let path = entry.path();
122
123        // Never follow a symlink, in either direction. `path.is_dir()` would
124        // resolve it, so a single link inside the workspace (`link -> /home`)
125        // would let the walker read trees the path guard confined the *root*
126        // argument away from. Skipping them keeps the walk inside the tree the
127        // guard actually authorized.
128        let is_dir = std::fs::symlink_metadata(&path)
129            .map(|m| m.is_dir())
130            .unwrap_or(false);
131        if is_dir {
132            // Skip hidden directories and common non-code directories
133            if let Some(name) = path.file_name().and_then(|n| n.to_str())
134                && (name.starts_with('.') || name == "node_modules" || name == "target")
135            {
136                continue;
137            }
138            walk_dir(&path, regex, include_pattern, results, total_matches)?;
139        } else if std::fs::symlink_metadata(&path)
140            .map(|m| m.is_file())
141            .unwrap_or(false)
142        {
143            // Apply include filter if specified
144            if let Some(inc) = include_pattern
145                && !path.to_string_lossy().contains(inc)
146            {
147                continue;
148            }
149
150            // Skip binary-looking files
151            if let Some(ext) = path.extension().and_then(|e| e.to_str())
152                && matches!(
153                    ext,
154                    "png"
155                        | "jpg"
156                        | "jpeg"
157                        | "gif"
158                        | "bmp"
159                        | "ico"
160                        | "svg"
161                        | "woff"
162                        | "woff2"
163                        | "ttf"
164                        | "eot"
165                        | "otf"
166                        | "pdf"
167                        | "zip"
168                        | "tar"
169                        | "gz"
170                        | "bz2"
171                        | "xz"
172                        | "exe"
173                        | "dll"
174                        | "so"
175                        | "dylib"
176                        | "wasm"
177                        | "o"
178                        | "pyc"
179                        | "class"
180                )
181            {
182                continue;
183            }
184
185            let content = match fs::read_to_string(&path) {
186                Ok(c) => c,
187                Err(_) => continue, // Skip binary files
188            };
189
190            let rel_path = path.to_string_lossy();
191            for (line_num, line) in content.lines().enumerate() {
192                if regex.is_match(line) {
193                    results.push(format!("{}:{}:{}", rel_path, line_num + 1, line));
194                    *total_matches += 1;
195                }
196            }
197        }
198    }
199
200    Ok(())
201}