aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
42
akode-rs/file-search/src/cli.rs
Normal file
42
akode-rs/file-search/src/cli.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::num::NonZero;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::ArgAction;
|
||||
use clap::Parser;
|
||||
|
||||
/// Fuzzy matches filenames under a directory.
|
||||
#[derive(Parser)]
|
||||
#[command(version)]
|
||||
pub struct Cli {
|
||||
/// Whether to output results in JSON format.
|
||||
#[clap(long, default_value = "false")]
|
||||
pub json: bool,
|
||||
|
||||
/// Maximum number of results to return.
|
||||
#[clap(long, short = 'l', default_value = "64")]
|
||||
pub limit: NonZero<usize>,
|
||||
|
||||
/// Directory to search.
|
||||
#[clap(long, short = 'C')]
|
||||
pub cwd: Option<PathBuf>,
|
||||
|
||||
/// Include matching file indices in the output.
|
||||
#[arg(long, default_value = "false")]
|
||||
pub compute_indices: bool,
|
||||
|
||||
// While it is common to default to the number of logical CPUs when creating
|
||||
// a thread pool, empirically, the I/O of the filetree traversal offers
|
||||
// limited parallelism and is the bottleneck, so using a smaller number of
|
||||
// threads is more efficient. (Empirically, using more than 2 threads doesn't seem to provide much benefit.)
|
||||
//
|
||||
/// Number of worker threads to use.
|
||||
#[clap(long, default_value = "2")]
|
||||
pub threads: NonZero<usize>,
|
||||
|
||||
/// Exclude patterns
|
||||
#[arg(short, long, action = ArgAction::Append)]
|
||||
pub exclude: Vec<String>,
|
||||
|
||||
/// Search pattern.
|
||||
pub pattern: Option<String>,
|
||||
}
|
||||
652
akode-rs/file-search/src/lib.rs
Normal file
652
akode-rs/file-search/src/lib.rs
Normal file
@@ -0,0 +1,652 @@
|
||||
use crossbeam_channel::Receiver;
|
||||
use crossbeam_channel::Sender;
|
||||
use crossbeam_channel::after;
|
||||
use crossbeam_channel::never;
|
||||
use crossbeam_channel::select;
|
||||
use crossbeam_channel::unbounded;
|
||||
use ignore::WalkBuilder;
|
||||
use ignore::overrides::OverrideBuilder;
|
||||
use nucleo::Config;
|
||||
use nucleo::Injector;
|
||||
use nucleo::Matcher;
|
||||
use nucleo::Nucleo;
|
||||
use nucleo::Utf32String;
|
||||
use nucleo::pattern::CaseMatching;
|
||||
use nucleo::pattern::Normalization;
|
||||
use serde::Serialize;
|
||||
use std::num::NonZero;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Condvar;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[cfg(test)]
|
||||
use nucleo::Utf32Str;
|
||||
#[cfg(test)]
|
||||
use nucleo::pattern::AtomKind;
|
||||
#[cfg(test)]
|
||||
use nucleo::pattern::Pattern;
|
||||
|
||||
mod cli;
|
||||
mod snapshot;
|
||||
|
||||
pub use cli::Cli;
|
||||
|
||||
/// A single match result returned from the search.
|
||||
///
|
||||
/// * `score` – Relevance score used to select and order this result.
|
||||
/// * `path` – Path to the matched entry (file or directory), relative to the
|
||||
/// search directory.
|
||||
/// * `match_type` – Whether this match is a file or directory.
|
||||
/// * `indices` – Optional list of character indices that matched the query.
|
||||
/// These are only filled when the caller of [`run`] sets
|
||||
/// `options.compute_indices` to `true`. The indices vector follows the
|
||||
/// guidance from `nucleo::pattern::Pattern::indices`: they are
|
||||
/// unique and sorted in ascending order so that callers can use
|
||||
/// them directly for highlighting.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct FileMatch {
|
||||
pub score: u32,
|
||||
pub path: PathBuf,
|
||||
pub match_type: MatchType,
|
||||
pub root: PathBuf,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub indices: Option<Vec<u32>>, // Sorted & deduplicated when present
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MatchType {
|
||||
File,
|
||||
Directory,
|
||||
}
|
||||
|
||||
/// Carries the selected root and entry type without duplicating ASCII matcher paths.
|
||||
enum IndexedEntry {
|
||||
Ascii {
|
||||
root_idx: usize,
|
||||
match_type: MatchType,
|
||||
},
|
||||
Unicode(Box<UnicodeEntry>),
|
||||
}
|
||||
|
||||
// Unicode matcher columns retain only one codepoint per grapheme.
|
||||
struct UnicodeEntry {
|
||||
root_idx: usize,
|
||||
relative_path: Box<str>,
|
||||
match_type: MatchType,
|
||||
}
|
||||
|
||||
impl FileMatch {
|
||||
pub fn full_path(&self) -> PathBuf {
|
||||
self.root.join(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the final path component for a matched path, falling back to the full path.
|
||||
pub fn file_name_from_path(path: &str) -> String {
|
||||
Path::new(path)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FileSearchResults {
|
||||
pub matches: Vec<FileMatch>,
|
||||
pub total_match_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
|
||||
pub struct FileSearchSnapshot {
|
||||
pub query: String,
|
||||
pub matches: Vec<FileMatch>,
|
||||
pub total_match_count: usize,
|
||||
pub scanned_file_count: usize,
|
||||
pub walk_complete: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileSearchOptions {
|
||||
pub limit: NonZero<usize>,
|
||||
pub exclude: Vec<String>,
|
||||
pub threads: NonZero<usize>,
|
||||
pub compute_indices: bool,
|
||||
/// Toggle ignore-file processing in the walker.
|
||||
///
|
||||
/// When enabled, `.gitignore` files are scoped by
|
||||
/// `WalkBuilder::require_git(true)`, so they are honored only when the
|
||||
/// traversed path is inside a git repository. When disabled, the walker
|
||||
/// turns off `.gitignore`, git-global/exclude rules, `.ignore`, and
|
||||
/// parent-directory ignore scanning.
|
||||
pub respect_gitignore: bool,
|
||||
}
|
||||
|
||||
impl Default for FileSearchOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
#[expect(clippy::unwrap_used)]
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
#[expect(clippy::unwrap_used)]
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait SessionReporter: Send + Sync + 'static {
|
||||
/// Called when the debounced top-N changes.
|
||||
fn on_update(&self, snapshot: &FileSearchSnapshot);
|
||||
|
||||
/// Called when the session becomes idle or is cancelled. Guaranteed to be called at least once per update_query.
|
||||
fn on_complete(&self);
|
||||
}
|
||||
|
||||
pub struct FileSearchSession {
|
||||
inner: Arc<SessionInner>,
|
||||
}
|
||||
|
||||
impl FileSearchSession {
|
||||
/// Update the query. This should be cheap relative to re-walking.
|
||||
pub fn update_query(&self, pattern_text: &str) {
|
||||
let _ = self
|
||||
.inner
|
||||
.work_tx
|
||||
.send(WorkSignal::QueryUpdated(pattern_text.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FileSearchSession {
|
||||
fn drop(&mut self) {
|
||||
self.inner.shutdown.store(true, Ordering::Relaxed);
|
||||
let _ = self.inner.work_tx.send(WorkSignal::Shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_session(
|
||||
search_directories: Vec<PathBuf>,
|
||||
options: FileSearchOptions,
|
||||
reporter: Arc<dyn SessionReporter>,
|
||||
cancel_flag: Option<Arc<AtomicBool>>,
|
||||
) -> anyhow::Result<FileSearchSession> {
|
||||
let FileSearchOptions {
|
||||
limit,
|
||||
exclude,
|
||||
threads,
|
||||
compute_indices,
|
||||
respect_gitignore,
|
||||
} = options;
|
||||
|
||||
let Some(primary_search_directory) = search_directories.first() else {
|
||||
anyhow::bail!("at least one search directory is required");
|
||||
};
|
||||
let override_matcher = build_override_matcher(primary_search_directory, &exclude)?;
|
||||
let (work_tx, work_rx) = unbounded();
|
||||
|
||||
let notify_tx = work_tx.clone();
|
||||
let notify = Arc::new(move || {
|
||||
let _ = notify_tx.send(WorkSignal::NucleoNotify);
|
||||
});
|
||||
let nucleo = Nucleo::new(
|
||||
Config::DEFAULT.match_paths(),
|
||||
notify,
|
||||
Some(threads.get()),
|
||||
1,
|
||||
);
|
||||
let injector = nucleo.injector();
|
||||
|
||||
let cancelled = cancel_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
|
||||
|
||||
let inner = Arc::new(SessionInner {
|
||||
search_directories,
|
||||
limit: limit.get(),
|
||||
threads: threads.get(),
|
||||
compute_indices,
|
||||
respect_gitignore,
|
||||
cancelled,
|
||||
shutdown: Arc::new(AtomicBool::new(false)),
|
||||
reporter,
|
||||
work_tx,
|
||||
});
|
||||
|
||||
let matcher_inner = inner.clone();
|
||||
thread::spawn(move || matcher_worker(matcher_inner, work_rx, nucleo));
|
||||
|
||||
let walker_inner = inner.clone();
|
||||
thread::spawn(move || walker_worker(walker_inner, override_matcher, injector));
|
||||
|
||||
Ok(FileSearchSession { inner })
|
||||
}
|
||||
|
||||
pub trait Reporter {
|
||||
fn report_match(&self, file_match: &FileMatch);
|
||||
fn warn_matches_truncated(&self, total_match_count: usize, shown_match_count: usize);
|
||||
fn warn_no_search_pattern(&self, search_directory: &Path);
|
||||
}
|
||||
|
||||
pub async fn run_main<T: Reporter>(
|
||||
Cli {
|
||||
pattern,
|
||||
limit,
|
||||
cwd,
|
||||
compute_indices,
|
||||
json: _,
|
||||
exclude,
|
||||
threads,
|
||||
}: Cli,
|
||||
reporter: T,
|
||||
) -> anyhow::Result<()> {
|
||||
let search_directory = match cwd {
|
||||
Some(dir) => dir,
|
||||
None => std::env::current_dir()?,
|
||||
};
|
||||
let pattern_text = match pattern {
|
||||
Some(pattern) => pattern,
|
||||
None => {
|
||||
reporter.warn_no_search_pattern(&search_directory);
|
||||
#[cfg(unix)]
|
||||
Command::new("ls")
|
||||
.arg("-al")
|
||||
.current_dir(search_directory)
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.status()
|
||||
.await?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
Command::new("cmd")
|
||||
.arg("/c")
|
||||
.arg(search_directory)
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.status()
|
||||
.await?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let FileSearchResults {
|
||||
total_match_count,
|
||||
matches,
|
||||
} = run(
|
||||
&pattern_text,
|
||||
vec![search_directory.to_path_buf()],
|
||||
FileSearchOptions {
|
||||
limit,
|
||||
exclude,
|
||||
threads,
|
||||
compute_indices,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)?;
|
||||
let match_count = matches.len();
|
||||
let matches_truncated = total_match_count > match_count;
|
||||
|
||||
for file_match in matches {
|
||||
reporter.report_match(&file_match);
|
||||
}
|
||||
if matches_truncated {
|
||||
reporter.warn_matches_truncated(total_match_count, match_count);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The worker threads will periodically check `cancel_flag` to see if they
|
||||
/// should stop processing files.
|
||||
pub fn run(
|
||||
pattern_text: &str,
|
||||
roots: Vec<PathBuf>,
|
||||
options: FileSearchOptions,
|
||||
cancel_flag: Option<Arc<AtomicBool>>,
|
||||
) -> anyhow::Result<FileSearchResults> {
|
||||
let reporter = Arc::new(RunReporter::default());
|
||||
let session = create_session(roots, options, reporter.clone(), cancel_flag)?;
|
||||
|
||||
session.update_query(pattern_text);
|
||||
|
||||
let snapshot = reporter.wait_for_complete();
|
||||
Ok(FileSearchResults {
|
||||
matches: snapshot.matches,
|
||||
total_match_count: snapshot.total_match_count,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sort matches in-place by descending score, then ascending path.
|
||||
#[cfg(test)]
|
||||
fn sort_matches(matches: &mut [(u32, String)]) {
|
||||
matches.sort_by(cmp_by_score_desc_then_path_asc::<(u32, String), _, _>(
|
||||
|t| t.0,
|
||||
|t| t.1.as_str(),
|
||||
));
|
||||
}
|
||||
|
||||
/// Returns a comparator closure suitable for `slice.sort_by(...)` that orders
|
||||
/// items by descending score and then ascending path using the provided accessors.
|
||||
pub fn cmp_by_score_desc_then_path_asc<T, FScore, FPath>(
|
||||
score_of: FScore,
|
||||
path_of: FPath,
|
||||
) -> impl FnMut(&T, &T) -> std::cmp::Ordering
|
||||
where
|
||||
FScore: Fn(&T) -> u32,
|
||||
FPath: Fn(&T) -> &str,
|
||||
{
|
||||
use std::cmp::Ordering;
|
||||
move |a, b| match score_of(b).cmp(&score_of(a)) {
|
||||
Ordering::Equal => path_of(a).cmp(path_of(b)),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn create_pattern(pattern: &str) -> Pattern {
|
||||
Pattern::new(
|
||||
pattern,
|
||||
CaseMatching::Ignore,
|
||||
Normalization::Smart,
|
||||
AtomKind::Fuzzy,
|
||||
)
|
||||
}
|
||||
|
||||
struct SessionInner {
|
||||
search_directories: Vec<PathBuf>,
|
||||
limit: usize,
|
||||
threads: usize,
|
||||
compute_indices: bool,
|
||||
respect_gitignore: bool,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
shutdown: Arc<AtomicBool>,
|
||||
reporter: Arc<dyn SessionReporter>,
|
||||
work_tx: Sender<WorkSignal>,
|
||||
}
|
||||
|
||||
enum WorkSignal {
|
||||
QueryUpdated(String),
|
||||
NucleoNotify,
|
||||
WalkComplete,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
fn build_override_matcher(
|
||||
search_directory: &Path,
|
||||
exclude: &[String],
|
||||
) -> anyhow::Result<Option<ignore::overrides::Override>> {
|
||||
if exclude.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut override_builder = OverrideBuilder::new(search_directory);
|
||||
for exclude in exclude {
|
||||
let exclude_pattern = format!("!{exclude}");
|
||||
override_builder.add(&exclude_pattern)?;
|
||||
}
|
||||
let matcher = override_builder.build()?;
|
||||
Ok(Some(matcher))
|
||||
}
|
||||
|
||||
fn get_file_path<'a>(path: &'a Path, search_directories: &[PathBuf]) -> Option<(usize, &'a str)> {
|
||||
let mut best_match: Option<(usize, &Path)> = None;
|
||||
for (idx, root) in search_directories.iter().enumerate() {
|
||||
if let Ok(rel_path) = path.strip_prefix(root) {
|
||||
let root_depth = root.components().count();
|
||||
match best_match {
|
||||
Some((best_idx, _))
|
||||
if search_directories[best_idx].components().count() >= root_depth => {}
|
||||
_ => {
|
||||
best_match = Some((idx, rel_path));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (root_idx, rel_path) = best_match?;
|
||||
rel_path.to_str().map(|p| (root_idx, p))
|
||||
}
|
||||
|
||||
/// Walks the search directories and feeds discovered paths into `nucleo`
|
||||
/// via the injector.
|
||||
///
|
||||
/// The walker uses `require_git(true)` to match git's own ignore semantics:
|
||||
/// git never reads `.gitignore` files from directories above the repository
|
||||
/// root. Without this flag, the `ignore` crate reads `.gitignore` files from
|
||||
/// *all* ancestor directories—a deliberate divergence from git intended for
|
||||
/// non-git use cases—allowing a broad parent ignore (e.g. `~/.gitignore`
|
||||
/// containing `*`) to silently suppress every file in the walk.
|
||||
///
|
||||
/// When `respect_gitignore` is `false`, all git-related ignore processing is
|
||||
/// disabled regardless of this flag.
|
||||
fn walker_worker(
|
||||
inner: Arc<SessionInner>,
|
||||
override_matcher: Option<ignore::overrides::Override>,
|
||||
injector: Injector<IndexedEntry>,
|
||||
) {
|
||||
let Some(first_root) = inner.search_directories.first() else {
|
||||
let _ = inner.work_tx.send(WorkSignal::WalkComplete);
|
||||
return;
|
||||
};
|
||||
|
||||
let mut walk_builder = WalkBuilder::new(first_root);
|
||||
for root in inner.search_directories.iter().skip(1) {
|
||||
walk_builder.add(root);
|
||||
}
|
||||
walk_builder
|
||||
.threads(inner.threads)
|
||||
// Allow hidden entries.
|
||||
.hidden(false)
|
||||
// Follow symlinks to search their contents.
|
||||
.follow_links(true)
|
||||
// Keep ignore behavior aligned with git repositories: only apply
|
||||
// gitignore rules when a git context exists.
|
||||
.require_git(true);
|
||||
if !inner.respect_gitignore {
|
||||
walk_builder
|
||||
.git_ignore(false)
|
||||
.git_global(false)
|
||||
.git_exclude(false)
|
||||
.ignore(false)
|
||||
.parents(false);
|
||||
}
|
||||
if let Some(override_matcher) = override_matcher {
|
||||
walk_builder.overrides(override_matcher);
|
||||
}
|
||||
|
||||
let walker = walk_builder.build_parallel();
|
||||
|
||||
walker.run(|| {
|
||||
const CHECK_INTERVAL: usize = 1024;
|
||||
let mut n = 0;
|
||||
let search_directories = inner.search_directories.clone();
|
||||
let injector = injector.clone();
|
||||
let cancelled = inner.cancelled.clone();
|
||||
let shutdown = inner.shutdown.clone();
|
||||
|
||||
Box::new(move |entry| {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(_) => return ignore::WalkState::Continue,
|
||||
};
|
||||
let path = entry.path();
|
||||
if path.to_str().is_none() {
|
||||
return ignore::WalkState::Continue;
|
||||
}
|
||||
if let Some((root_idx, relative_path)) = get_file_path(path, &search_directories) {
|
||||
let match_type = match entry.file_type() {
|
||||
Some(file_type) if file_type.is_dir() => MatchType::Directory,
|
||||
_ => MatchType::File,
|
||||
};
|
||||
let column = Utf32String::from(relative_path);
|
||||
let indexed_entry = match &column {
|
||||
Utf32String::Ascii(_) => IndexedEntry::Ascii {
|
||||
root_idx,
|
||||
match_type,
|
||||
},
|
||||
Utf32String::Unicode(_) => IndexedEntry::Unicode(Box::new(UnicodeEntry {
|
||||
root_idx,
|
||||
relative_path: Box::from(relative_path),
|
||||
match_type,
|
||||
})),
|
||||
};
|
||||
injector.push(indexed_entry, |_, cols| {
|
||||
cols[0] = column;
|
||||
});
|
||||
}
|
||||
n += 1;
|
||||
if n >= CHECK_INTERVAL {
|
||||
if cancelled.load(Ordering::Relaxed) || shutdown.load(Ordering::Relaxed) {
|
||||
return ignore::WalkState::Quit;
|
||||
}
|
||||
n = 0;
|
||||
}
|
||||
ignore::WalkState::Continue
|
||||
})
|
||||
});
|
||||
let _ = inner.work_tx.send(WorkSignal::WalkComplete);
|
||||
}
|
||||
|
||||
fn matcher_worker(
|
||||
inner: Arc<SessionInner>,
|
||||
work_rx: Receiver<WorkSignal>,
|
||||
mut nucleo: Nucleo<IndexedEntry>,
|
||||
) -> anyhow::Result<()> {
|
||||
const TICK_TIMEOUT_MS: u64 = 10;
|
||||
let config = Config::DEFAULT.match_paths();
|
||||
let mut matcher = Matcher::new(config);
|
||||
let cancel_requested = || inner.cancelled.load(Ordering::Relaxed);
|
||||
let shutdown_requested = || inner.shutdown.load(Ordering::Relaxed);
|
||||
|
||||
let mut last_query = String::new();
|
||||
let mut next_notify = never();
|
||||
let mut will_notify = false;
|
||||
let mut walk_complete = false;
|
||||
let mut ranking = None;
|
||||
|
||||
loop {
|
||||
select! {
|
||||
recv(work_rx) -> signal => {
|
||||
let Ok(signal) = signal else {
|
||||
break;
|
||||
};
|
||||
match signal {
|
||||
WorkSignal::QueryUpdated(query) => {
|
||||
ranking = None;
|
||||
let append = query.starts_with(&last_query);
|
||||
nucleo.pattern.reparse(
|
||||
0,
|
||||
&query,
|
||||
CaseMatching::Ignore,
|
||||
Normalization::Smart,
|
||||
append,
|
||||
);
|
||||
last_query = query;
|
||||
will_notify = true;
|
||||
next_notify = after(Duration::from_millis(0));
|
||||
}
|
||||
WorkSignal::NucleoNotify => {
|
||||
if !will_notify {
|
||||
will_notify = true;
|
||||
next_notify = after(Duration::from_millis(TICK_TIMEOUT_MS));
|
||||
}
|
||||
}
|
||||
WorkSignal::WalkComplete => {
|
||||
walk_complete = true;
|
||||
if !will_notify {
|
||||
will_notify = true;
|
||||
next_notify = after(Duration::from_millis(0));
|
||||
}
|
||||
}
|
||||
WorkSignal::Shutdown => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
recv(next_notify) -> _ => {
|
||||
will_notify = false;
|
||||
if ranking.is_none() {
|
||||
let status = nucleo.tick(TICK_TIMEOUT_MS);
|
||||
if status.changed {
|
||||
ranking = snapshot::Ranking::start(&nucleo, &last_query, walk_complete);
|
||||
}
|
||||
if ranking.is_none() && !status.running && walk_complete {
|
||||
inner.reporter.on_complete();
|
||||
}
|
||||
}
|
||||
if let Some(active) = &mut ranking {
|
||||
if let Some(snapshot) = active.advance(
|
||||
&inner, &nucleo, &last_query, &mut matcher,
|
||||
Duration::from_millis(TICK_TIMEOUT_MS),
|
||||
) {
|
||||
inner.reporter.on_update(&snapshot);
|
||||
ranking = None;
|
||||
}
|
||||
// Resume this snapshot or collect work that arrived while ranking it.
|
||||
will_notify = true;
|
||||
next_notify = after(Duration::ZERO);
|
||||
}
|
||||
}
|
||||
default(Duration::from_millis(100)) => {
|
||||
// Occasionally check the cancel flag.
|
||||
}
|
||||
}
|
||||
|
||||
if cancel_requested() || shutdown_requested() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we cancelled or otherwise exited the loop, make sure the reporter is notified.
|
||||
inner.reporter.on_complete();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RunReporter {
|
||||
snapshot: RwLock<FileSearchSnapshot>,
|
||||
completed: (Condvar, Mutex<bool>),
|
||||
}
|
||||
|
||||
impl SessionReporter for RunReporter {
|
||||
fn on_update(&self, snapshot: &FileSearchSnapshot) {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut guard = self.snapshot.write().unwrap();
|
||||
*guard = snapshot.clone();
|
||||
}
|
||||
|
||||
fn on_complete(&self) {
|
||||
let (cv, mutex) = &self.completed;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut completed = mutex.lock().unwrap();
|
||||
*completed = true;
|
||||
cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
impl RunReporter {
|
||||
fn wait_for_complete(&self) -> FileSearchSnapshot {
|
||||
let (cv, mutex) = &self.completed;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut completed = mutex.lock().unwrap();
|
||||
while !*completed {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
{
|
||||
completed = cv.wait(completed).unwrap();
|
||||
}
|
||||
}
|
||||
#[allow(clippy::unwrap_used)]
|
||||
self.snapshot.read().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
614
akode-rs/file-search/src/lib_tests.rs
Normal file
614
akode-rs/file-search/src/lib_tests.rs
Normal file
@@ -0,0 +1,614 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Condvar;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn verify_score_is_none_for_non_match() {
|
||||
let mut utf32buf = Vec::<char>::new();
|
||||
let line = "hello";
|
||||
let mut matcher = Matcher::new(Config::DEFAULT);
|
||||
let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut utf32buf);
|
||||
let pattern = create_pattern("zzz");
|
||||
let score = pattern.score(haystack, &mut matcher);
|
||||
assert_eq!(score, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tie_breakers_sort_by_path_when_scores_equal() {
|
||||
let mut matches = vec![
|
||||
(100, "b_path".to_string()),
|
||||
(100, "a_path".to_string()),
|
||||
(90, "zzz".to_string()),
|
||||
];
|
||||
|
||||
sort_matches(&mut matches);
|
||||
|
||||
// Highest score first; ties broken alphabetically.
|
||||
let expected = vec![
|
||||
(100, "a_path".to_string()),
|
||||
(100, "b_path".to_string()),
|
||||
(90, "zzz".to_string()),
|
||||
];
|
||||
|
||||
assert_eq!(matches, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_filenames_survive_the_path_result_limit() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let folder = root.path().join("viewmodel");
|
||||
fs::create_dir(&folder).unwrap();
|
||||
fs::write(folder.join("build.gradle.kts"), "").unwrap();
|
||||
let source = Path::new("feature").join("src");
|
||||
fs::create_dir_all(root.path().join(&source)).unwrap();
|
||||
let filename = source.join("ChatViewModel.kt");
|
||||
fs::write(root.path().join(&filename), "").unwrap();
|
||||
|
||||
let search = |query, limit| {
|
||||
run(
|
||||
query,
|
||||
vec![root.path().to_path_buf()],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(limit).unwrap(),
|
||||
..Default::default()
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.unwrap()
|
||||
.matches
|
||||
};
|
||||
for i in 0..80 {
|
||||
fs::create_dir_all(root.path().join(format!("parent-{i}/viewmodel"))).unwrap();
|
||||
}
|
||||
let hits = search("ViewModel", 2);
|
||||
assert_eq!(hits[0].match_type, MatchType::Directory);
|
||||
assert_eq!(hits[1].path, filename);
|
||||
assert_eq!(search("VM", 1)[0].path, filename);
|
||||
fs::create_dir(root.path().join("src")).unwrap();
|
||||
for i in 0..80 {
|
||||
fs::write(root.path().join(format!("source-{i}.rs")), "").unwrap();
|
||||
}
|
||||
assert_eq!(search("src", 1)[0].path, Path::new("src"));
|
||||
fs::write(root.path().join(&source).join("src"), "").unwrap();
|
||||
assert_eq!(search("src", 1)[0].path, source.join("src"));
|
||||
assert_eq!(
|
||||
search(&format!("viewmodel{}", std::path::MAIN_SEPARATOR), 1)[0].path,
|
||||
Path::new("viewmodel").join("build.gradle.kts")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_name_from_path_uses_basename() {
|
||||
assert_eq!(file_name_from_path("foo/bar.txt"), "bar.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_name_from_path_falls_back_to_full_path() {
|
||||
assert_eq!(file_name_from_path(""), "");
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct RecordingReporter {
|
||||
updates: Mutex<Vec<FileSearchSnapshot>>,
|
||||
complete_times: Mutex<Vec<Instant>>,
|
||||
complete_cv: Condvar,
|
||||
update_cv: Condvar,
|
||||
}
|
||||
|
||||
impl RecordingReporter {
|
||||
fn wait_until<T, F>(
|
||||
&self,
|
||||
mutex: &Mutex<T>,
|
||||
cv: &Condvar,
|
||||
timeout: Duration,
|
||||
mut predicate: F,
|
||||
) -> bool
|
||||
where
|
||||
F: FnMut(&T) -> bool,
|
||||
{
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut state = mutex.lock().unwrap();
|
||||
loop {
|
||||
if predicate(&state) {
|
||||
return true;
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return false;
|
||||
}
|
||||
let (next_state, wait_result) = cv.wait_timeout(state, remaining).unwrap();
|
||||
state = next_state;
|
||||
if wait_result.timed_out() {
|
||||
return predicate(&state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_complete(&self, timeout: Duration) -> bool {
|
||||
self.wait_until(
|
||||
&self.complete_times,
|
||||
&self.complete_cv,
|
||||
timeout,
|
||||
|completes| !completes.is_empty(),
|
||||
)
|
||||
}
|
||||
fn clear(&self) {
|
||||
self.updates.lock().unwrap().clear();
|
||||
self.complete_times.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
fn updates(&self) -> Vec<FileSearchSnapshot> {
|
||||
self.updates.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
fn wait_for_updates_at_least(&self, min_len: usize, timeout: Duration) -> bool {
|
||||
self.wait_until(&self.updates, &self.update_cv, timeout, |updates| {
|
||||
updates.len() >= min_len
|
||||
})
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> FileSearchSnapshot {
|
||||
self.updates
|
||||
.lock()
|
||||
.unwrap()
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionReporter for RecordingReporter {
|
||||
fn on_update(&self, snapshot: &FileSearchSnapshot) {
|
||||
let mut updates = self.updates.lock().unwrap();
|
||||
updates.push(snapshot.clone());
|
||||
self.update_cv.notify_all();
|
||||
}
|
||||
|
||||
fn on_complete(&self) {
|
||||
{
|
||||
let mut complete_times = self.complete_times.lock().unwrap();
|
||||
complete_times.push(Instant::now());
|
||||
}
|
||||
self.complete_cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn create_temp_tree(file_count: usize) -> TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for i in 0..file_count {
|
||||
let path = dir.path().join(format!("file-{i:04}.txt"));
|
||||
fs::write(path, format!("contents {i}")).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_scanned_file_count_is_monotonic_across_queries() {
|
||||
let dir = create_temp_tree(/*file_count*/ 200);
|
||||
let reporter = Arc::new(RecordingReporter::default());
|
||||
let session = create_session(
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter.clone(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
session.update_query("file-00");
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
let first_snapshot = reporter.snapshot();
|
||||
session.update_query("file-01");
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
let second_snapshot = reporter.snapshot();
|
||||
let _ = reporter.wait_for_complete(Duration::from_secs(5));
|
||||
let completed_snapshot = reporter.snapshot();
|
||||
|
||||
assert!(second_snapshot.scanned_file_count >= first_snapshot.scanned_file_count);
|
||||
assert!(completed_snapshot.scanned_file_count >= second_snapshot.scanned_file_count);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_streams_updates_before_walk_complete() {
|
||||
let dir = create_temp_tree(/*file_count*/ 600);
|
||||
let reporter = Arc::new(RecordingReporter::default());
|
||||
let session = create_session(
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter.clone(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
session.update_query("file-0");
|
||||
let completed = reporter.wait_for_complete(Duration::from_secs(5));
|
||||
|
||||
assert!(completed);
|
||||
let updates = reporter.updates();
|
||||
assert!(updates.iter().any(|snapshot| !snapshot.walk_complete));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_accepts_query_updates_after_walk_complete() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join("alpha.txt"), "alpha").unwrap();
|
||||
fs::write(dir.path().join("beta.txt"), "beta").unwrap();
|
||||
let reporter = Arc::new(RecordingReporter::default());
|
||||
let session = create_session(
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter.clone(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
session.update_query("alpha");
|
||||
assert!(reporter.wait_for_complete(Duration::from_secs(5)));
|
||||
let updates_before = reporter.updates().len();
|
||||
|
||||
session.update_query("beta");
|
||||
assert!(reporter.wait_for_updates_at_least(updates_before + 1, Duration::from_secs(5),));
|
||||
|
||||
let updates = reporter.updates();
|
||||
let last_update = updates.last().cloned().expect("update");
|
||||
assert!(
|
||||
last_update
|
||||
.matches
|
||||
.iter()
|
||||
.any(|file_match| file_match.path.to_string_lossy().contains("beta.txt"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_emits_complete_when_query_changes_with_no_matches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join("alpha.txt"), "alpha").unwrap();
|
||||
fs::write(dir.path().join("beta.txt"), "beta").unwrap();
|
||||
let reporter = Arc::new(RecordingReporter::default());
|
||||
let session = create_session(
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter.clone(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
session.update_query("asdf");
|
||||
assert!(reporter.wait_for_complete(Duration::from_secs(5)));
|
||||
|
||||
let completed_snapshot = reporter.snapshot();
|
||||
assert_eq!(completed_snapshot.matches, Vec::new());
|
||||
assert_eq!(completed_snapshot.total_match_count, 0);
|
||||
|
||||
reporter.clear();
|
||||
|
||||
session.update_query("asdfa");
|
||||
assert!(reporter.wait_for_complete(Duration::from_secs(5)));
|
||||
assert!(!reporter.updates().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_session_does_not_cancel_siblings_with_shared_cancel_flag() {
|
||||
let root_a = create_temp_tree(/*file_count*/ 200);
|
||||
let root_b = create_temp_tree(/*file_count*/ 4_000);
|
||||
let cancel_flag = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let reporter_a = Arc::new(RecordingReporter::default());
|
||||
let session_a = create_session(
|
||||
vec![root_a.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter_a,
|
||||
Some(cancel_flag.clone()),
|
||||
)
|
||||
.expect("session_a");
|
||||
|
||||
let reporter_b = Arc::new(RecordingReporter::default());
|
||||
let session_b = create_session(
|
||||
vec![root_b.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter_b.clone(),
|
||||
Some(cancel_flag),
|
||||
)
|
||||
.expect("session_b");
|
||||
|
||||
session_a.update_query("file-0");
|
||||
session_b.update_query("file-1");
|
||||
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
drop(session_a);
|
||||
|
||||
let completed = reporter_b.wait_for_complete(Duration::from_secs(5));
|
||||
assert_eq!(completed, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_emits_updates_when_query_changes() {
|
||||
let dir = create_temp_tree(/*file_count*/ 200);
|
||||
let reporter = Arc::new(RecordingReporter::default());
|
||||
let session = create_session(
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
reporter.clone(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
session.update_query("zzzzzzzz");
|
||||
let completed = reporter.wait_for_complete(Duration::from_secs(5));
|
||||
assert!(completed);
|
||||
|
||||
reporter.clear();
|
||||
|
||||
session.update_query("zzzzzzzzq");
|
||||
let completed = reporter.wait_for_complete(Duration::from_secs(5));
|
||||
assert!(completed);
|
||||
|
||||
let updates = reporter.updates();
|
||||
assert_eq!(updates.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_returns_matches_for_query() {
|
||||
let dir = create_temp_tree(/*file_count*/ 40);
|
||||
let options = FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
};
|
||||
let results = run(
|
||||
"file-000",
|
||||
vec![dir.path().to_path_buf()],
|
||||
options,
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
|
||||
assert!(!results.matches.is_empty());
|
||||
assert!(results.total_match_count >= results.matches.len());
|
||||
assert!(
|
||||
results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.to_string_lossy().contains("file-0000.txt"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_returns_directory_matches_for_query() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(dir.path().join("docs/guides")).unwrap();
|
||||
fs::write(dir.path().join("docs/guides/intro.md"), "intro").unwrap();
|
||||
fs::write(dir.path().join("docs/readme.md"), "readme").unwrap();
|
||||
|
||||
let results = run(
|
||||
"guides",
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
|
||||
assert!(results.matches.iter().any(|m| {
|
||||
m.path == std::path::Path::new("docs").join("guides")
|
||||
&& m.match_type == MatchType::Directory
|
||||
}));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_classifies_followed_directory_symlink_as_directory() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::create_dir(dir.path().join("guides")).unwrap();
|
||||
symlink(dir.path().join("guides"), dir.path().join("guides-link")).unwrap();
|
||||
|
||||
let results = run(
|
||||
"guides-link",
|
||||
vec![dir.path().to_path_buf()],
|
||||
FileSearchOptions::default(),
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
|
||||
assert!(results.matches.iter().any(|file_match| {
|
||||
file_match.path == Path::new("guides-link") && file_match.match_type == MatchType::Directory
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_exits_run() {
|
||||
let dir = create_temp_tree(/*file_count*/ 200);
|
||||
let cancel_flag = Arc::new(AtomicBool::new(true));
|
||||
let search_dir = dir.path().to_path_buf();
|
||||
let options = FileSearchOptions {
|
||||
compute_indices: false,
|
||||
..Default::default()
|
||||
};
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
|
||||
let handle = thread::spawn(move || {
|
||||
let result = run("file-", vec![search_dir], options, Some(cancel_flag));
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
|
||||
let result = rx
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("run should exit after cancellation");
|
||||
handle.join().unwrap();
|
||||
|
||||
let results = result.expect("run ok");
|
||||
assert_eq!(results.matches, Vec::new());
|
||||
assert_eq!(results.total_match_count, 0);
|
||||
}
|
||||
|
||||
/// Regression test for #3493: a parent directory's `.gitignore` with `*`
|
||||
/// must not suppress files discovered inside a child "repo" directory.
|
||||
///
|
||||
/// The fixture intentionally omits `git init` so that no `.git` directory
|
||||
/// exists. With `require_git(true)`, the walker skips all gitignore
|
||||
/// processing, making the parent's broad ignore harmless.
|
||||
#[test]
|
||||
fn parent_gitignore_outside_repo_does_not_hide_repo_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let parent = temp.path().join("home");
|
||||
let repo = parent.join("repo");
|
||||
fs::create_dir_all(repo.join(".vscode")).unwrap();
|
||||
|
||||
fs::write(parent.join(".gitignore"), "*\n!.gitignore\n").unwrap();
|
||||
fs::write(
|
||||
repo.join(".gitignore"),
|
||||
".vscode/*\n!.vscode/\n!.vscode/settings.json\n!package.json\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(repo.join("package.json"), "{ \"name\": \"demo\" }\n").unwrap();
|
||||
fs::write(repo.join(".vscode/settings.json"), "{ \"editor\": true }\n").unwrap();
|
||||
|
||||
let respect_results = run(
|
||||
"package",
|
||||
vec![repo.clone()],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
assert!(
|
||||
respect_results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.as_path() == Path::new("package.json"))
|
||||
);
|
||||
|
||||
let nested_file_results = run(
|
||||
"settings",
|
||||
vec![repo],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
assert!(
|
||||
nested_file_results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.as_path() == Path::new(".vscode/settings.json"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_repo_still_respects_local_gitignore_when_enabled() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let parent = temp.path().join("home");
|
||||
let repo = parent.join("repo");
|
||||
fs::create_dir_all(repo.join(".vscode")).unwrap();
|
||||
|
||||
fs::write(parent.join(".gitignore"), "*\n!.gitignore\n").unwrap();
|
||||
fs::write(
|
||||
repo.join(".gitignore"),
|
||||
".vscode/*\n!.vscode/\n!.vscode/settings.json\n!package.json\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(repo.join("package.json"), "{ \"name\": \"demo\" }\n").unwrap();
|
||||
fs::write(repo.join(".vscode/settings.json"), "{ \"editor\": true }\n").unwrap();
|
||||
fs::write(
|
||||
repo.join(".vscode/extensions.json"),
|
||||
"{ \"extensions\": [] }\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
fs::create_dir_all(repo.join(".git")).unwrap();
|
||||
|
||||
let package_results = run(
|
||||
"package",
|
||||
vec![repo.clone()],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
assert!(
|
||||
package_results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.as_path() == Path::new("package.json"))
|
||||
);
|
||||
|
||||
let ignored_results = run(
|
||||
"extensions.json",
|
||||
vec![repo.clone()],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
assert!(
|
||||
!ignored_results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.as_path() == Path::new(".vscode/extensions.json"))
|
||||
);
|
||||
|
||||
let whitelisted_results = run(
|
||||
"settings.json",
|
||||
vec![repo],
|
||||
FileSearchOptions {
|
||||
limit: NonZero::new(20).unwrap(),
|
||||
exclude: Vec::new(),
|
||||
threads: NonZero::new(2).unwrap(),
|
||||
compute_indices: false,
|
||||
respect_gitignore: true,
|
||||
},
|
||||
/*cancel_flag*/ None,
|
||||
)
|
||||
.expect("run ok");
|
||||
assert!(
|
||||
whitelisted_results
|
||||
.matches
|
||||
.iter()
|
||||
.any(|m| m.path.as_path() == Path::new(".vscode/settings.json"))
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "matcher_tests.rs"]
|
||||
mod matcher_tests;
|
||||
83
akode-rs/file-search/src/main.rs
Normal file
83
akode-rs/file-search/src/main.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::io::IsTerminal;
|
||||
use std::path::Path;
|
||||
|
||||
use clap::Parser;
|
||||
use akode_file_search::Cli;
|
||||
use akode_file_search::FileMatch;
|
||||
use akode_file_search::Reporter;
|
||||
use akode_file_search::run_main;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
let reporter = StdioReporter {
|
||||
write_output_as_json: cli.json,
|
||||
show_indices: cli.compute_indices && std::io::stdout().is_terminal(),
|
||||
};
|
||||
run_main(cli, reporter).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct StdioReporter {
|
||||
write_output_as_json: bool,
|
||||
show_indices: bool,
|
||||
}
|
||||
|
||||
impl Reporter for StdioReporter {
|
||||
fn report_match(&self, file_match: &FileMatch) {
|
||||
if self.write_output_as_json {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let json = serde_json::to_string(file_match).unwrap();
|
||||
println!("{json}");
|
||||
} else if self.show_indices {
|
||||
#[allow(clippy::expect_used)]
|
||||
let indices = file_match
|
||||
.indices
|
||||
.as_ref()
|
||||
.expect("--compute-indices was specified");
|
||||
// `indices` is guaranteed to be sorted in ascending order. Instead
|
||||
// of calling `contains` for every character (which would be O(N^2)
|
||||
// in the worst-case), walk through the `indices` vector once while
|
||||
// iterating over the characters.
|
||||
let mut indices_iter = indices.iter().peekable();
|
||||
|
||||
for (i, c) in file_match.path.to_string_lossy().chars().enumerate() {
|
||||
match indices_iter.peek() {
|
||||
Some(next) if **next == i as u32 => {
|
||||
// ANSI escape code for bold: \x1b[1m ... \x1b[0m
|
||||
print!("\x1b[1m{c}\x1b[0m");
|
||||
// advance the iterator since we've consumed this index
|
||||
indices_iter.next();
|
||||
}
|
||||
_ => {
|
||||
print!("{c}");
|
||||
}
|
||||
}
|
||||
}
|
||||
println!();
|
||||
} else {
|
||||
println!("{}", file_match.path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
fn warn_matches_truncated(&self, total_match_count: usize, shown_match_count: usize) {
|
||||
if self.write_output_as_json {
|
||||
let value = json!({"matches_truncated": true});
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let json = serde_json::to_string(&value).unwrap();
|
||||
println!("{json}");
|
||||
} else {
|
||||
eprintln!(
|
||||
"Warning: showing {shown_match_count} out of {total_match_count} results. Provide a more specific pattern or increase the --limit.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn warn_no_search_pattern(&self, search_directory: &Path) {
|
||||
eprintln!(
|
||||
"No search pattern specified. Showing the contents of the current directory ({}):",
|
||||
search_directory.to_string_lossy()
|
||||
);
|
||||
}
|
||||
}
|
||||
109
akode-rs/file-search/src/matcher_tests.rs
Normal file
109
akode-rs/file-search/src/matcher_tests.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
//! Regression coverage for associating asynchronous matcher results with their query.
|
||||
|
||||
use crate::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn query_update_does_not_relabel_pending_matches() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (work_tx, work_rx) = unbounded();
|
||||
let notify_tx = work_tx.clone();
|
||||
let mut nucleo = Nucleo::new(
|
||||
Config::DEFAULT.match_paths(),
|
||||
Arc::new(move || {
|
||||
let _ = notify_tx.send(WorkSignal::NucleoNotify);
|
||||
}),
|
||||
/*num_threads*/ Some(1),
|
||||
/*columns*/ 1,
|
||||
);
|
||||
let injector = nucleo.injector();
|
||||
for (relative, match_type) in [("", MatchType::Directory), ("beta.txt", MatchType::File)] {
|
||||
injector.push(
|
||||
IndexedEntry::Ascii {
|
||||
root_idx: 0,
|
||||
match_type,
|
||||
},
|
||||
|_, columns| columns[0] = Utf32String::from(relative),
|
||||
);
|
||||
}
|
||||
while nucleo.tick(/*timeout*/ 10).running {
|
||||
work_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
}
|
||||
let inner = SessionInner {
|
||||
search_directories: vec![root.path().to_path_buf()],
|
||||
limit: 50,
|
||||
threads: 1,
|
||||
compute_indices: true,
|
||||
respect_gitignore: true,
|
||||
cancelled: Arc::new(AtomicBool::new(false)),
|
||||
shutdown: Arc::new(AtomicBool::new(false)),
|
||||
reporter: Arc::new(tests::RecordingReporter::default()),
|
||||
work_tx,
|
||||
};
|
||||
let mut matcher = Matcher::new(Config::DEFAULT.match_paths());
|
||||
let snapshot = |nucleo: &Nucleo<IndexedEntry>, query: &str, matcher: &mut Matcher| {
|
||||
snapshot::Ranking::start(nucleo, query, /*walk_complete*/ true)?.advance(
|
||||
&inner,
|
||||
nucleo,
|
||||
query,
|
||||
matcher,
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
};
|
||||
let initial = snapshot(&nucleo, "", &mut matcher).unwrap();
|
||||
assert_eq!(initial.matches.len(), 2);
|
||||
|
||||
nucleo.pattern.reparse(
|
||||
/*column*/ 0,
|
||||
"bet",
|
||||
CaseMatching::Ignore,
|
||||
Normalization::Smart,
|
||||
/*append*/ true,
|
||||
);
|
||||
// The requested pattern has changed, but no tick has replaced the previous
|
||||
// snapshot. This is the same intermediate state a busy tick can expose.
|
||||
assert_eq!(snapshot(&nucleo, "bet", &mut matcher), None);
|
||||
|
||||
while nucleo.tick(/*timeout*/ 10).running {
|
||||
work_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
snapshot(&nucleo, "bet", &mut matcher),
|
||||
Some(FileSearchSnapshot {
|
||||
query: "bet".to_string(),
|
||||
matches: vec![FileMatch {
|
||||
score: 65_536 + 84,
|
||||
path: PathBuf::from("beta.txt"),
|
||||
match_type: MatchType::File,
|
||||
root: root.path().to_path_buf(),
|
||||
indices: Some(vec![0, 1, 2]),
|
||||
}],
|
||||
total_match_count: 1,
|
||||
scanned_file_count: 2,
|
||||
walk_complete: true,
|
||||
}),
|
||||
);
|
||||
// Force the pending ranking to span worker turns, then resume it on the same snapshot.
|
||||
for i in 0..256 {
|
||||
injector.push(
|
||||
IndexedEntry::Ascii {
|
||||
root_idx: 0,
|
||||
match_type: MatchType::File,
|
||||
},
|
||||
|_, columns| columns[0] = Utf32String::from(format!("bet/path-{i}")),
|
||||
);
|
||||
}
|
||||
while nucleo.tick(/*timeout*/ 10).running {
|
||||
work_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
}
|
||||
let mut partial = snapshot::Ranking::start(&nucleo, "bet", /*walk_complete*/ true).unwrap();
|
||||
assert!(
|
||||
partial
|
||||
.advance(&inner, &nucleo, "bet", &mut matcher, Duration::ZERO)
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
partial.advance(&inner, &nucleo, "bet", &mut matcher, Duration::from_secs(5)),
|
||||
snapshot(&nucleo, "bet", &mut matcher)
|
||||
);
|
||||
}
|
||||
216
akode-rs/file-search/src/snapshot.rs
Normal file
216
akode-rs/file-search/src/snapshot.rs
Normal file
@@ -0,0 +1,216 @@
|
||||
//! Ranks a stable matcher snapshot in slices so the worker can handle new queries.
|
||||
|
||||
use crate::FileMatch;
|
||||
use crate::FileSearchSnapshot;
|
||||
use crate::IndexedEntry;
|
||||
use crate::MatchType;
|
||||
use crate::SessionInner;
|
||||
use nucleo::Match;
|
||||
use nucleo::Matcher;
|
||||
use nucleo::Nucleo;
|
||||
use nucleo::Utf32Str;
|
||||
use nucleo::Utf32String;
|
||||
use nucleo::pattern::AtomKind;
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
// A single Nucleo atom returns a u16. Leave room for its full score within each group.
|
||||
const NAME_BONUS: u32 = u16::MAX as u32 + 1;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Ranking {
|
||||
next: usize,
|
||||
best: BinaryHeap<(Reverse<u32>, usize)>,
|
||||
found_exact_folder: bool,
|
||||
rank_names: bool,
|
||||
walk_complete: bool,
|
||||
}
|
||||
|
||||
impl Ranking {
|
||||
pub(super) fn start(
|
||||
nucleo: &Nucleo<IndexedEntry>,
|
||||
query: &str,
|
||||
walk_complete: bool,
|
||||
) -> Option<Self> {
|
||||
let pattern = nucleo.snapshot().pattern().column_pattern(0);
|
||||
// A tick can collect the previous query while the new one is running.
|
||||
if pattern.atoms != nucleo.pattern.column_pattern(0).atoms {
|
||||
return None;
|
||||
}
|
||||
let rank_names = matches!(pattern.atoms.as_slice(), [atom] if atom.kind == AtomKind::Fuzzy && !atom.negative)
|
||||
&& !query.contains(['/', '\\']);
|
||||
Some(Self {
|
||||
rank_names,
|
||||
walk_complete,
|
||||
..Self::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Yields to the worker between slices so a new query or cancellation can preempt this snapshot.
|
||||
pub(super) fn advance(
|
||||
&mut self,
|
||||
inner: &SessionInner,
|
||||
nucleo: &Nucleo<IndexedEntry>,
|
||||
query: &str,
|
||||
matcher: &mut Matcher,
|
||||
budget: Duration,
|
||||
) -> Option<FileSearchSnapshot> {
|
||||
let snapshot = nucleo.snapshot();
|
||||
let ranked = snapshot.matches();
|
||||
if !self.rank_names {
|
||||
return Some(collect(
|
||||
inner,
|
||||
nucleo,
|
||||
query,
|
||||
matcher,
|
||||
self.walk_complete,
|
||||
ranked
|
||||
.iter()
|
||||
.copied()
|
||||
.take(inner.limit)
|
||||
.map(|matched| (matched, false)),
|
||||
));
|
||||
}
|
||||
let name = &snapshot.pattern().column_pattern(0).atoms[0];
|
||||
let deadline = Instant::now() + budget;
|
||||
for (matched, item) in ranked[self.next..]
|
||||
.iter()
|
||||
.zip(snapshot.matched_items(self.next as u32..))
|
||||
{
|
||||
let kind = match item.data {
|
||||
IndexedEntry::Ascii { match_type, .. } => *match_type,
|
||||
IndexedEntry::Unicode(entry) => entry.match_type,
|
||||
};
|
||||
let basename = basename(item.matcher_columns[0].slice(..));
|
||||
let exact_length = basename.len() == name.needle_text().len();
|
||||
let score = match kind {
|
||||
MatchType::File => name.score(basename, matcher).map(|score| {
|
||||
let bonus = if exact_length {
|
||||
3 * NAME_BONUS
|
||||
} else {
|
||||
NAME_BONUS
|
||||
};
|
||||
bonus + u32::from(score)
|
||||
}),
|
||||
// Keep the strongest exact folder. More folders with the same name
|
||||
// compete in path order so they cannot crowd out matching files.
|
||||
MatchType::Directory
|
||||
if !self.found_exact_folder
|
||||
&& exact_length
|
||||
&& name.score(basename, matcher).is_some() =>
|
||||
{
|
||||
self.found_exact_folder = true;
|
||||
Some(2 * NAME_BONUS + matched.score)
|
||||
}
|
||||
MatchType::Directory => None,
|
||||
}
|
||||
.unwrap_or(matched.score);
|
||||
// The heap head is the lowest score, then the latest path on a tie.
|
||||
let candidate = (Reverse(score), self.next);
|
||||
if self.best.len() < inner.limit {
|
||||
self.best.push(candidate);
|
||||
} else if let Some(mut worst) = self.best.peek_mut()
|
||||
&& candidate < *worst
|
||||
{
|
||||
*worst = candidate;
|
||||
}
|
||||
self.next += 1;
|
||||
if self.next.is_multiple_of(64) && Instant::now() >= deadline {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let selected = std::mem::take(&mut self.best)
|
||||
.into_sorted_vec()
|
||||
.into_iter()
|
||||
.map(|(Reverse(score), index)| {
|
||||
(
|
||||
Match {
|
||||
score,
|
||||
idx: ranked[index].idx,
|
||||
},
|
||||
score >= NAME_BONUS,
|
||||
)
|
||||
});
|
||||
Some(collect(
|
||||
inner,
|
||||
nucleo,
|
||||
query,
|
||||
matcher,
|
||||
self.walk_complete,
|
||||
selected,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(
|
||||
inner: &SessionInner,
|
||||
nucleo: &Nucleo<IndexedEntry>,
|
||||
query: &str,
|
||||
matcher: &mut Matcher,
|
||||
walk_complete: bool,
|
||||
candidates: impl Iterator<Item = (Match, bool)>,
|
||||
) -> FileSearchSnapshot {
|
||||
let snapshot = nucleo.snapshot();
|
||||
let pattern = snapshot.pattern().column_pattern(0);
|
||||
let matches = candidates
|
||||
.filter_map(|(match_, matched_name)| {
|
||||
let item = snapshot.get_item(match_.idx)?;
|
||||
let (root_idx, relative_path, match_type) = match item.data {
|
||||
IndexedEntry::Ascii {
|
||||
root_idx,
|
||||
match_type,
|
||||
} => {
|
||||
let Utf32String::Ascii(path) = &item.matcher_columns[0] else {
|
||||
return None;
|
||||
};
|
||||
(*root_idx, path.as_ref(), *match_type)
|
||||
}
|
||||
IndexedEntry::Unicode(entry) => (
|
||||
entry.root_idx,
|
||||
entry.relative_path.as_ref(),
|
||||
entry.match_type,
|
||||
),
|
||||
};
|
||||
let indices = if inner.compute_indices {
|
||||
let mut indices = Vec::<u32>::new();
|
||||
let path = item.matcher_columns[0].slice(..);
|
||||
let haystack = if matched_name { basename(path) } else { path };
|
||||
let _ = pattern.indices(haystack, matcher, &mut indices);
|
||||
for index in &mut indices {
|
||||
*index += (path.len() - haystack.len()) as u32;
|
||||
}
|
||||
indices.sort_unstable();
|
||||
indices.dedup();
|
||||
Some(indices)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(FileMatch {
|
||||
score: match_.score,
|
||||
path: PathBuf::from(relative_path),
|
||||
match_type,
|
||||
root: inner.search_directories[root_idx].clone(),
|
||||
indices,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
FileSearchSnapshot {
|
||||
query: query.to_string(),
|
||||
matches,
|
||||
total_match_count: snapshot.matched_item_count() as usize,
|
||||
scanned_file_count: snapshot.item_count() as usize,
|
||||
walk_complete,
|
||||
}
|
||||
}
|
||||
|
||||
fn basename(path: Utf32Str<'_>) -> Utf32Str<'_> {
|
||||
let len = path
|
||||
.chars()
|
||||
.rev()
|
||||
.take_while(|c| !std::path::is_separator(*c))
|
||||
.count();
|
||||
path.slice(path.len() - len..)
|
||||
}
|
||||
Reference in New Issue
Block a user