use ignore::{WalkBuilder, WalkState};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph, Widget},
};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
const MAX_RESULTS: usize = 40;
#[derive(Clone, Debug)]
pub struct FileEntry {
pub path: PathBuf,
pub rel: String,
pub rel_lower: String,
pub filename_start: usize,
pub filename_start_lower: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MatchTier {
Subsequence = 1,
PathSubstring = 2,
FilenameSubstring = 3,
FilenamePrefix = 4,
ExactFilename = 5,
}
#[derive(Clone, Debug)]
pub struct ScoredResult {
pub entry: FileEntry,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineHint {
pub line: usize,
pub end: Option<usize>,
pub col: Option<usize>,
}
#[derive(Default)]
pub struct FileFinder {
pub query: String,
pub cursor: usize,
pub entries: Arc<Vec<FileEntry>>,
pub results: Vec<ScoredResult>,
pub selected: usize,
pub scroll: usize,
pub last_rect: Rect,
pub last_inner_height: u16,
}
impl FileFinder {
pub fn new(entries: Arc<Vec<FileEntry>>) -> Self {
let mut me = Self {
query: String::new(),
cursor: 0,
entries,
results: Vec::new(),
selected: 0,
scroll: 0,
last_rect: Rect::default(),
last_inner_height: 0,
};
me.refresh_results();
me
}
pub fn set_query(&mut self, q: &str) {
if q == self.query {
return;
}
self.query = q.to_string();
self.cursor = self.query.chars().count();
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
fn char_count(&self) -> usize {
self.query.chars().count()
}
fn byte_offset(&self, char_idx: usize) -> usize {
self.query
.char_indices()
.nth(char_idx)
.map(|(b, _)| b)
.unwrap_or(self.query.len())
}
pub fn replace_entries(&mut self, entries: Arc<Vec<FileEntry>>) {
if Arc::ptr_eq(&self.entries, &entries) {
return;
}
self.entries = entries;
self.refresh_results();
if self.results.is_empty() {
self.selected = 0;
} else if self.selected >= self.results.len() {
self.selected = self.results.len() - 1;
}
if self.scroll > self.selected {
self.scroll = self.selected;
}
}
pub fn push_char(&mut self, c: char) {
let at = self.byte_offset(self.cursor);
self.query.insert(at, c);
self.cursor += 1;
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn pop_char(&mut self) {
if self.cursor == 0 {
return;
}
let at = self.byte_offset(self.cursor - 1);
self.query.remove(at);
self.cursor -= 1;
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn delete_char(&mut self) {
if self.cursor >= self.char_count() {
return;
}
let at = self.byte_offset(self.cursor);
self.query.remove(at);
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn move_cursor_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_cursor_right(&mut self) {
self.cursor = (self.cursor + 1).min(self.char_count());
}
pub fn move_cursor_home(&mut self) {
self.cursor = 0;
}
pub fn move_cursor_end(&mut self) {
self.cursor = self.char_count();
}
pub fn select_next(&mut self) {
if self.results.is_empty() {
return;
}
if self.selected + 1 < self.results.len() {
self.selected += 1;
}
}
pub fn select_prev(&mut self) {
if self.selected > 0 {
self.selected -= 1;
}
}
pub fn line_hint(&self) -> Option<LineHint> {
split_line_hint(&self.query).1
}
pub fn selected_entry(&self) -> Option<&FileEntry> {
self.results.get(self.selected).map(|r| &r.entry)
}
pub fn row_index_at(&self, y: u16) -> Option<usize> {
let list_top = self.last_rect.y.saturating_add(3);
if y < list_top || y - list_top >= self.last_inner_height {
return None;
}
let idx = self.scroll + (y - list_top) as usize;
(idx < self.results.len()).then_some(idx)
}
#[cfg(test)]
pub fn selected_index(&self) -> usize {
self.selected
}
#[cfg(test)]
pub fn visible_results(&self) -> &[ScoredResult] {
&self.results
}
fn refresh_results(&mut self) {
let (file_part, hint) = split_line_hint(&self.query);
let mut needle: String = file_part.trim().to_lowercase();
let cut = file_part.len() != self.query.trim_end().len();
if needle.is_empty() && (hint.is_some() || cut) {
self.results = Vec::new();
return;
}
if hint.is_none() {
let raw = self.query.trim().to_lowercase();
if raw != needle && entries_have_filename(&self.entries, &raw) {
needle = raw;
}
}
if needle.is_empty() {
let mut scored: Vec<ScoredResult> = Vec::with_capacity(MAX_RESULTS);
for entry in self.entries.iter().take(MAX_RESULTS) {
scored.push(ScoredResult {
entry: entry.clone(),
});
}
scored.sort_by(|a, b| a.entry.rel.cmp(&b.entry.rel));
self.results = scored;
return;
}
let entries: &[FileEntry] = &self.entries;
let merged: BinaryHeap<RankedSlot> = entries
.par_iter()
.enumerate()
.fold(
|| BinaryHeap::<RankedSlot>::with_capacity(MAX_RESULTS + 1),
|mut heap, (idx, entry)| {
if let Some((tier, score)) =
score_entry(&needle, &entry.rel_lower, entry.filename_start_lower)
{
push_topk(
&mut heap,
RankedSlot {
tier,
rel_len: entry.rel.len() as u32,
score,
idx,
},
MAX_RESULTS,
);
}
heap
},
)
.reduce(
|| BinaryHeap::<RankedSlot>::with_capacity(MAX_RESULTS + 1),
|mut a, b| {
for slot in b {
push_topk(&mut a, slot, MAX_RESULTS);
}
a
},
);
let top: Vec<RankedSlot> = merged.into_sorted_vec();
self.results = top
.into_iter()
.map(|slot| ScoredResult {
entry: entries[slot.idx].clone(),
})
.collect();
}
}
#[derive(Clone, Copy, Debug)]
struct RankedSlot {
tier: MatchTier,
rel_len: u32,
score: i32,
idx: usize,
}
impl PartialEq for RankedSlot {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for RankedSlot {}
impl PartialOrd for RankedSlot {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RankedSlot {
fn cmp(&self, other: &Self) -> Ordering {
other
.tier
.cmp(&self.tier)
.then_with(|| self.rel_len.cmp(&other.rel_len))
.then_with(|| other.score.cmp(&self.score))
.then_with(|| self.idx.cmp(&other.idx))
}
}
fn push_topk(heap: &mut BinaryHeap<RankedSlot>, slot: RankedSlot, k: usize) {
if heap.len() < k {
heap.push(slot);
return;
}
if let Some(worst) = heap.peek()
&& slot.cmp(worst) == Ordering::Less
{
heap.pop();
heap.push(slot);
}
}
fn split_line_hint(query: &str) -> (&str, Option<LineHint>) {
let q = query.trim_end();
for (i, _) in q.match_indices(':') {
let rest = &q[i + 1..];
if let Some(hint) = parse_line_hint(rest) {
return (&q[..i], Some(hint));
}
if is_partial_line_hint(rest) {
return (&q[..i], None);
}
}
(q, None)
}
fn is_partial_line_hint(s: &str) -> bool {
let mut seen_sep = false;
for b in s.bytes() {
match b {
b'0'..=b'9' => {}
b'-' | b':' if !seen_sep => seen_sep = true,
_ => return false,
}
}
true
}
fn parse_line_hint(s: &str) -> Option<LineHint> {
let num = |t: &str| {
(!t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()))
.then(|| t.parse::<usize>().unwrap_or(usize::MAX))
.filter(|n| *n > 0)
};
if let Some((a, b)) = s.split_once('-') {
let (a, b) = (num(a)?, num(b)?);
return Some(LineHint {
line: a.min(b),
end: Some(a.max(b)),
col: None,
});
}
if let Some((a, b)) = s.split_once(':') {
if b.is_empty() || !b.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
return Some(LineHint {
line: num(a)?,
end: None,
col: num(b),
});
}
Some(LineHint {
line: num(s)?,
end: None,
col: None,
})
}
fn entries_have_filename(entries: &[FileEntry], name: &str) -> bool {
entries
.par_iter()
.any(|e| &e.rel_lower[e.filename_start_lower..] == name)
}
pub fn score_entry(
needle: &str,
hay_lower: &str,
filename_start: usize,
) -> Option<(MatchTier, i32)> {
if needle.is_empty() {
return Some((MatchTier::Subsequence, 0));
}
let filename = &hay_lower[filename_start..];
if filename == needle {
return Some((MatchTier::ExactFilename, 10_000));
}
if filename.starts_with(needle) {
return Some((MatchTier::FilenamePrefix, 5_000));
}
if filename.contains(needle) {
return Some((MatchTier::FilenameSubstring, 2_500));
}
if hay_lower.contains(needle) {
return Some((MatchTier::PathSubstring, 1_000));
}
fuzzy_score(needle, hay_lower, filename_start).map(|s| (MatchTier::Subsequence, s))
}
pub fn fuzzy_score(needle: &str, hay_lower: &str, filename_start: usize) -> Option<i32> {
if needle.is_empty() {
return Some(0);
}
let mut needle_chars = needle.chars().peekable();
let mut score: i32 = 0;
let mut consecutive: i32 = 0;
let mut prev_match: Option<usize> = None;
let mut prev: Option<(usize, char)> = None;
for (i, c) in hay_lower.char_indices() {
let Some(&want) = needle_chars.peek() else {
break;
};
if c == want {
let mut bonus: i32 = 1;
if i >= filename_start {
bonus += 4;
}
let at_word_boundary = i == 0
|| i == filename_start
|| matches!(prev, Some((_, '/' | '_' | '-' | '.' | ' ')));
if at_word_boundary {
bonus += 5;
}
if prev_match.is_some() && prev_match == prev.map(|(p, _)| p) {
consecutive += 1;
bonus += consecutive * 5;
} else {
if let Some(p) = prev_match {
let gap = i.saturating_sub(p + 1) as i32;
bonus -= gap.min(20);
}
consecutive = 0;
}
score += bonus;
prev_match = Some(i);
needle_chars.next();
}
prev = Some((i, c));
}
if needle_chars.peek().is_none() {
Some(score - (hay_lower.len() as i32 / 4))
} else {
None
}
}
const NOISE_DIR_NAMES: &[&str] = &[
".git",
".hg",
".svn",
".bzr",
"node_modules",
"target",
"__pycache__",
".venv",
"venv",
".tox",
".mypy_cache",
".pytest_cache",
".ruff_cache",
".next",
".nuxt",
".cache",
"dist",
"build",
".gradle",
".idea",
".vscode-test",
".DS_Store",
".cargo",
".rustup",
".npm",
".nvm",
".bun",
".pnpm-store",
".deno",
".gem",
".pyenv",
".rbenv",
".m2",
".local",
".docker",
".claude",
".codex",
".nuget",
".pub-cache",
".dart-tool",
".dotnet",
".oh-my-zsh",
];
const NOISE_PATH_RUNS: &[&[&str]] = &[&["go", "pkg", "mod"], &["go", "pkg", "sumdb"]];
fn normal_component_count(path: &Path) -> usize {
path.components()
.filter(|c| matches!(c, std::path::Component::Normal(_)))
.count()
}
fn has_component_run(path: &Path, run: &[&str], min_end: usize) -> bool {
let comps: Vec<&std::ffi::OsStr> = path
.components()
.filter_map(|c| match c {
std::path::Component::Normal(s) => Some(s),
_ => None,
})
.collect();
comps.windows(run.len()).enumerate().any(|(i, w)| {
i + run.len() > min_end
&& w.iter()
.zip(run)
.all(|(a, b)| *a == std::ffi::OsStr::new(b))
})
}
pub fn is_noise_dir(name: &std::ffi::OsStr) -> bool {
name.to_str().is_some_and(|n| NOISE_DIR_NAMES.contains(&n))
}
pub fn has_noise_path_run(path: &Path, root: &Path) -> bool {
let depth = if path.starts_with(root) {
normal_component_count(root)
} else {
0
};
NOISE_PATH_RUNS
.iter()
.any(|r| has_component_run(path, r, depth))
}
pub fn is_noise_path_under_root(path: &Path, root: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
is_path_under_noise_dir(rel) || has_noise_path_run(path, root)
}
pub fn is_path_under_noise_dir(path: &Path) -> bool {
path.components()
.filter_map(|c| match c {
std::path::Component::Normal(s) => Some(s),
_ => None,
})
.any(is_noise_dir)
}
fn macos_blocked_paths() -> Vec<PathBuf> {
match std::env::var_os("HOME") {
Some(home) => macos_blocked_paths_for(&PathBuf::from(home)),
None => Vec::new(),
}
}
fn macos_blocked_paths_for(home: &Path) -> Vec<PathBuf> {
let lib = home.join("Library");
[
"Containers",
"Group Containers",
"Caches",
"Application Support",
"Mobile Documents",
"CloudStorage",
"Developer",
"CoreSimulator",
"Mail",
"Messages",
"Safari",
"Cookies",
"Metadata",
"Suggestions",
"Biome",
"Calendars",
"Reminders",
"PersonalizationPortrait",
"HomeKit",
"Photos",
"Daemon Containers",
"WebKit",
]
.iter()
.map(|leaf| lib.join(leaf))
.collect()
}
pub fn build_file_index(root: &Path) -> Vec<FileEntry> {
build_file_index_with_blocked(root, macos_blocked_paths())
}
pub fn build_multi_file_index(roots: &[PathBuf]) -> Vec<FileEntry> {
if roots.len() == 1 {
return build_file_index(&roots[0]);
}
let labels = crate::workspace::root_display_labels(roots);
let mut out = Vec::new();
for (root, label) in roots.iter().zip(&labels) {
let prefix = format!("{label}/");
for mut e in build_file_index(root) {
e.rel = format!("{prefix}{}", e.rel);
e.rel_lower = e.rel.to_lowercase();
e.filename_start = e.rel.rfind('/').map(|i| i + 1).unwrap_or(0);
e.filename_start_lower = e.rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
out.push(e);
}
}
out
}
fn build_file_index_with_blocked(root: &Path, blocked: Vec<PathBuf>) -> Vec<FileEntry> {
let collected: Arc<Mutex<Vec<FileEntry>>> = Arc::new(Mutex::new(Vec::new()));
let root_buf = root.to_path_buf();
let filter_root = root.to_path_buf();
let walker = WalkBuilder::new(root)
.git_ignore(true)
.require_git(false)
.hidden(false)
.filter_entry(move |entry| {
let depth = entry.depth();
if depth == 0 {
return true;
}
if is_noise_dir(entry.file_name()) {
return false;
}
if has_noise_path_run(entry.path(), &filter_root) {
return false;
}
for b in &blocked {
if entry.path().starts_with(b) {
return false;
}
}
true
})
.build_parallel();
walker.run(|| {
let collected = collected.clone();
let root_buf = root_buf.clone();
Box::new(move |entry| {
let entry = match entry {
Ok(e) => e,
Err(_) => return WalkState::Continue,
};
if !entry.file_type().is_some_and(|t| t.is_file()) {
return WalkState::Continue;
}
let path = entry.path().to_path_buf();
let rel_path = path.strip_prefix(&root_buf).unwrap_or(&path);
let rel = rel_path.to_string_lossy().replace('\\', "/");
if rel.is_empty() {
return WalkState::Continue;
}
let rel_lower = rel.to_lowercase();
let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
let filename_start_lower = rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
if let Ok(mut g) = collected.lock() {
g.push(FileEntry {
path,
rel,
rel_lower,
filename_start,
filename_start_lower,
});
}
WalkState::Continue
})
});
let mut out = Arc::try_unwrap(collected)
.map(|m| m.into_inner().unwrap_or_default())
.unwrap_or_default();
out.sort_by(|a, b| a.rel.cmp(&b.rel));
out
}
pub fn render_file_finder(
finder: &mut FileFinder,
area: Rect,
buf: &mut Buffer,
theme: crate::theme::Theme,
center: bool,
) {
let width = area.width.saturating_mul(7) / 10;
let width = width.clamp(40, 100).min(area.width);
let height = area.height.saturating_mul(6) / 10;
let height = height.max(10).min(area.height);
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = if center {
area.y + (area.height.saturating_sub(height)) / 2
} else {
area.y + (area.height.saturating_sub(height)) / 4
};
let rect = Rect {
x,
y,
width,
height,
};
finder.last_rect = rect;
Widget::render(Clear, rect, buf);
let title = Span::styled(
" Go to File — Esc to close, ↑/↓ to navigate, Enter to open ",
Style::default()
.fg(theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
.add_modifier(Modifier::BOLD),
);
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))))
.title(title.clone())
.style(Style::default().bg(theme.ui(Color::Rgb(0x16, 0x18, 0x1f))));
let inner = Rect {
x: rect.x + 1,
y: rect.y + 1,
width: rect.width.saturating_sub(2),
height: rect.height.saturating_sub(2),
};
Widget::render(block, rect, buf);
if theme.framed_overlays() {
crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
}
let sel_bg = if theme.gradient() {
let (r, g, b) = crate::gradient::POPUP_SEL_BG;
Color::Rgb(r, g, b)
} else {
theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
};
if inner.height == 0 || inner.width == 0 {
return;
}
let query_style = Style::default()
.fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
.add_modifier(Modifier::BOLD);
let caret_style = Style::default()
.fg(theme.ui(Color::Rgb(0x16, 0x18, 0x1f)))
.bg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
.add_modifier(Modifier::SLOW_BLINK);
let cursor = finder.cursor.min(finder.query.chars().count());
let before: String = finder.query.chars().take(cursor).collect();
let at: String = finder.query.chars().skip(cursor).take(1).collect();
let after: String = finder.query.chars().skip(cursor + 1).collect();
let caret_glyph = if at.is_empty() { String::from(" ") } else { at };
let prompt_line = Line::from(vec![
Span::styled(
"> ",
Style::default().fg(theme.ui(Color::Rgb(0x88, 0xc0, 0xd0))),
),
Span::styled(before, query_style),
Span::styled(caret_glyph, caret_style),
Span::styled(after, query_style),
]);
let prompt_rect = Rect {
x: inner.x,
y: inner.y,
width: inner.width,
height: 1,
};
Widget::render(Paragraph::new(prompt_line), prompt_rect, buf);
let separator_rect = Rect {
x: inner.x,
y: inner.y + 1,
width: inner.width,
height: 1,
};
let sep_line = Line::from(Span::styled(
"─".repeat(separator_rect.width as usize),
Style::default().fg(theme.ui(Color::Rgb(0x3b, 0x42, 0x52))),
));
Widget::render(Paragraph::new(sep_line), separator_rect, buf);
let list_rect = Rect {
x: inner.x,
y: inner.y + 2,
width: inner.width,
height: inner.height.saturating_sub(2),
};
finder.last_inner_height = list_rect.height;
if list_rect.height == 0 {
return;
}
let visible = list_rect.height as usize;
let total = finder.results.len();
if finder.selected >= finder.scroll + visible {
finder.scroll = finder.selected + 1 - visible;
}
if finder.selected < finder.scroll {
finder.scroll = finder.selected;
}
let end = (finder.scroll + visible).min(total);
if total == 0 {
let empty = if finder.query.trim().is_empty() {
Line::from(Span::styled(
" (no files indexed)",
Style::default().fg(theme.ui(Color::Rgb(0x7a, 0x82, 0x90))),
))
} else {
Line::from(Span::styled(
format!(" No matches for '{}'", finder.query),
Style::default().fg(theme.ui(Color::Rgb(0x7a, 0x82, 0x90))),
))
};
Widget::render(Paragraph::new(empty), list_rect, buf);
return;
}
let mut lines: Vec<Line<'static>> = Vec::with_capacity(end - finder.scroll);
for (offset, result) in finder.results[finder.scroll..end].iter().enumerate() {
let row_idx = finder.scroll + offset;
let is_selected = row_idx == finder.selected;
let row_style = if is_selected {
Style::default().bg(sel_bg).fg(theme.ui(Color::White))
} else {
Style::default().fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
};
let dir_style = if is_selected {
Style::default()
.bg(sel_bg)
.fg(theme.ui(Color::Rgb(0xa0, 0xb4, 0xd8)))
} else {
Style::default().fg(theme.ui(Color::Rgb(0x8e, 0x95, 0xa4)))
};
let (dir_part, file_part) = split_dir_file(&result.entry.rel, result.entry.filename_start);
let prefix = if is_selected { "> " } else { " " };
let spans: Vec<Span<'static>> = vec![
Span::styled(prefix.to_string(), row_style),
Span::styled(
file_part.to_string(),
row_style.add_modifier(Modifier::BOLD),
),
Span::styled(
if dir_part.is_empty() {
String::new()
} else {
format!(" {dir_part}")
},
dir_style,
),
];
lines.push(Line::from(spans));
}
Widget::render(Paragraph::new(lines), list_rect, buf);
}
fn split_dir_file(rel: &str, filename_start: usize) -> (&str, &str) {
if filename_start == 0 {
("", rel)
} else {
let dir = &rel[..filename_start.saturating_sub(1)];
let file = &rel[filename_start..];
(dir, file)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fuzzy_matching_compares_characters_not_bytes() {
assert_eq!(fuzzy_score("é", "ã©", 0), None);
assert!(fuzzy_score("é", "café", 0).is_some());
}
#[test]
fn row_index_at_maps_the_quick_pick_list_geometry() {
let entry = |name: &str| FileEntry {
path: std::path::PathBuf::from(name),
rel: name.to_string(),
rel_lower: name.to_lowercase(),
filename_start: 0,
filename_start_lower: 0,
};
let mut f = FileFinder::new(Arc::new(vec![entry("a.rs"), entry("b.rs"), entry("c.rs")]));
f.last_rect = Rect {
x: 10,
y: 5,
width: 60,
height: 10,
};
f.last_inner_height = 6;
assert_eq!(f.row_index_at(7), None, "the separator is not a row");
assert_eq!(
f.row_index_at(8),
Some(0),
"the list starts below the separator"
);
assert_eq!(f.row_index_at(10), Some(2));
assert_eq!(f.row_index_at(11), None, "below the last result is empty");
assert_eq!(f.row_index_at(14), None, "the bottom border is not a row");
f.scroll = 2;
assert_eq!(f.row_index_at(8), Some(2), "scroll offsets the mapping");
}
#[test]
fn multi_root_index_survives_root_names_whose_lowercase_changes_byte_length() {
let a = tempfile::tempdir().unwrap();
let root_i = a.path().join("İİ");
let root_b = a.path().join("beta");
std::fs::create_dir(&root_i).unwrap();
std::fs::create_dir(&root_b).unwrap();
std::fs::write(
root_i.join("main.rs"),
"x
",
)
.unwrap();
std::fs::write(
root_b.join("main.rs"),
"y
",
)
.unwrap();
let idx = build_multi_file_index(&[root_i, root_b]);
let turkish = idx
.iter()
.find(|e| e.rel.starts_with("İİ/"))
.expect("the entry keeps its root label");
assert_eq!(&turkish.rel[turkish.filename_start..], "main.rs");
assert_eq!(
&turkish.rel_lower[turkish.filename_start_lower..],
"main.rs",
"the scoring string slices at ITS own offset"
);
assert_eq!(
score_entry("main.rs", &turkish.rel_lower, turkish.filename_start_lower)
.map(|(t, _)| t),
Some(MatchTier::ExactFilename),
"filename-tier scoring works through the unicode root label"
);
}
#[test]
fn multi_root_index_disambiguates_same_named_roots() {
let outer = tempfile::tempdir().unwrap();
let work = outer.path().join("work").join("api");
let archive = outer.path().join("archive").join("api");
std::fs::create_dir_all(&work).unwrap();
std::fs::create_dir_all(&archive).unwrap();
std::fs::write(
work.join("main.rs"),
"a
",
)
.unwrap();
std::fs::write(
archive.join("main.rs"),
"b
",
)
.unwrap();
let idx = build_multi_file_index(&[work, archive]);
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
assert!(
rels.contains(&"api (work)/main.rs") && rels.contains(&"api (archive)/main.rs"),
"same-named roots label with their parents: {rels:?}"
);
}
#[test]
fn multi_root_index_prefixes_rels_with_the_root_name_and_keeps_filename_scoring() {
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
let a_root = a.path().join("alpha");
let b_root = b.path().join("beta");
std::fs::create_dir(&a_root).unwrap();
std::fs::create_dir(&b_root).unwrap();
std::fs::write(a_root.join("main.rs"), "a\n").unwrap();
std::fs::write(b_root.join("main.rs"), "b\n").unwrap();
let idx = build_multi_file_index(&[a_root.clone(), b_root.clone()]);
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
assert!(rels.contains(&"alpha/main.rs"), "rels: {rels:?}");
assert!(rels.contains(&"beta/main.rs"), "rels: {rels:?}");
for e in &idx {
assert_eq!(
&e.rel[e.filename_start..],
"main.rs",
"filename_start must shift with the prefix so filename-tier scoring holds"
);
assert!(e.path.is_absolute() && e.path.ends_with("main.rs"));
}
let single = build_multi_file_index(&[a_root]);
assert_eq!(single.len(), 1);
assert_eq!(single[0].rel, "main.rs");
}
fn entry(rel: &str) -> FileEntry {
let rel_lower = rel.to_lowercase();
let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
let filename_start_lower = rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
FileEntry {
path: PathBuf::from(rel),
rel: rel.to_string(),
rel_lower,
filename_start,
filename_start_lower,
}
}
#[test]
fn fuzzy_score_returns_some_for_subsequence_match() {
let score = fuzzy_score(
"ab",
"alpha/beta.rs",
"alpha/beta.rs".rfind('/').unwrap() + 1,
);
assert!(
score.is_some(),
"'ab' must subsequence-match 'alpha/beta.rs'"
);
}
#[test]
fn fuzzy_score_returns_none_when_chars_are_out_of_order() {
let score = fuzzy_score("zx", "abc/def.rs", 4);
assert!(score.is_none());
}
#[test]
fn filename_matches_rank_above_directory_matches() {
let dir_match = fuzzy_score(
"be",
"beta_dir/zoom.rs",
"beta_dir/zoom.rs".rfind('/').unwrap() + 1,
);
let file_match = fuzzy_score("be", "zoom/beta.rs", "zoom/beta.rs".rfind('/').unwrap() + 1);
assert!(
file_match > dir_match,
"matches inside the filename must score higher than matches in directory segments (file={file_match:?}, dir={dir_match:?})"
);
}
#[test]
fn consecutive_chars_score_higher_than_split_chars() {
let consec = fuzzy_score("alp", "alpha.rs", 0).unwrap();
let split = fuzzy_score("alp", "a_l_p_xx.rs", 0).unwrap();
assert!(
consec > split,
"'alp' against 'alpha.rs' must score higher than against 'a_l_p_xx.rs'"
);
}
#[test]
fn file_finder_with_empty_query_lists_files_alphabetically() {
let entries = Arc::new(vec![
entry("zeta.rs"),
entry("alpha.rs"),
entry("mid/beta.rs"),
]);
let finder = FileFinder::new(entries);
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(names, vec!["alpha.rs", "mid/beta.rs", "zeta.rs"]);
}
#[test]
fn cursor_supports_mid_string_insert_and_delete() {
let finder_entries = Arc::new(vec![entry("a.rs")]);
let mut f = FileFinder::new(finder_entries);
for c in "abc".chars() {
f.push_char(c);
}
assert_eq!((f.query.as_str(), f.cursor), ("abc", 3));
f.move_cursor_left();
f.move_cursor_left();
assert_eq!(f.cursor, 1);
f.push_char('X');
assert_eq!((f.query.as_str(), f.cursor), ("aXbc", 2));
f.pop_char();
assert_eq!((f.query.as_str(), f.cursor), ("abc", 1));
f.delete_char();
assert_eq!((f.query.as_str(), f.cursor), ("ac", 1));
f.move_cursor_home();
assert_eq!(f.cursor, 0);
f.move_cursor_end();
assert_eq!(f.cursor, 2);
f.move_cursor_right();
assert_eq!(
f.cursor, 2,
"cursor must not move past the end of the query"
);
}
#[test]
fn query_with_path_separator_matches_the_relative_path() {
let entries = Arc::new(vec![
entry("md2pdf/core.py"),
entry("other/core.py"),
entry("core.py"),
]);
let mut finder = FileFinder::new(entries);
finder.set_query("md2pdf/core.py");
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
names.first().copied(),
Some("md2pdf/core.py"),
"a query containing '/' must match against the relative path; got {names:?}"
);
}
#[test]
fn a_line_suffix_is_split_off_the_query_and_the_file_part_still_matches() {
let entries = Arc::new(vec![entry("src/alpha.rs"), entry("src/beta.rs")]);
let mut finder = FileFinder::new(entries);
for (query, hint) in [
(
"alpha:236-239",
LineHint {
line: 236,
end: Some(239),
col: None,
},
),
(
"alpha:236",
LineHint {
line: 236,
end: None,
col: None,
},
),
(
"alpha:236:7",
LineHint {
line: 236,
end: None,
col: Some(7),
},
),
] {
finder.set_query(query);
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
names,
vec!["src/alpha.rs"],
"{query}: the file part alone selects the file; got {names:?}"
);
assert_eq!(finder.line_hint(), Some(hint), "{query}");
}
finder.set_query("alpha:239-236");
assert_eq!(
finder.line_hint(),
Some(LineHint {
line: 236,
end: Some(239),
col: None,
}),
"a reversed range normalises"
);
finder.set_query("alpha:0");
assert_eq!(finder.line_hint(), None, "line 0 is not a line");
finder.set_query("alpha");
assert_eq!(finder.line_hint(), None, "no suffix, no hint");
finder.set_query("alpha:");
assert_eq!(finder.line_hint(), None, "a bare colon is not a hint");
for partial in ["alpha:", "alpha:236-", "alpha:236:"] {
finder.set_query(partial);
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
names,
vec!["src/alpha.rs"],
"{partial}: still matching on the file part"
);
assert_eq!(
finder.line_hint(),
None,
"{partial}: no hint until it parses"
);
}
for q in [":236", ":", "::", ":236-", ":0"] {
finder.set_query(q);
assert!(
finder.visible_results().is_empty(),
"{q:?} alone matches nothing"
);
}
finder.set_query("alpha:236:0");
assert_eq!(
finder.line_hint().map(|h| (h.line, h.col)),
Some((236, None)),
"`:236:0` is line 236 with no column"
);
finder.set_query("alpha:99999999999999999999");
assert_eq!(finder.line_hint().map(|h| h.line), Some(usize::MAX));
}
#[test]
fn a_filename_that_ends_in_a_colon_still_wins_an_exact_match() {
let entries = Arc::new(vec![entry("src/alpha"), entry("src/alpha:")]);
let mut finder = FileFinder::new(entries);
finder.set_query("alpha:");
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
names.first().copied(),
Some("src/alpha:"),
"the file whose name IS the query ranks first; got {names:?}"
);
assert_eq!(finder.line_hint(), None);
}
#[test]
fn typing_filters_to_subsequence_matches_only() {
let entries = Arc::new(vec![
entry("alpha.rs"),
entry("sub/beta.rs"),
entry("gamma.rs"),
]);
let mut finder = FileFinder::new(entries);
finder.set_query("be");
let names: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
names,
vec!["sub/beta.rs"],
"filter 'be' must keep only beta.rs"
);
}
#[test]
fn selection_clamps_when_results_shrink_under_typing() {
let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs")]);
let mut finder = FileFinder::new(entries);
finder.select_next();
assert_eq!(finder.selected_index(), 1);
finder.set_query("alp");
assert_eq!(
finder.selected_index(),
0,
"selection must reset to 0 when the result list changes shape"
);
}
#[test]
fn select_next_caps_at_last_result() {
let entries = Arc::new(vec![entry("a.rs"), entry("b.rs")]);
let mut finder = FileFinder::new(entries);
finder.select_next();
finder.select_next();
finder.select_next();
assert_eq!(
finder.selected_index(),
1,
"select_next must not overshoot the last index"
);
}
#[test]
fn select_prev_caps_at_zero() {
let entries = Arc::new(vec![entry("a.rs"), entry("b.rs")]);
let mut finder = FileFinder::new(entries);
finder.select_prev();
finder.select_prev();
assert_eq!(finder.selected_index(), 0);
}
#[test]
fn build_file_index_walks_workspace_and_honours_gitignore() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
std::fs::create_dir(tmp.path().join("sub")).unwrap();
std::fs::write(tmp.path().join("sub").join("beta.rs"), "").unwrap();
std::fs::write(tmp.path().join(".gitignore"), "ignored.txt\n").unwrap();
std::fs::write(tmp.path().join("ignored.txt"), "").unwrap();
let entries = build_file_index(tmp.path());
let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
assert!(names.contains(&"alpha.rs"));
assert!(names.contains(&"sub/beta.rs"));
assert!(
!names.contains(&"ignored.txt"),
"gitignored files must be excluded from the Cmd+P index"
);
}
#[test]
fn build_file_index_includes_user_owned_dot_directories() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join(".croft")).unwrap();
std::fs::write(tmp.path().join(".croft").join("lsp.log"), b"").unwrap();
std::fs::create_dir(tmp.path().join(".config")).unwrap();
std::fs::write(tmp.path().join(".config").join("init.toml"), b"").unwrap();
let entries = build_file_index(tmp.path());
let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
assert!(
names.contains(&".croft/lsp.log"),
"Cmd+P index must include files under user dot-dirs like .croft/; got {names:?}"
);
assert!(
names.contains(&".config/init.toml"),
"Cmd+P index must include files under .config/ and similar user dot-dirs; got {names:?}"
);
}
#[test]
fn build_file_index_skips_macos_app_data_containers() {
let tmp = tempfile::tempdir().unwrap();
let fake_home = tmp.path();
let containers = fake_home
.join("Library")
.join("Containers")
.join("com.example.app")
.join("Data");
std::fs::create_dir_all(&containers).unwrap();
std::fs::write(containers.join("private.sqlite"), b"").unwrap();
let group = fake_home
.join("Library")
.join("Group Containers")
.join("group.example")
.join("shared");
std::fs::create_dir_all(&group).unwrap();
std::fs::write(group.join("shared.db"), b"").unwrap();
let logs = fake_home.join("Library").join("Logs");
std::fs::create_dir_all(&logs).unwrap();
std::fs::write(logs.join("app.log"), b"").unwrap();
let entries = build_file_index_with_blocked(fake_home, macos_blocked_paths_for(fake_home));
let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
assert!(
names.contains(&"Library/Logs/app.log"),
"Library/Logs/app.log must still be indexed; got {names:?}"
);
assert!(
!names.iter().any(|n| n.starts_with("Library/Containers/")),
"Library/Containers/** must be excluded to avoid macOS AppData TCC prompts; got {names:?}"
);
assert!(
!names
.iter()
.any(|n| n.starts_with("Library/Group Containers/")),
"Library/Group Containers/** must be excluded for the same TCC reason; got {names:?}"
);
}
#[test]
fn build_file_index_skips_vendored_noise_directories() {
let tmp = tempfile::tempdir().unwrap();
for noise in [
".git",
"node_modules",
"target",
"__pycache__",
".venv",
".tox",
".mypy_cache",
] {
let dir = tmp.path().join(noise);
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("blob"), b"").unwrap();
}
std::fs::write(tmp.path().join("real.txt"), b"").unwrap();
let entries = build_file_index(tmp.path());
let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
assert!(
names.contains(&"real.txt"),
"the regular workspace file must still be indexed; got {names:?}"
);
for noise in [
".git/blob",
"node_modules/blob",
"target/blob",
"__pycache__/blob",
".venv/blob",
".tox/blob",
".mypy_cache/blob",
] {
assert!(
!names.contains(&noise),
"{noise} must be filtered out so vendored / generated dirs do not drown the Cmd+P index; got {names:?}"
);
}
}
#[test]
fn exact_filename_match_beats_every_substring_or_subsequence_match() {
let entries = Arc::new(vec![
entry("packages/anterior-dev-py/tests/test_citations_storage.py"),
entry("app/oncohealth/tasks/main/tests/test_configure_agent_v1.py"),
entry("packages/anterior-dev-py/src/anterior/dev/citations/storage.py"),
]);
let mut finder = FileFinder::new(entries);
finder.set_query("storage.py");
let rels: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
rels.first().copied(),
Some("packages/anterior-dev-py/src/anterior/dev/citations/storage.py"),
"exact filename match 'storage.py' MUST come before test_citations_storage.py (filename-substring) and test_configure_agent_v1.py (only a scattered subsequence) — got {rels:?}. Subsequence tier swamping exact match is the bug the user yelled about at 10:54 on 2026-05-13."
);
}
#[test]
fn filename_prefix_beats_filename_substring_which_beats_path_substring_which_beats_subsequence()
{
let entries = Arc::new(vec![
entry("zzz_other/random_storage_thing.py"),
entry("dir_with_storage_in_name/other.py"),
entry("a/test_storage.py"),
entry("b/storage_helper.py"),
]);
let mut finder = FileFinder::new(entries);
finder.set_query("storage");
let rels: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
rels,
vec![
"b/storage_helper.py",
"a/test_storage.py",
"zzz_other/random_storage_thing.py",
"dir_with_storage_in_name/other.py",
],
"tier order must be: filename starts-with > filename contains > path contains > scattered subsequence — got {rels:?}"
);
}
#[test]
fn within_the_same_tier_the_shorter_relative_path_wins() {
let entries = Arc::new(vec![
entry("a/very/deeply/nested/dir/structure/storage.py"),
entry("storage.py"),
entry("b/c/storage.py"),
]);
let mut finder = FileFinder::new(entries);
finder.set_query("storage.py");
let rels: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
rels,
vec![
"storage.py",
"b/c/storage.py",
"a/very/deeply/nested/dir/structure/storage.py",
],
"all three are exact-filename matches; tie-break must be ascending rel.len() so the workspace-root storage.py wins — got {rels:?}"
);
}
#[test]
#[ignore]
fn bench_cmd_p_real_home() {
let home = std::env::var("HOME").expect("$HOME");
let root = std::path::PathBuf::from(home);
let t0 = std::time::Instant::now();
let entries = build_file_index(&root);
let walk_ms = t0.elapsed().as_secs_f64() * 1000.0;
eprintln!("walk: indexed {} files in {:.0} ms", entries.len(), walk_ms);
let arc = std::sync::Arc::new(entries);
let mut finder = FileFinder::new(arc.clone());
for c in "lsp.log".chars() {
let t = std::time::Instant::now();
finder.push_char(c);
let ms = t.elapsed().as_secs_f64() * 1000.0;
eprintln!(
"type '{}' -> query={:?} results={} latency={:.2} ms",
c,
finder.query,
finder.visible_results().len(),
ms
);
}
}
#[test]
fn replace_entries_re_ranks_results_against_the_new_index() {
let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs")]);
let mut finder = FileFinder::new(entries);
finder.set_query("resolver.ts");
assert!(
finder.visible_results().is_empty(),
"no resolver.ts in initial index"
);
let new_entries = Arc::new(vec![
entry("alpha.rs"),
entry("beta.rs"),
entry("packages/ant-ts-lib-noggin/src/entities/files/resolver.ts"),
]);
finder.replace_entries(new_entries);
let rels: Vec<&str> = finder
.visible_results()
.iter()
.map(|r| r.entry.rel.as_str())
.collect();
assert_eq!(
rels.first().copied(),
Some("packages/ant-ts-lib-noggin/src/entities/files/resolver.ts"),
"after replace_entries the new index must drive the result list; got {rels:?}"
);
}
#[test]
fn replace_entries_clamps_selection_when_results_shrink() {
let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs"), entry("gamma.rs")]);
let mut finder = FileFinder::new(entries);
finder.select_next();
finder.select_next();
assert_eq!(finder.selected_index(), 2);
finder.replace_entries(Arc::new(vec![entry("alpha.rs")]));
assert_eq!(
finder.selected_index(),
0,
"selection must clamp to last visible row when the index shrinks"
);
}
#[test]
fn fuzzy_score_handles_mixed_case_via_lowercased_haystack() {
let rel = "Sub/BetaFile.rs";
let rel_lower = rel.to_lowercase();
let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
let score = fuzzy_score("beta", &rel_lower, filename_start);
assert!(score.is_some());
}
#[test]
fn is_path_under_noise_dir_flags_cargo_and_npm_output_paths() {
assert!(is_path_under_noise_dir(Path::new(
"/Users/v/proj/target/debug/build/croft-abcd"
)));
assert!(is_path_under_noise_dir(Path::new(
"/Users/v/proj/node_modules/foo/bar.js"
)));
assert!(is_path_under_noise_dir(Path::new(
"/Users/v/proj/.git/objects/ff/abcd"
)));
}
#[test]
fn is_path_under_noise_dir_flags_home_tool_caches() {
for p in [
"/root/.cargo/registry/src/index/foo-1.0/src/lib.rs",
"/root/.claude/projects/x/session.jsonl",
"/root/.npm/_cacache/index-v5/aa/bb",
"/root/.nvm/versions/node/v20/lib/x.js",
"/root/.bun/install/cache/pkg/index.js",
"/root/.local/share/pipx/venvs/tool/bin/x",
] {
assert!(is_path_under_noise_dir(Path::new(p)), "{p}");
}
}
#[test]
fn noise_is_measured_from_the_workspace_root_not_the_filesystem_root() {
let root = Path::new("/home/dev/build/myapp");
assert!(
!is_noise_path_under_root(&root.join("src/a.rs"), root),
"a source file in a workspace under build/ is not noise"
);
assert!(
!is_noise_path_under_root(root, root),
"nor is the root itself"
);
for rel in ["target/debug/x", "node_modules/p/i.js", "go/pkg/mod/x"] {
assert!(
is_noise_path_under_root(&root.join(rel), root),
"{rel} is noise below the root"
);
}
assert!(is_noise_path_under_root(
Path::new("/elsewhere/target/x"),
root
));
assert!(is_path_under_noise_dir(&root.join("src/a.rs")));
}
#[test]
fn is_path_under_noise_dir_does_not_flag_workspace_source_paths() {
assert!(!is_path_under_noise_dir(Path::new(
"/Users/v/proj/src/app.rs"
)));
assert!(!is_path_under_noise_dir(Path::new(
"/Users/v/proj/README.md"
)));
assert!(!is_path_under_noise_dir(Path::new(
"/Users/v/proj/docs/target.md"
)));
}
#[test]
fn noise_rules_flag_dotnet_dart_and_go_module_caches() {
for p in [
"/root/.nuget/packages/microsoft.codeanalysis.common/5.0.0/lib/x.dll",
"/root/.pub-cache/hosted/pub.dev/args-2.4.2/lib/args.dart",
"/root/.dart-tool/pub/bin/x",
"/root/.dotnet/sdk/8.0.100/x.dll",
"/root/.oh-my-zsh/plugins/git/git.plugin.zsh",
] {
assert!(is_path_under_noise_dir(Path::new(p)), "{p}");
}
for p in [
"/root/go/pkg/mod/golang.org/x/tools@v0.28.0/go/analysis/x.go",
"/root/go/pkg/sumdb/sum.golang.org/lookup/x",
] {
assert!(has_noise_path_run(Path::new(p), Path::new("/root")), "{p}");
}
}
#[test]
fn build_file_index_indexes_a_workspace_opened_inside_the_module_cache() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("go/pkg/mod/github.com/x/y@v1.0.0");
std::fs::create_dir_all(root.join("internal")).unwrap();
std::fs::write(root.join("main.go"), "x").unwrap();
std::fs::write(root.join("internal/a.go"), "x").unwrap();
let idx = build_file_index(&root);
let mut rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
rels.sort_unstable();
assert_eq!(rels, vec!["internal/a.go", "main.go"]);
}
#[test]
fn build_file_index_indexes_a_workspace_under_a_noise_named_ancestor() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("build/myapp");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/main.rs"), "x").unwrap();
let idx = build_file_index(&root);
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
assert_eq!(rels, vec!["src/main.rs"]);
}
#[test]
fn noise_rules_keep_a_real_go_source_tree() {
let root = Path::new("/Users/v/proj");
for p in [
"/Users/v/proj/go/main.go",
"/Users/v/proj/go/pkg/handler/handler.go",
"/Users/v/proj/src/mod/thing.rs",
"/Users/v/proj/pkg/mod/thing.go",
] {
assert!(!has_noise_path_run(Path::new(p), root), "{p}");
assert!(!is_path_under_noise_dir(Path::new(p)), "{p}");
}
assert!(!has_noise_path_run(
Path::new("/home/u/go/pkg/mod/x@v1/main.go"),
Path::new("/home/u/go/pkg/mod/x@v1")
));
}
#[test]
fn a_gopath_root_still_prunes_the_module_cache_below_it() {
let gopath = Path::new("/home/u/go");
for p in [
"/home/u/go/pkg/mod/x@v1/a.go",
"/home/u/go/pkg/sumdb/lookup/y",
] {
assert!(has_noise_path_run(Path::new(p), gopath), "{p}");
}
assert!(!has_noise_path_run(
Path::new("/home/u/go/src/app/main.go"),
gopath
));
assert!(!has_noise_path_run(
Path::new("/home/u/go/pkg/mod/x@v1/a.go"),
Path::new("/home/u/go/pkg/mod/x@v1")
));
assert!(!has_noise_path_run(
Path::new("/home/u/go/pkg/mod/x/a.go"),
Path::new("/home/u/go/pkg/mod")
));
assert!(has_noise_path_run(
Path::new("/home/u/go/pkg/mod/x/a.go"),
Path::new("/home/u/go/pkg")
));
}
#[test]
fn has_component_run_matches_only_consecutive_whole_components() {
assert!(has_component_run(
Path::new("/a/go/pkg/mod/b"),
&["go", "pkg", "mod"],
0
));
assert!(!has_component_run(
Path::new("/a/go/pkg/other/mod"),
&["go", "pkg", "mod"],
0
));
assert!(!has_component_run(
Path::new("/a/cargo/pkg/mod"),
&["go", "pkg", "mod"],
0
));
assert!(!has_component_run(
Path::new("/a/go/pkg/mod/b"),
&["go", "pkg", "mod"],
4
));
assert!(has_component_run(
Path::new("/a/go/pkg/mod/b"),
&["go", "pkg", "mod"],
3
));
}
#[test]
fn build_file_index_skips_the_go_module_cache() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("go/pkg/mod/golang.org/x")).unwrap();
std::fs::write(root.join("go/pkg/mod/golang.org/x/cached.go"), "x").unwrap();
std::fs::create_dir_all(root.join("go/cmd")).unwrap();
std::fs::write(root.join("go/cmd/main.go"), "x").unwrap();
let idx = build_file_index(root);
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
assert!(rels.contains(&"go/cmd/main.go"), "{rels:?}");
assert!(
!rels.iter().any(|r| r.contains("pkg/mod")),
"module cache leaked into the index: {rels:?}"
);
}
#[test]
fn build_file_index_skips_the_module_cache_of_a_gopath_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("go");
std::fs::create_dir_all(root.join("pkg/mod/golang.org/x")).unwrap();
std::fs::write(root.join("pkg/mod/golang.org/x/cached.go"), "x").unwrap();
std::fs::create_dir_all(root.join("cmd")).unwrap();
std::fs::write(root.join("cmd/main.go"), "x").unwrap();
let idx = build_file_index(&root);
let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
assert!(rels.contains(&"cmd/main.go"), "{rels:?}");
assert!(
!rels.iter().any(|r| r.contains("pkg/mod")),
"a GOPATH root's own module cache leaked into the index: {rels:?}"
);
}
}