use std::path::{Path, PathBuf};
use async_trait::async_trait;
use globset::{Glob, GlobMatcher};
use ignore::WalkBuilder;
use regex::Regex;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const MAX_GREP_HITS: usize = 200;
const MAX_GREP_FILE_BYTES: u64 = 1024 * 1024;
pub struct GrepTool {
working_dir: PathBuf,
}
impl GrepTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn collect(&self, root: &Path, re: &Regex, glob: Option<&GlobMatcher>) -> (Vec<String>, bool) {
let base =
std::fs::canonicalize(&self.working_dir).unwrap_or_else(|_| self.working_dir.clone());
let mut hits = Vec::new();
let mut truncated = false;
'walk: for entry in WalkBuilder::new(root).hidden(true).build().flatten() {
if entry.file_type().is_some_and(|ft| ft.is_dir()) {
continue;
}
let path = entry.path();
let rel = path.strip_prefix(&base).unwrap_or(path);
if let Some(g) = glob
&& !g.is_match(rel)
{
continue;
}
if std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_GREP_FILE_BYTES) {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
continue;
};
let rel_display = rel.to_string_lossy();
for (idx, line) in content.lines().enumerate() {
if re.is_match(line) {
if hits.len() >= MAX_GREP_HITS {
truncated = true;
break 'walk;
}
hits.push(format!("{}:{}: {}", rel_display, idx + 1, line.trim_end()));
}
}
}
(hits, truncated)
}
fn grep_inner(
&self,
pattern: &str,
sub_path: Option<&str>,
glob: Option<&str>,
) -> Result<String, FsError> {
let root = match sub_path {
Some(p) => scoped_path(&self.working_dir, Path::new(p))?,
None => scoped_path(&self.working_dir, Path::new("."))?,
};
let re = Regex::new(pattern).map_err(|e| FsError::GrepPattern {
pattern: pattern.to_string(),
reason: e.to_string(),
})?;
let matcher = match glob {
Some(g) => Some(
Glob::new(g)
.map_err(|e| FsError::GlobPattern {
pattern: g.to_string(),
reason: e.to_string(),
})?
.compile_matcher(),
),
None => None,
};
let (hits, truncated) = self.collect(&root, &re, matcher.as_ref());
if hits.is_empty() {
return Ok(format!("no matches for pattern '{pattern}'"));
}
let mut out = hits.join("\n");
if truncated {
out.push_str(&format!(
"\n… (truncated at {MAX_GREP_HITS} matches; refine the pattern)"
));
}
Ok(out)
}
}
#[async_trait]
impl ToolExecutor for GrepTool {
fn name(&self) -> &str {
"grep"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "grep",
"description": "Search file contents by regular expression across the project. Returns matching 'path:line: text' hits, one per line. Hidden and .gitignore'd files are skipped. Prefer this over shelling out to 'grep'.",
"parameters": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Regular expression to match against each line of file contents."
},
"path": {
"type": "string",
"description": "Optional subdirectory (relative to the working directory) to scope the search. Defaults to the whole project."
},
"glob": {
"type": "string",
"description": "Optional glob (e.g. '**/*.py') restricting which files are searched."
}
},
"required": ["pattern"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let Some(pattern) = args.get("pattern").and_then(Value::as_str) else {
return ToolResult::err("grep: missing required argument 'pattern'");
};
let sub_path = args.get("path").and_then(Value::as_str);
let glob = args.get("glob").and_then(Value::as_str);
match self.grep_inner(pattern, sub_path, glob) {
Ok(listing) => ToolResult::ok(listing),
Err(e) => ToolResult::err(e.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use serde_json::json;
use super::*;
use crate::tools::traits::ToolExecutor;
fn seed(tmp: &tempfile::TempDir) {
fs::write(
tmp.path().join("app.py"),
"import os\ndef handler():\n return TODO_FIXME\n",
)
.expect("write");
fs::create_dir_all(tmp.path().join("lib")).expect("mkdir");
fs::write(
tmp.path().join("lib/util.rs"),
"fn helper() {}\n// TODO_FIXME later\n",
)
.expect("write");
}
#[tokio::test]
async fn grep_finds_matching_lines() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GrepTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "TODO_FIXME"})).await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
let out = result.content();
assert!(out.contains("app.py:3:"), "app.py hit missing: {out}");
assert!(out.contains("lib/util.rs:2:"), "util.rs hit missing: {out}");
}
#[tokio::test]
async fn grep_uses_regex_semantics() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GrepTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "^def "})).await;
assert!(!result.is_error());
let out = result.content();
assert!(out.contains("def handler"), "def line missing: {out}");
assert!(
!out.contains("import os"),
"import line must not match: {out}"
);
}
#[tokio::test]
async fn grep_glob_filter_restricts_files() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GrepTool::new(tmp.path());
let result = tool
.execute(json!({"pattern": "TODO_FIXME", "glob": "**/*.rs"}))
.await;
assert!(!result.is_error());
let out = result.content();
assert!(out.contains("lib/util.rs"), "rs hit missing: {out}");
assert!(
!out.contains("app.py"),
"py file must be filtered out: {out}"
);
}
#[tokio::test]
async fn grep_scoped_to_subdirectory() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GrepTool::new(tmp.path());
let result = tool
.execute(json!({"pattern": "TODO_FIXME", "path": "lib"}))
.await;
assert!(!result.is_error());
let out = result.content();
assert!(out.contains("lib/util.rs"), "lib hit missing: {out}");
assert!(!out.contains("app.py"), "app.py is outside scope: {out}");
}
#[tokio::test]
async fn grep_no_matches_reports_clearly() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GrepTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "ZZZ_NOT_PRESENT"})).await;
assert!(!result.is_error());
assert!(
result.content().contains("no matches"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn grep_truncates_large_result_sets() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut content = String::new();
for i in 0..(MAX_GREP_HITS + 5) {
content.push_str(&format!("MATCH_MARKER line {i}\n"));
}
fs::write(tmp.path().join("big.txt"), content).expect("write");
let tool = GrepTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "MATCH_MARKER"})).await;
assert!(!result.is_error(), "{}", result.content());
assert!(
result.content().contains("truncated"),
"expected truncation notice: {}",
result.content()
);
}
#[tokio::test]
async fn grep_bad_regex_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GrepTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "(unclosed"})).await;
assert!(result.is_error());
assert!(
result.content().contains("grep"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn grep_path_traversal_is_rejected() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GrepTool::new(tmp.path());
let result = tool
.execute(json!({"pattern": "x", "path": "../../etc"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[test]
fn schema_has_required_pattern() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GrepTool::new(tmp.path());
let schema = tool.schema();
let required = schema["function"]["parameters"]["required"]
.as_array()
.expect("required array");
assert!(
required.iter().any(|v| v.as_str() == Some("pattern")),
"schema must list 'pattern' as required"
);
}
}