use std::path::{Path, PathBuf};
use async_trait::async_trait;
use serde_json::{json, Value};
use crate::tools::{confine, str_arg, Tool, ToolError};
const SKIP_DIRS: [&str; 8] = [
".git",
".hg",
".svn",
"node_modules",
"target",
".venv",
"venv",
"__pycache__",
];
const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
const MAX_ENTRIES: usize = 50_000;
const SNIFF_BYTES: usize = 8 * 1024;
pub struct SearchFiles {
root: PathBuf,
max_bytes: usize,
}
impl SearchFiles {
pub fn new(root: PathBuf, max_bytes: usize) -> Self {
Self { root, max_bytes }
}
}
struct Query {
pattern: String,
path: String,
target: Target,
file_glob: Option<String>,
context: usize,
mode: Mode,
limit: usize,
offset: usize,
order: Order,
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum Target {
Content,
Files,
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum Mode {
Content,
FilesOnly,
Count,
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum Order {
Discovery,
Modified,
}
impl Query {
fn from_args(args: &Value) -> Result<Self, ToolError> {
let target = match args.get("target").and_then(Value::as_str) {
None | Some("content") => Target::Content,
Some("files") => Target::Files,
Some(other) => {
return Err(ToolError::InvalidArgs(format!(
"`target` is `content` or `files`, not `{other}`"
)))
}
};
let mode = match args.get("output_mode").and_then(Value::as_str) {
None => {
if target == Target::Files {
Mode::FilesOnly
} else {
Mode::Content
}
}
Some("content") => Mode::Content,
Some("files_only") => Mode::FilesOnly,
Some("count") => Mode::Count,
Some(other) => {
return Err(ToolError::InvalidArgs(format!(
"`output_mode` is `content`, `files_only` or `count`, not `{other}`"
)))
}
};
let order = match args.get("order").and_then(Value::as_str) {
None | Some("discovery") => Order::Discovery,
Some("modified") => Order::Modified,
Some(other) => {
return Err(ToolError::InvalidArgs(format!(
"`order` is `discovery` or `modified`, not `{other}`"
)))
}
};
let number = |key: &str, default: i64, low: i64, high: i64| -> Result<usize, ToolError> {
match args.get(key) {
None => Ok(default as usize),
Some(v) => v
.as_i64()
.filter(|n| *n >= low && *n <= high)
.map(|n| n as usize)
.ok_or_else(|| {
ToolError::InvalidArgs(format!("`{key}` is a number from {low} to {high}"))
}),
}
};
Ok(Self {
pattern: str_arg(args, "pattern")?.to_string(),
path: args
.get("path")
.and_then(Value::as_str)
.unwrap_or(".")
.to_string(),
target,
file_glob: args
.get("file_glob")
.and_then(Value::as_str)
.map(str::to_string),
context: number("context", 0, 0, 20)?,
mode,
limit: number(
"limit",
if target == Target::Files { 100 } else { 50 },
1,
5_000,
)?,
offset: number("offset", 0, 0, 1_000_000)?,
order,
})
}
}
struct Found {
path: PathBuf,
shown: String,
modified: Option<std::time::SystemTime>,
}
#[async_trait]
impl Tool for SearchFiles {
fn name(&self) -> &str {
"search_files"
}
fn description(&self) -> &str {
"Find where something is in the workspace, instead of reading files one at a time. \
`target: \"content\"` matches `pattern` as a regular expression against one line at a time and \
answers `path:line:content`; `file_glob` narrows to file names, `context` adds lines either side, \
and `output_mode` picks `content`, `files_only` or `count`. `target: \"files\"` matches file names \
(a glob like `*.rs`, or a plain substring) and answers one path per line, newest first with \
`order: \"modified\"`. `.git`, `node_modules`, `target` and virtualenvs are not walked. Stops at \
`limit` matches and says so; `offset` pages through a wide search."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Regular expression matched against one line at a time (target `content`), or a file-name glob / substring (target `files`)"
},
"path": {
"type": "string",
"description": "Directory to walk, relative to the workspace (default `.`)"
},
"target": {
"type": "string",
"enum": ["content", "files"],
"description": "`content` searches inside files (default); `files` searches file names"
},
"file_glob": {
"type": "string",
"description": "Only files whose name matches this glob, e.g. `*.rs` (target `content`)"
},
"context": {
"type": "integer",
"description": "Lines before and after each match (0-20, default 0)"
},
"output_mode": {
"type": "string",
"enum": ["content", "files_only", "count"],
"description": "`content` prints matching lines, `files_only` one path per file, `count` a per-file histogram"
},
"limit": {
"type": "integer",
"description": "Stop after this many matches (default 50) or files (default 100)"
},
"offset": {
"type": "integer",
"description": "Skip this many matches first, to page through a wide result"
},
"order": {
"type": "string",
"enum": ["discovery", "modified"],
"description": "Walk order (default) or newest-modified first (target `files`)"
}
},
"required": ["pattern"]
})
}
fn describe_call(&self, args: &Value) -> String {
let pattern = args["pattern"].as_str().unwrap_or("?");
let where_ = args["path"].as_str().unwrap_or(".");
if args["target"].as_str() == Some("files") {
return format!("search for files named {pattern} in {where_}");
}
format!("search {where_} for {pattern}")
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let query = Query::from_args(&args)?;
let start = confine(&self.root, &query.path)?;
if !start.is_dir() {
return Err(ToolError::Failed(format!(
"{}: not a directory",
query.path
)));
}
let root = self.root.clone();
let max_bytes = self.max_bytes;
tokio::task::spawn_blocking(move || run(&root, &start, &query, max_bytes))
.await
.map_err(|e| ToolError::Failed(format!("search panicked: {e}")))?
}
}
const NFA_SIZE_LIMIT: usize = 1 << 20;
fn run(root: &Path, start: &Path, query: &Query, max_bytes: usize) -> Result<String, ToolError> {
let matcher = match query.target {
Target::Content => Some(
regex_automata::meta::Regex::builder()
.configure(
regex_automata::meta::Config::new()
.nfa_size_limit(Some(NFA_SIZE_LIMIT))
.dfa_size_limit(Some(NFA_SIZE_LIMIT)),
)
.build(&query.pattern)
.map_err(|e| ToolError::InvalidArgs(format!("`pattern` is not a regex: {e}")))?,
),
Target::Files => None,
};
let mut files = walk(start, root, query.order)?;
if query.order == Order::Modified {
files.sort_by(|a, b| b.modified.cmp(&a.modified).then(a.shown.cmp(&b.shown)));
}
match query.target {
Target::Files => Ok(list_files(files, query)),
Target::Content => Ok(search_content(
files,
matcher.as_ref().expect("a content search has a matcher"),
query,
max_bytes,
)),
}
}
fn walk(start: &Path, root: &Path, order: Order) -> Result<Vec<Found>, ToolError> {
let mut out = Vec::new();
let mut stack = vec![start.to_path_buf()];
let mut looked = 0usize;
while let Some(dir) = stack.pop() {
let entries = match std::fs::read_dir(&dir) {
Ok(entries) => entries,
Err(_) => continue,
};
for entry in entries.flatten() {
looked += 1;
if looked > MAX_ENTRIES {
return Ok(out);
}
let name = entry.file_name().to_string_lossy().into_owned();
let path = entry.path();
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
if !SKIP_DIRS.contains(&name.as_str()) {
stack.push(path);
}
continue;
}
if !kind.is_file() {
continue;
}
let shown = path
.strip_prefix(root)
.unwrap_or(&path)
.display()
.to_string();
let modified = if order == Order::Modified {
entry.metadata().ok().and_then(|m| m.modified().ok())
} else {
None
};
out.push(Found {
path,
shown,
modified,
});
}
}
out.sort_by(|a, b| a.shown.cmp(&b.shown));
Ok(out)
}
fn list_files(files: Vec<Found>, query: &Query) -> String {
let wanted: Vec<&Found> = files
.iter()
.filter(|f| {
let name = f.path.file_name().unwrap_or_default().to_string_lossy();
name_matches(&query.pattern, &name)
})
.collect();
let total = wanted.len();
let page: Vec<&Found> = wanted
.into_iter()
.skip(query.offset)
.take(query.limit)
.collect();
if page.is_empty() {
return format!(
"no file name matches `{}` under {}",
query.pattern,
if query.path.is_empty() {
"."
} else {
&query.path
}
);
}
let mut out: Vec<String> = page.iter().map(|f| f.shown.clone()).collect();
let shown = out.len();
if total > query.offset + shown {
out.push(format!(
"[{} of {total} files — raise `limit` or narrow the pattern]",
query.offset + shown
));
}
out.join("\n")
}
fn search_content(
files: Vec<Found>,
matcher: ®ex_automata::meta::Regex,
query: &Query,
max_bytes: usize,
) -> String {
let budget = max_bytes.saturating_sub(256);
let mut out = String::new();
let mut capped = false;
let mut matches_seen = 0usize; let mut printed = 0usize;
let mut skipped_big = 0usize;
let mut binary = 0usize;
let per_file = query.mode != Mode::Content;
let mut files_printed = 0usize;
'files: for file in files {
if let Some(glob) = &query.file_glob {
let name = file.path.file_name().unwrap_or_default().to_string_lossy();
if !glob_matches(glob, &name) {
continue;
}
}
let Ok(meta) = std::fs::metadata(&file.path) else {
continue;
};
if meta.len() > MAX_FILE_BYTES {
skipped_big += 1;
continue;
}
let Ok(bytes) = std::fs::read(&file.path) else {
continue;
};
let head = &bytes[..bytes.len().min(SNIFF_BYTES)];
if head.contains(&0u8) {
binary += 1;
continue;
}
let text = String::from_utf8_lossy(&bytes);
let lines: Vec<&str> = text.lines().collect();
let hits: Vec<usize> = lines
.iter()
.enumerate()
.filter(|(_, line)| matcher.is_match(line.as_bytes()))
.map(|(i, _)| i)
.collect();
if hits.is_empty() {
continue;
}
if per_file {
if matches_seen + hits.len() <= query.offset {
matches_seen += hits.len();
continue;
}
if files_printed >= query.offset + query.limit {
matches_seen += hits.len();
continue;
}
files_printed += 1;
if files_printed > query.offset {
match query.mode {
Mode::FilesOnly => out.push_str(&format!("{}\n", file.shown)),
Mode::Count => {
out.push_str(&format!("{}:{}\n", file.shown, hits.len()));
}
Mode::Content => {}
}
}
matches_seen += hits.len();
if files_printed >= query.offset + query.limit {
break 'files;
}
continue;
}
for i in &hits {
matches_seen += 1;
if matches_seen <= query.offset {
continue;
}
if printed >= query.limit {
break 'files;
}
if out.len() >= budget {
capped = true;
break 'files;
}
if query.context > 0 {
if !out.is_empty() {
out.push_str("--\n");
}
let from = i.saturating_sub(query.context);
let to = (i + query.context).min(lines.len().saturating_sub(1));
for (j, line) in lines.iter().enumerate().take(to + 1).skip(from) {
let sep = if j == *i { ':' } else { '-' };
out.push_str(&format!("{}{sep}{}{sep}{}\n", file.shown, j + 1, line));
}
} else {
out.push_str(&format!("{}:{}:{}\n", file.shown, i + 1, lines[*i]));
}
printed += 1;
}
}
let mut tail = Vec::new();
if capped {
tail.push(format!(
"[output reached the {max_bytes}-byte cap — narrow the pattern, or page with `offset`]"
));
}
if printed == 0 && !capped && query.mode == Mode::Content {
let mut said = format!(
"no match for `{}` under {}",
query.pattern,
if query.path.is_empty() {
"."
} else {
&query.path
}
);
if let Some(glob) = &query.file_glob {
said.push_str(&format!(" in files named {glob}"));
}
if skipped_big > 0 || binary > 0 {
said.push_str(&format!(
" ({} file(s) over {} KiB and {binary} binary skipped)",
skipped_big,
MAX_FILE_BYTES / 1024
));
}
return said;
}
if printed >= query.limit {
tail.push(format!(
"[stopped at {} matches — more may remain; raise `limit` or narrow the pattern]",
query.limit
));
}
if skipped_big > 0 {
tail.push(format!(
"[{skipped_big} file(s) over {} KiB skipped]",
MAX_FILE_BYTES / 1024
));
}
if binary > 0 {
tail.push(format!("[{binary} binary file(s) skipped]"));
}
let body = out.trim_end().to_string();
if tail.is_empty() {
return body;
}
format!("{body}\n{}", tail.join("\n"))
}
fn name_matches(pattern: &str, name: &str) -> bool {
if pattern.contains(['*', '?']) {
glob_matches(pattern, name)
} else {
name.contains(pattern)
}
}
fn glob_matches(pattern: &str, name: &str) -> bool {
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
let (mut pi, mut ni) = (0usize, 0usize);
let (mut star, mut mark) = (None, 0usize);
while ni < n.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
pi += 1;
ni += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some(pi);
mark = ni;
pi += 1;
} else if let Some(s) = star {
pi = s + 1;
mark += 1;
ni = mark;
} else {
return false;
}
}
while pi < p.len() && p[pi] == '*' {
pi += 1;
}
pi == p.len()
}
#[cfg(test)]
mod tests {
use super::*;
fn tree(files: &[(&str, &str)]) -> tempdir_lite::Dir {
let dir = tempdir_lite::Dir::new();
for (path, body) in files {
let full = dir.path().join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(full, body).unwrap();
}
dir
}
async fn search(dir: &tempdir_lite::Dir, args: Value) -> String {
SearchFiles::new(dir.path().to_path_buf(), 60_000)
.call(args)
.await
.unwrap()
}
#[tokio::test]
async fn a_pattern_whose_nfa_is_too_large_is_refused() {
let dir = tree(&[("a.txt", "hello\n")]);
let pattern = "(?s).{1,2000}".to_string();
let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
.call(serde_json::json!({"pattern": pattern}))
.await
.expect_err("the NFA cap refuses it");
let message = err.to_string();
assert!(
message.contains("not a regex"),
"it is reported as the bad argument it is: {message}"
);
}
#[tokio::test]
async fn a_pattern_is_found_with_its_line_and_a_glob_narrows_it() {
let dir = tree(&[
("a.rs", "fn main() {}\nlet needle = 1;\n"),
("b.md", "the needle is here too\n"),
("sub/c.rs", "// needle in a subdirectory\n"),
]);
let all = search(&dir, json!({"pattern": "needle"})).await;
assert!(all.contains("a.rs:2:let needle = 1;"), "{all}");
assert!(all.contains("b.md:1:the needle is here too"), "{all}");
assert!(
all.contains(&format!("sub{}c.rs:1", std::path::MAIN_SEPARATOR)),
"{all}"
);
let narrow = search(&dir, json!({"pattern": "needle", "file_glob": "*.rs"})).await;
assert!(!narrow.contains("b.md"), "{narrow}");
assert!(narrow.contains("a.rs:2"), "{narrow}");
assert!(narrow.contains("c.rs:1"), "{narrow}");
}
#[tokio::test]
async fn the_ignored_directories_are_not_walked_and_the_workspace_is_the_fence() {
let dir = tree(&[
("src/a.rs", "needle\n"),
("target/debug/junk.rs", "needle\n"),
("node_modules/pkg/index.js", "needle\n"),
]);
let found = search(&dir, json!({"pattern": "needle"})).await;
assert!(found.contains("a.rs:1"), "{found}");
assert!(!found.contains("target"), "{found}");
assert!(!found.contains("node_modules"), "{found}");
let outside = SearchFiles::new(dir.path().to_path_buf(), 60_000)
.call(json!({"pattern": "needle", "path": "../.."}))
.await;
assert!(outside.is_err(), "a path above the workspace is refused");
}
#[tokio::test]
async fn a_limit_is_reported_rather_than_silently_short() {
let body: String = (1..=80).map(|i| format!("needle {i}\n")).collect();
let dir = tree(&[("big.txt", &body)]);
let page = search(&dir, json!({"pattern": "needle", "limit": 5})).await;
assert_eq!(page.matches("needle ").count(), 5, "{page}");
assert!(page.contains("stopped at 5 matches"), "{page}");
let next = search(&dir, json!({"pattern": "needle", "limit": 5, "offset": 5})).await;
assert!(next.starts_with("big.txt:6:needle 6"), "{next}");
}
#[tokio::test]
async fn context_lines_come_with_the_match_and_are_not_confused_with_it() {
let dir = tree(&[("a.txt", "one\ntwo\nneedle\nfour\nfive\n")]);
let with = search(&dir, json!({"pattern": "needle", "context": 1})).await;
assert!(with.contains("a.txt-2-two"), "{with}");
assert!(with.contains("a.txt:3:needle"), "{with}");
assert!(with.contains("a.txt-4-four"), "{with}");
assert!(!with.contains("one"), "{with}");
}
#[tokio::test]
async fn files_are_found_by_name_and_count_says_how_many_times() {
let dir = tree(&[
("a.rs", "needle\nneedle\n"),
("b.rs", "needle\n"),
("c.md", "nothing\n"),
]);
let names = search(&dir, json!({"target": "files", "pattern": "*.rs"})).await;
assert_eq!(
names.lines().filter(|l| l.ends_with(".rs")).count(),
2,
"{names}"
);
assert!(!names.contains("c.md"), "{names}");
let histogram = search(&dir, json!({"pattern": "needle", "output_mode": "count"})).await;
assert!(histogram.contains("a.rs:2"), "{histogram}");
assert!(histogram.contains("b.rs:1"), "{histogram}");
assert!(!histogram.contains("c.md"), "{histogram}");
let only = search(
&dir,
json!({"pattern": "needle", "output_mode": "files_only"}),
)
.await;
assert_eq!(
only.lines().filter(|l| l.ends_with(".rs")).count(),
2,
"{only}"
);
}
#[tokio::test]
async fn a_pattern_that_is_not_a_regex_is_refused_by_name_and_nothing_is_walked() {
let dir = tree(&[("a.txt", "x\n")]);
let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
.call(json!({"pattern": "a(b"}))
.await
.unwrap_err();
assert!(err.to_string().contains("not a regex"), "{err}");
}
#[tokio::test]
async fn binary_files_are_skipped_and_said_to_be() {
let dir = tree(&[("a.txt", "needle\n")]);
std::fs::write(dir.path().join("blob.bin"), b"needle\x00\x01\x02").unwrap();
let found = search(&dir, json!({"pattern": "needle"})).await;
assert!(found.contains("a.txt:1"), "{found}");
assert!(!found.contains("blob.bin"), "{found}");
}
#[test]
fn two_directories_made_together_are_two_directories() {
let dirs: Vec<tempdir_lite::Dir> = (0..200).map(|_| tempdir_lite::Dir::new()).collect();
let mut seen: Vec<&std::path::Path> = dirs.iter().map(|d| d.path()).collect();
seen.sort();
seen.dedup();
assert_eq!(seen.len(), 200, "every path is its own");
for d in &dirs {
assert!(
d.path().is_dir(),
"and every one is there: {}",
d.path().display()
);
}
}
#[test]
fn a_glob_matches_a_name_the_way_a_person_writes_it() {
assert!(glob_matches("*.rs", "main.rs"));
assert!(glob_matches("m?in.rs", "main.rs"));
assert!(glob_matches("*.tar.gz", "a.tar.gz"));
assert!(!glob_matches("*.rs", "main.rss"));
assert!(!glob_matches("a*b*c", "abcx"));
assert!(!name_matches("cargo", "Cargo.toml"));
assert!(name_matches("Cargo", "Cargo.toml"));
}
}
#[cfg(test)]
mod tempdir_lite {
pub struct Dir(std::path::PathBuf);
impl Dir {
pub fn new() -> Self {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut path = std::env::temp_dir();
let tag: u64 = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
^ (std::process::id() as u64) << 32;
path.push(format!("eclipse-search-{tag:x}-{seq}"));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
pub fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}