use std::path::{Path, PathBuf};
use async_trait::async_trait;
use globset::{Glob, GlobMatcher};
use ignore::WalkBuilder;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const MAX_GLOB_MATCHES: usize = 500;
pub struct GlobTool {
working_dir: PathBuf,
}
impl GlobTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn collect(&self, root: &Path, matcher: &GlobMatcher) -> (Vec<String>, bool) {
let base =
std::fs::canonicalize(&self.working_dir).unwrap_or_else(|_| self.working_dir.clone());
let mut matches = Vec::new();
for entry in WalkBuilder::new(root).hidden(true).build().flatten() {
if entry.file_type().is_some_and(|ft| ft.is_dir()) {
continue;
}
let rel = entry.path().strip_prefix(&base).unwrap_or(entry.path());
if matcher.is_match(rel) {
matches.push(rel.to_string_lossy().into_owned());
}
}
matches.sort();
let truncated = matches.len() > MAX_GLOB_MATCHES;
matches.truncate(MAX_GLOB_MATCHES);
(matches, truncated)
}
fn glob_inner(&self, pattern: &str, sub_path: 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 matcher = Glob::new(pattern)
.map_err(|e| FsError::GlobPattern {
pattern: pattern.to_string(),
reason: e.to_string(),
})?
.compile_matcher();
let (matches, truncated) = self.collect(&root, &matcher);
if matches.is_empty() {
return Ok(format!("no files matched pattern '{pattern}'"));
}
let mut out = matches.join("\n");
if truncated {
out.push_str(&format!(
"\n… (truncated at {MAX_GLOB_MATCHES} matches; refine the pattern)"
));
}
Ok(out)
}
}
#[async_trait]
impl ToolExecutor for GlobTool {
fn name(&self) -> &str {
"glob"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "glob",
"description": "Find files by glob pattern (e.g. '**/*.py', 'src/*.rs'). Returns matching project-relative paths, one per line. Hidden and .gitignore'd files are skipped. Prefer this over shelling out to 'find'.",
"parameters": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Glob pattern to match against project-relative paths. '**' matches any number of directories; '*' matches within a path segment."
},
"path": {
"type": "string",
"description": "Optional subdirectory (relative to the working directory) to scope the search. Defaults to the whole project."
}
},
"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("glob: missing required argument 'pattern'");
};
let sub_path = args.get("path").and_then(Value::as_str);
match self.glob_inner(pattern, sub_path) {
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("a.py"), "x = 1\n").expect("write");
fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
fs::write(tmp.path().join("pkg/b.py"), "y = 2\n").expect("write");
fs::write(tmp.path().join("pkg/c.txt"), "text\n").expect("write");
fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
fs::write(tmp.path().join("src/main.rs"), "fn main() {}\n").expect("write");
}
#[tokio::test]
async fn glob_finds_files_recursively() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GlobTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "**/*.py"})).await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
let out = result.content();
assert!(out.contains("a.py"), "top-level a.py missing: {out}");
assert!(out.contains("pkg/b.py"), "nested pkg/b.py missing: {out}");
assert!(!out.contains("c.txt"), "non-matching c.txt present: {out}");
assert!(
!out.contains("main.rs"),
"non-matching main.rs present: {out}"
);
}
#[tokio::test]
async fn glob_single_level_pattern() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GlobTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "src/*.rs"})).await;
assert!(!result.is_error());
let out = result.content();
assert!(out.contains("src/main.rs"), "src/main.rs missing: {out}");
assert!(
!out.contains("a.py"),
"a.py should not match src/*.rs: {out}"
);
}
#[tokio::test]
async fn glob_scoped_to_subdirectory() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GlobTool::new(tmp.path());
let result = tool
.execute(json!({"pattern": "**/*.py", "path": "pkg"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let out = result.content();
assert!(out.contains("pkg/b.py"), "pkg/b.py missing: {out}");
assert!(!out.contains("a.py"), "a.py is outside scoped path: {out}");
}
#[tokio::test]
async fn glob_no_matches_reports_clearly() {
let tmp = tempfile::tempdir().expect("tempdir");
seed(&tmp);
let tool = GlobTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "**/*.java"})).await;
assert!(!result.is_error());
assert!(
result.content().contains("no files matched"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn glob_path_traversal_is_rejected() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GlobTool::new(tmp.path());
let result = tool
.execute(json!({"pattern": "*", "path": "../../etc"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn glob_bad_pattern_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GlobTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "[unclosed"})).await;
assert!(result.is_error());
assert!(
result.content().contains("glob"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn glob_truncates_large_result_sets() {
let tmp = tempfile::tempdir().expect("tempdir");
for i in 0..(MAX_GLOB_MATCHES + 5) {
fs::write(tmp.path().join(format!("f{i}.py")), "x\n").expect("write");
}
let tool = GlobTool::new(tmp.path());
let result = tool.execute(json!({"pattern": "**/*.py"})).await;
assert!(!result.is_error());
assert!(
result.content().contains("truncated"),
"expected truncation notice"
);
}
#[test]
fn schema_has_required_pattern() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = GlobTool::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"
);
}
}