Skip to main content

eclipse_core/
tools_search.rs

1//! `search_files`: find where a pattern appears, without reading files one at a time.
2//!
3//! Two targets, one tool, because they answer the same question — "where is this?" — and a model
4//! that has to choose between `search_files` and `find_files` chooses wrong at least once a
5//! session:
6//!
7//! - `target: "content"` (the default) walks the tree and matches `pattern` as a **regular
8//!   expression against one line at a time**, printing `path:line:content`.
9//! - `target: "files"` matches file **names** — a glob (`*.rs`) or, when the pattern has no glob
10//!   characters in it, a substring.
11//!
12//! The walk is rooted at the workspace the way [`read_file`](crate::tools::ReadFile) is: one
13//! [`confine`] call, so a search cannot reach a path a read would be refused. It is also bounded
14//! in three places — matches (`limit`), files visited, and bytes per file — because a pattern
15//! that matches everything is the normal case (`fn `) and an unbounded answer is a context bill,
16//! not a result. Whatever the bound cuts is reported: a search that says "stopped at 50" is
17//! usable, one that quietly returns the first 50 is a lie.
18
19use std::path::{Path, PathBuf};
20
21use async_trait::async_trait;
22use serde_json::{json, Value};
23
24use crate::tools::{confine, str_arg, Tool, ToolError};
25
26/// Directories a search never enters. Not configurable on purpose: a `target/` walk is 30 seconds
27/// of a tool call and `node_modules` is the same, and the answer to "why is my search slow" should
28/// not be a config key.
29const SKIP_DIRS: [&str; 8] = [
30    ".git",
31    ".hg",
32    ".svn",
33    "node_modules",
34    "target",
35    ".venv",
36    "venv",
37    "__pycache__",
38];
39
40/// Files larger than this are skipped and counted. A 40 MB log is not what a search is for, and
41/// reading it to find that out costs more than the search.
42const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
43
44/// How many directory entries one search may look at. A backstop against a tree that is not a
45/// workspace (a home directory, a mount of the whole disk); the cap is reported like the others.
46const MAX_ENTRIES: usize = 50_000;
47
48/// The first bytes of a file are checked for NUL: a binary match is noise, and rendering it as
49/// text floods the answer with replacement characters.
50const SNIFF_BYTES: usize = 8 * 1024;
51
52pub struct SearchFiles {
53    root: PathBuf,
54    max_bytes: usize,
55}
56
57impl SearchFiles {
58    pub fn new(root: PathBuf, max_bytes: usize) -> Self {
59        Self { root, max_bytes }
60    }
61}
62
63/// What the call asked for, after the defaults are filled in.
64struct Query {
65    pattern: String,
66    path: String,
67    target: Target,
68    file_glob: Option<String>,
69    context: usize,
70    mode: Mode,
71    limit: usize,
72    offset: usize,
73    order: Order,
74}
75
76#[derive(PartialEq, Eq, Clone, Copy)]
77enum Target {
78    Content,
79    Files,
80}
81
82#[derive(PartialEq, Eq, Clone, Copy)]
83enum Mode {
84    Content,
85    FilesOnly,
86    Count,
87}
88
89#[derive(PartialEq, Eq, Clone, Copy)]
90enum Order {
91    Discovery,
92    Modified,
93}
94
95impl Query {
96    fn from_args(args: &Value) -> Result<Self, ToolError> {
97        let target = match args.get("target").and_then(Value::as_str) {
98            None | Some("content") => Target::Content,
99            Some("files") => Target::Files,
100            Some(other) => {
101                return Err(ToolError::InvalidArgs(format!(
102                    "`target` is `content` or `files`, not `{other}`"
103                )))
104            }
105        };
106        let mode = match args.get("output_mode").and_then(Value::as_str) {
107            None => {
108                if target == Target::Files {
109                    Mode::FilesOnly
110                } else {
111                    Mode::Content
112                }
113            }
114            Some("content") => Mode::Content,
115            Some("files_only") => Mode::FilesOnly,
116            Some("count") => Mode::Count,
117            Some(other) => {
118                return Err(ToolError::InvalidArgs(format!(
119                    "`output_mode` is `content`, `files_only` or `count`, not `{other}`"
120                )))
121            }
122        };
123        let order = match args.get("order").and_then(Value::as_str) {
124            None | Some("discovery") => Order::Discovery,
125            Some("modified") => Order::Modified,
126            Some(other) => {
127                return Err(ToolError::InvalidArgs(format!(
128                    "`order` is `discovery` or `modified`, not `{other}`"
129                )))
130            }
131        };
132        let number = |key: &str, default: i64, low: i64, high: i64| -> Result<usize, ToolError> {
133            match args.get(key) {
134                None => Ok(default as usize),
135                Some(v) => v
136                    .as_i64()
137                    .filter(|n| *n >= low && *n <= high)
138                    .map(|n| n as usize)
139                    .ok_or_else(|| {
140                        ToolError::InvalidArgs(format!("`{key}` is a number from {low} to {high}"))
141                    }),
142            }
143        };
144        Ok(Self {
145            pattern: str_arg(args, "pattern")?.to_string(),
146            path: args
147                .get("path")
148                .and_then(Value::as_str)
149                .unwrap_or(".")
150                .to_string(),
151            target,
152            file_glob: args
153                .get("file_glob")
154                .and_then(Value::as_str)
155                .map(str::to_string),
156            context: number("context", 0, 0, 20)?,
157            mode,
158            limit: number(
159                "limit",
160                if target == Target::Files { 100 } else { 50 },
161                1,
162                5_000,
163            )?,
164            offset: number("offset", 0, 0, 1_000_000)?,
165            order,
166        })
167    }
168}
169
170/// One file found by the walk, with what the caller may need about it.
171struct Found {
172    path: PathBuf,
173    /// Relative to the search root, which is how every line of output is spelled.
174    shown: String,
175    modified: Option<std::time::SystemTime>,
176}
177
178#[async_trait]
179impl Tool for SearchFiles {
180    fn name(&self) -> &str {
181        "search_files"
182    }
183
184    fn description(&self) -> &str {
185        "Find where something is in the workspace, instead of reading files one at a time. \
186`target: \"content\"` matches `pattern` as a regular expression against one line at a time and \
187answers `path:line:content`; `file_glob` narrows to file names, `context` adds lines either side, \
188and `output_mode` picks `content`, `files_only` or `count`. `target: \"files\"` matches file names \
189(a glob like `*.rs`, or a plain substring) and answers one path per line, newest first with \
190`order: \"modified\"`. `.git`, `node_modules`, `target` and virtualenvs are not walked. Stops at \
191`limit` matches and says so; `offset` pages through a wide search."
192    }
193
194    fn parameters(&self) -> Value {
195        json!({
196            "type": "object",
197            "properties": {
198                "pattern": {
199                    "type": "string",
200                    "description": "Regular expression matched against one line at a time (target `content`), or a file-name glob / substring (target `files`)"
201                },
202                "path": {
203                    "type": "string",
204                    "description": "Directory to walk, relative to the workspace (default `.`)"
205                },
206                "target": {
207                    "type": "string",
208                    "enum": ["content", "files"],
209                    "description": "`content` searches inside files (default); `files` searches file names"
210                },
211                "file_glob": {
212                    "type": "string",
213                    "description": "Only files whose name matches this glob, e.g. `*.rs` (target `content`)"
214                },
215                "context": {
216                    "type": "integer",
217                    "description": "Lines before and after each match (0-20, default 0)"
218                },
219                "output_mode": {
220                    "type": "string",
221                    "enum": ["content", "files_only", "count"],
222                    "description": "`content` prints matching lines, `files_only` one path per file, `count` a per-file histogram"
223                },
224                "limit": {
225                    "type": "integer",
226                    "description": "Stop after this many matches (default 50) or files (default 100)"
227                },
228                "offset": {
229                    "type": "integer",
230                    "description": "Skip this many matches first, to page through a wide result"
231                },
232                "order": {
233                    "type": "string",
234                    "enum": ["discovery", "modified"],
235                    "description": "Walk order (default) or newest-modified first (target `files`)"
236                }
237            },
238            "required": ["pattern"]
239        })
240    }
241
242    fn describe_call(&self, args: &Value) -> String {
243        let pattern = args["pattern"].as_str().unwrap_or("?");
244        let where_ = args["path"].as_str().unwrap_or(".");
245        if args["target"].as_str() == Some("files") {
246            return format!("search for files named {pattern} in {where_}");
247        }
248        format!("search {where_} for {pattern}")
249    }
250
251    async fn call(&self, args: Value) -> Result<String, ToolError> {
252        let query = Query::from_args(&args)?;
253        let start = confine(&self.root, &query.path)?;
254        if !start.is_dir() {
255            return Err(ToolError::Failed(format!(
256                "{}: not a directory",
257                query.path
258            )));
259        }
260        // The walk is blocking work over the filesystem, and the cap above is what keeps it
261        // short; doing it off the runtime keeps one slow search from stalling a run's stream.
262        let root = self.root.clone();
263        let max_bytes = self.max_bytes;
264        tokio::task::spawn_blocking(move || run(&root, &start, &query, max_bytes))
265            .await
266            .map_err(|e| ToolError::Failed(format!("search panicked: {e}")))?
267    }
268}
269
270/// How much NFA a supplied pattern may compile (`#427`). A megabyte is far past any pattern a
271/// search needs and far short of what a pathological one would build.
272const NFA_SIZE_LIMIT: usize = 1 << 20;
273
274fn run(root: &Path, start: &Path, query: &Query, max_bytes: usize) -> Result<String, ToolError> {
275    let matcher = match query.target {
276        Target::Content => Some(
277            // `#427`: a pattern is model-supplied and its NFA is not bounded by anything else, so
278            // compiling `(a|b|c|…){1,1000}` could cost whatever it liked before the first file was
279            // read. One megabyte of NFA refuses the monstrosity and leaves every real pattern
280            // (a grep, a symbol, a line shape) untouched.
281            regex_automata::meta::Regex::builder()
282                .configure(
283                    regex_automata::meta::Config::new()
284                        .nfa_size_limit(Some(NFA_SIZE_LIMIT))
285                        .dfa_size_limit(Some(NFA_SIZE_LIMIT)),
286                )
287                .build(&query.pattern)
288                .map_err(|e| ToolError::InvalidArgs(format!("`pattern` is not a regex: {e}")))?,
289        ),
290        Target::Files => None,
291    };
292    let mut files = walk(start, root, query.order)?;
293    if query.order == Order::Modified {
294        files.sort_by(|a, b| b.modified.cmp(&a.modified).then(a.shown.cmp(&b.shown)));
295    }
296
297    match query.target {
298        Target::Files => Ok(list_files(files, query)),
299        Target::Content => Ok(search_content(
300            files,
301            matcher.as_ref().expect("a content search has a matcher"),
302            query,
303            max_bytes,
304        )),
305    }
306}
307
308/// Every regular file under `start`, skipping the ignored directories, not following symlinks.
309///
310/// Symlinks are skipped rather than resolved: `confine` already refuses a path that leaves the
311/// workspace, but a walk that follows links can still leave and come back, and "the search says
312/// the file is in the workspace" is worth keeping simple.
313fn walk(start: &Path, root: &Path, order: Order) -> Result<Vec<Found>, ToolError> {
314    let mut out = Vec::new();
315    let mut stack = vec![start.to_path_buf()];
316    let mut looked = 0usize;
317    while let Some(dir) = stack.pop() {
318        let entries = match std::fs::read_dir(&dir) {
319            Ok(entries) => entries,
320            // An unreadable directory is not an error the caller can act on: it is walked past,
321            // the way `rg` walks past it.
322            Err(_) => continue,
323        };
324        for entry in entries.flatten() {
325            looked += 1;
326            if looked > MAX_ENTRIES {
327                return Ok(out);
328            }
329            let name = entry.file_name().to_string_lossy().into_owned();
330            let path = entry.path();
331            let Ok(kind) = entry.file_type() else {
332                continue;
333            };
334            if kind.is_dir() {
335                if !SKIP_DIRS.contains(&name.as_str()) {
336                    stack.push(path);
337                }
338                continue;
339            }
340            if !kind.is_file() {
341                continue;
342            }
343            let shown = path
344                .strip_prefix(root)
345                .unwrap_or(&path)
346                .display()
347                .to_string();
348            let modified = if order == Order::Modified {
349                entry.metadata().ok().and_then(|m| m.modified().ok())
350            } else {
351                None
352            };
353            out.push(Found {
354                path,
355                shown,
356                modified,
357            });
358        }
359    }
360    out.sort_by(|a, b| a.shown.cmp(&b.shown));
361    Ok(out)
362}
363
364fn list_files(files: Vec<Found>, query: &Query) -> String {
365    let wanted: Vec<&Found> = files
366        .iter()
367        .filter(|f| {
368            let name = f.path.file_name().unwrap_or_default().to_string_lossy();
369            name_matches(&query.pattern, &name)
370        })
371        .collect();
372    let total = wanted.len();
373    let page: Vec<&Found> = wanted
374        .into_iter()
375        .skip(query.offset)
376        .take(query.limit)
377        .collect();
378    if page.is_empty() {
379        return format!(
380            "no file name matches `{}` under {}",
381            query.pattern,
382            if query.path.is_empty() {
383                "."
384            } else {
385                &query.path
386            }
387        );
388    }
389    let mut out: Vec<String> = page.iter().map(|f| f.shown.clone()).collect();
390    let shown = out.len();
391    if total > query.offset + shown {
392        out.push(format!(
393            "[{} of {total} files — raise `limit` or narrow the pattern]",
394            query.offset + shown
395        ));
396    }
397    out.join("\n")
398}
399
400fn search_content(
401    files: Vec<Found>,
402    matcher: &regex_automata::meta::Regex,
403    query: &Query,
404    max_bytes: usize,
405) -> String {
406    // The registry would cut a long answer mid-line and say `[output truncated]`. Stopping here
407    // instead keeps the answer a set of whole matches and says which cap it hit, which is the
408    // difference between a page someone can use and a page someone has to re-run.
409    let budget = max_bytes.saturating_sub(256);
410    let mut out = String::new();
411    let mut capped = false;
412    let mut matches_seen = 0usize; // counted before `offset`, so paging is stable
413    let mut printed = 0usize;
414    let mut skipped_big = 0usize;
415    let mut binary = 0usize;
416    // `count` and `files_only` print one line per file, so they page by file, not by match.
417    let per_file = query.mode != Mode::Content;
418    let mut files_printed = 0usize;
419
420    'files: for file in files {
421        if let Some(glob) = &query.file_glob {
422            let name = file.path.file_name().unwrap_or_default().to_string_lossy();
423            if !glob_matches(glob, &name) {
424                continue;
425            }
426        }
427        let Ok(meta) = std::fs::metadata(&file.path) else {
428            continue;
429        };
430        if meta.len() > MAX_FILE_BYTES {
431            skipped_big += 1;
432            continue;
433        }
434        let Ok(bytes) = std::fs::read(&file.path) else {
435            continue;
436        };
437        let head = &bytes[..bytes.len().min(SNIFF_BYTES)];
438        if head.contains(&0u8) {
439            binary += 1;
440            continue;
441        }
442        let text = String::from_utf8_lossy(&bytes);
443        let lines: Vec<&str> = text.lines().collect();
444        let hits: Vec<usize> = lines
445            .iter()
446            .enumerate()
447            .filter(|(_, line)| matcher.is_match(line.as_bytes()))
448            .map(|(i, _)| i)
449            .collect();
450        if hits.is_empty() {
451            continue;
452        }
453        if per_file {
454            if matches_seen + hits.len() <= query.offset {
455                matches_seen += hits.len();
456                continue;
457            }
458            if files_printed >= query.offset + query.limit {
459                matches_seen += hits.len();
460                continue;
461            }
462            files_printed += 1;
463            if files_printed > query.offset {
464                match query.mode {
465                    Mode::FilesOnly => out.push_str(&format!("{}\n", file.shown)),
466                    Mode::Count => {
467                        out.push_str(&format!("{}:{}\n", file.shown, hits.len()));
468                    }
469                    Mode::Content => {}
470                }
471            }
472            matches_seen += hits.len();
473            if files_printed >= query.offset + query.limit {
474                break 'files;
475            }
476            continue;
477        }
478        for i in &hits {
479            matches_seen += 1;
480            if matches_seen <= query.offset {
481                continue;
482            }
483            if printed >= query.limit {
484                // One match past the page is enough to know more remain; the rest of the walk is
485                // spent for nothing.
486                break 'files;
487            }
488            if out.len() >= budget {
489                capped = true;
490                break 'files;
491            }
492            if query.context > 0 {
493                if !out.is_empty() {
494                    out.push_str("--\n");
495                }
496                let from = i.saturating_sub(query.context);
497                let to = (i + query.context).min(lines.len().saturating_sub(1));
498                for (j, line) in lines.iter().enumerate().take(to + 1).skip(from) {
499                    let sep = if j == *i { ':' } else { '-' };
500                    out.push_str(&format!("{}{sep}{}{sep}{}\n", file.shown, j + 1, line));
501                }
502            } else {
503                out.push_str(&format!("{}:{}:{}\n", file.shown, i + 1, lines[*i]));
504            }
505            printed += 1;
506        }
507    }
508
509    let mut tail = Vec::new();
510    if capped {
511        tail.push(format!(
512            "[output reached the {max_bytes}-byte cap — narrow the pattern, or page with `offset`]"
513        ));
514    }
515    if printed == 0 && !capped && query.mode == Mode::Content {
516        let mut said = format!(
517            "no match for `{}` under {}",
518            query.pattern,
519            if query.path.is_empty() {
520                "."
521            } else {
522                &query.path
523            }
524        );
525        if let Some(glob) = &query.file_glob {
526            said.push_str(&format!(" in files named {glob}"));
527        }
528        if skipped_big > 0 || binary > 0 {
529            said.push_str(&format!(
530                " ({} file(s) over {} KiB and {binary} binary skipped)",
531                skipped_big,
532                MAX_FILE_BYTES / 1024
533            ));
534        }
535        return said;
536    }
537    if printed >= query.limit {
538        tail.push(format!(
539            "[stopped at {} matches — more may remain; raise `limit` or narrow the pattern]",
540            query.limit
541        ));
542    }
543    if skipped_big > 0 {
544        tail.push(format!(
545            "[{skipped_big} file(s) over {} KiB skipped]",
546            MAX_FILE_BYTES / 1024
547        ));
548    }
549    if binary > 0 {
550        tail.push(format!("[{binary} binary file(s) skipped]"));
551    }
552    let body = out.trim_end().to_string();
553    if tail.is_empty() {
554        return body;
555    }
556    format!("{body}\n{}", tail.join("\n"))
557}
558
559/// `*` and `?` against one file name, plus the substring reading a pattern without either gets.
560fn name_matches(pattern: &str, name: &str) -> bool {
561    if pattern.contains(['*', '?']) {
562        glob_matches(pattern, name)
563    } else {
564        name.contains(pattern)
565    }
566}
567
568fn glob_matches(pattern: &str, name: &str) -> bool {
569    let p: Vec<char> = pattern.chars().collect();
570    let n: Vec<char> = name.chars().collect();
571    // Iterative backtracking on `*`, so `*.tar.gz` and `a*b*c` work without a dependency.
572    let (mut pi, mut ni) = (0usize, 0usize);
573    let (mut star, mut mark) = (None, 0usize);
574    while ni < n.len() {
575        if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
576            pi += 1;
577            ni += 1;
578        } else if pi < p.len() && p[pi] == '*' {
579            star = Some(pi);
580            mark = ni;
581            pi += 1;
582        } else if let Some(s) = star {
583            pi = s + 1;
584            mark += 1;
585            ni = mark;
586        } else {
587            return false;
588        }
589    }
590    while pi < p.len() && p[pi] == '*' {
591        pi += 1;
592    }
593    pi == p.len()
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    fn tree(files: &[(&str, &str)]) -> tempdir_lite::Dir {
601        let dir = tempdir_lite::Dir::new();
602        for (path, body) in files {
603            let full = dir.path().join(path);
604            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
605            std::fs::write(full, body).unwrap();
606        }
607        dir
608    }
609
610    async fn search(dir: &tempdir_lite::Dir, args: Value) -> String {
611        SearchFiles::new(dir.path().to_path_buf(), 60_000)
612            .call(args)
613            .await
614            .unwrap()
615    }
616
617    /// `#427`: a supplied pattern is compiled before a single file is read, and the size of the
618    /// machine it builds was bounded by nothing. A repetition over a wide union is a few hundred
619    /// bytes of text and tens of megabytes of NFA, which is the shape that costs whatever it likes.
620    #[tokio::test]
621    async fn a_pattern_whose_nfa_is_too_large_is_refused() {
622        let dir = tree(&[("a.txt", "hello\n")]);
623        // A bounded repetition over any-byte, from a 12-character pattern: 2 000 copies of the
624        // state is past a megabyte and under the library's own 10 MB default, so this tests the
625        // cap and not the default. A union of literals was deduplicated away by the compiler.
626        let pattern = "(?s).{1,2000}".to_string();
627        let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
628            .call(serde_json::json!({"pattern": pattern}))
629            .await
630            .expect_err("the NFA cap refuses it");
631        let message = err.to_string();
632        assert!(
633            message.contains("not a regex"),
634            "it is reported as the bad argument it is: {message}"
635        );
636    }
637
638    #[tokio::test]
639    async fn a_pattern_is_found_with_its_line_and_a_glob_narrows_it() {
640        let dir = tree(&[
641            ("a.rs", "fn main() {}\nlet needle = 1;\n"),
642            ("b.md", "the needle is here too\n"),
643            ("sub/c.rs", "// needle in a subdirectory\n"),
644        ]);
645        let all = search(&dir, json!({"pattern": "needle"})).await;
646        assert!(all.contains("a.rs:2:let needle = 1;"), "{all}");
647        assert!(all.contains("b.md:1:the needle is here too"), "{all}");
648        assert!(
649            all.contains(&format!("sub{}c.rs:1", std::path::MAIN_SEPARATOR)),
650            "{all}"
651        );
652
653        let narrow = search(&dir, json!({"pattern": "needle", "file_glob": "*.rs"})).await;
654        assert!(!narrow.contains("b.md"), "{narrow}");
655        assert!(narrow.contains("a.rs:2"), "{narrow}");
656        assert!(narrow.contains("c.rs:1"), "{narrow}");
657    }
658
659    #[tokio::test]
660    async fn the_ignored_directories_are_not_walked_and_the_workspace_is_the_fence() {
661        let dir = tree(&[
662            ("src/a.rs", "needle\n"),
663            ("target/debug/junk.rs", "needle\n"),
664            ("node_modules/pkg/index.js", "needle\n"),
665        ]);
666        let found = search(&dir, json!({"pattern": "needle"})).await;
667        assert!(found.contains("a.rs:1"), "{found}");
668        assert!(!found.contains("target"), "{found}");
669        assert!(!found.contains("node_modules"), "{found}");
670
671        let outside = SearchFiles::new(dir.path().to_path_buf(), 60_000)
672            .call(json!({"pattern": "needle", "path": "../.."}))
673            .await;
674        assert!(outside.is_err(), "a path above the workspace is refused");
675    }
676
677    #[tokio::test]
678    async fn a_limit_is_reported_rather_than_silently_short() {
679        let body: String = (1..=80).map(|i| format!("needle {i}\n")).collect();
680        let dir = tree(&[("big.txt", &body)]);
681        let page = search(&dir, json!({"pattern": "needle", "limit": 5})).await;
682        assert_eq!(page.matches("needle ").count(), 5, "{page}");
683        assert!(page.contains("stopped at 5 matches"), "{page}");
684
685        let next = search(&dir, json!({"pattern": "needle", "limit": 5, "offset": 5})).await;
686        assert!(next.starts_with("big.txt:6:needle 6"), "{next}");
687    }
688
689    #[tokio::test]
690    async fn context_lines_come_with_the_match_and_are_not_confused_with_it() {
691        let dir = tree(&[("a.txt", "one\ntwo\nneedle\nfour\nfive\n")]);
692        let with = search(&dir, json!({"pattern": "needle", "context": 1})).await;
693        assert!(with.contains("a.txt-2-two"), "{with}");
694        assert!(with.contains("a.txt:3:needle"), "{with}");
695        assert!(with.contains("a.txt-4-four"), "{with}");
696        assert!(!with.contains("one"), "{with}");
697    }
698
699    #[tokio::test]
700    async fn files_are_found_by_name_and_count_says_how_many_times() {
701        let dir = tree(&[
702            ("a.rs", "needle\nneedle\n"),
703            ("b.rs", "needle\n"),
704            ("c.md", "nothing\n"),
705        ]);
706        let names = search(&dir, json!({"target": "files", "pattern": "*.rs"})).await;
707        assert_eq!(
708            names.lines().filter(|l| l.ends_with(".rs")).count(),
709            2,
710            "{names}"
711        );
712        assert!(!names.contains("c.md"), "{names}");
713
714        let histogram = search(&dir, json!({"pattern": "needle", "output_mode": "count"})).await;
715        assert!(histogram.contains("a.rs:2"), "{histogram}");
716        assert!(histogram.contains("b.rs:1"), "{histogram}");
717        assert!(!histogram.contains("c.md"), "{histogram}");
718
719        let only = search(
720            &dir,
721            json!({"pattern": "needle", "output_mode": "files_only"}),
722        )
723        .await;
724        assert_eq!(
725            only.lines().filter(|l| l.ends_with(".rs")).count(),
726            2,
727            "{only}"
728        );
729    }
730
731    #[tokio::test]
732    async fn a_pattern_that_is_not_a_regex_is_refused_by_name_and_nothing_is_walked() {
733        let dir = tree(&[("a.txt", "x\n")]);
734        let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
735            .call(json!({"pattern": "a(b"}))
736            .await
737            .unwrap_err();
738        assert!(err.to_string().contains("not a regex"), "{err}");
739    }
740
741    #[tokio::test]
742    async fn binary_files_are_skipped_and_said_to_be() {
743        let dir = tree(&[("a.txt", "needle\n")]);
744        std::fs::write(dir.path().join("blob.bin"), b"needle\x00\x01\x02").unwrap();
745        let found = search(&dir, json!({"pattern": "needle"})).await;
746        assert!(found.contains("a.txt:1"), "{found}");
747        assert!(!found.contains("blob.bin"), "{found}");
748    }
749
750    /// #337: these tests share a process and a clock. Two directories made in the same tick must
751    /// still be two directories, or one test's `Drop` deletes the tree another is searching.
752    #[test]
753    fn two_directories_made_together_are_two_directories() {
754        let dirs: Vec<tempdir_lite::Dir> = (0..200).map(|_| tempdir_lite::Dir::new()).collect();
755        let mut seen: Vec<&std::path::Path> = dirs.iter().map(|d| d.path()).collect();
756        seen.sort();
757        seen.dedup();
758        assert_eq!(seen.len(), 200, "every path is its own");
759        for d in &dirs {
760            assert!(
761                d.path().is_dir(),
762                "and every one is there: {}",
763                d.path().display()
764            );
765        }
766    }
767    #[test]
768    fn a_glob_matches_a_name_the_way_a_person_writes_it() {
769        assert!(glob_matches("*.rs", "main.rs"));
770        assert!(glob_matches("m?in.rs", "main.rs"));
771        assert!(glob_matches("*.tar.gz", "a.tar.gz"));
772        assert!(!glob_matches("*.rs", "main.rss"));
773        assert!(!glob_matches("a*b*c", "abcx"));
774        // A pattern with no glob characters is a substring, and the case is the caller's.
775        assert!(!name_matches("cargo", "Cargo.toml"));
776        assert!(name_matches("Cargo", "Cargo.toml"));
777    }
778}
779
780#[cfg(test)]
781mod tempdir_lite {
782    //! A directory that deletes itself, without pulling a dev-dependency in for it.
783    //!
784    //! The name used to be the clock alone (`as_nanos() ^ (pid << 32)`), and that is not a source of
785    //! uniqueness: cargo runs these tests as parallel threads of **one** process, so two of them
786    //! calling `new()` inside the same clock tick got the *same* directory — and the first `Drop`
787    //! then deleted it from under the second, which saw an empty tree and failed with "no match for
788    //! `needle` under .". It happened on a CI runner with a coarse clock (`msrv` on #337) where it
789    //! reads as a search bug. A counter makes the name unique per call, which no clock can promise.
790    pub struct Dir(std::path::PathBuf);
791
792    impl Dir {
793        pub fn new() -> Self {
794            static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
795            let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
796            let mut path = std::env::temp_dir();
797            let tag: u64 = std::time::SystemTime::now()
798                .duration_since(std::time::UNIX_EPOCH)
799                .map(|d| d.as_nanos() as u64)
800                .unwrap_or(0)
801                ^ (std::process::id() as u64) << 32;
802            path.push(format!("eclipse-search-{tag:x}-{seq}"));
803            std::fs::create_dir_all(&path).unwrap();
804            Self(path)
805        }
806
807        pub fn path(&self) -> &std::path::Path {
808            &self.0
809        }
810    }
811
812    impl Drop for Dir {
813        fn drop(&mut self) {
814            let _ = std::fs::remove_dir_all(&self.0);
815        }
816    }
817}