Skip to main content

vtcode_indexer/
lib.rs

1#![allow(
2    missing_docs,
3    dead_code,
4    unused_imports,
5    reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7#![expect(
8    unused_results,
9    reason = "Indexer cache and walker updates intentionally use mutation APIs for side effects and discard prior entries."
10)]
11
12//! Workspace-friendly file indexer and file utilities for VT Code.
13//!
14//! `vtcode-indexer` provides:
15//! - A lightweight workspace file indexer with markdown-backed persistence
16//! - Fast parallel fuzzy file search (via `file_search` module)
17//! - Markdown-backed storage utilities (via `markdown_store` module)
18
19pub mod file_search;
20pub mod markdown_store;
21
22mod atomic_write;
23mod snapshot;
24mod storage;
25
26pub use storage::{IndexStorage, MarkdownIndexStorage};
27
28use anyhow::Result;
29use hashbrown::HashMap;
30use ignore::{DirEntry, Walk};
31use rayon::prelude::*;
32use regex::Regex;
33use serde::{Deserialize, Serialize};
34use std::fmt::Write as FmtWrite;
35use std::fs;
36use std::io::ErrorKind;
37use std::path::{Path, PathBuf};
38use std::sync::Arc;
39use std::time::SystemTime;
40
41/// Directory traversal filter hook for [`SimpleIndexer`].
42pub trait TraversalFilter: Send + Sync {
43    /// Determine if the indexer should descend into the provided directory.
44    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
45
46    /// Determine if the indexer should process the provided file.
47    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
48
49    /// Metadata-aware variant of [`TraversalFilter::should_index_file`].
50    ///
51    /// The default implementation delegates to [`TraversalFilter::should_index_file`],
52    /// so existing filters keep their exact behavior. Filters whose file check
53    /// starts with an existence test should override this to reuse `metadata`
54    /// instead of stat-ing the path a second time.
55    fn should_index_file_with_metadata(
56        &self,
57        path: &Path,
58        metadata: &fs::Metadata,
59        config: &SimpleIndexerConfig,
60    ) -> bool {
61        let _ = metadata;
62        self.should_index_file(path, config)
63    }
64}
65
66/// Default traversal filter powered by [`SimpleIndexerConfig`].
67#[derive(Debug, Default, Clone)]
68pub struct ConfigTraversalFilter;
69
70impl TraversalFilter for ConfigTraversalFilter {
71    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
72        !should_skip_dir(path, config)
73    }
74
75    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
76        path.is_file() && snapshot::has_indexable_file_name(path, config)
77    }
78
79    fn should_index_file_with_metadata(
80        &self,
81        path: &Path,
82        metadata: &fs::Metadata,
83        config: &SimpleIndexerConfig,
84    ) -> bool {
85        metadata.is_file() && snapshot::has_indexable_file_name(path, config)
86    }
87}
88
89/// Configuration for [`SimpleIndexer`].
90#[derive(Clone, Debug)]
91pub struct SimpleIndexerConfig {
92    workspace_root: PathBuf,
93    index_dir: PathBuf,
94    ignore_hidden: bool,
95    excluded_dirs: Vec<PathBuf>,
96    allowed_dirs: Vec<PathBuf>,
97}
98
99impl SimpleIndexerConfig {
100    /// Builds a configuration using VT Code's legacy layout as defaults.
101    fn new(workspace_root: PathBuf) -> Self {
102        let index_dir = workspace_root.join(".vtcode").join("index");
103        let vtcode_dir = workspace_root.join(".vtcode");
104        let external_dir = vtcode_dir.join("external");
105
106        let mut excluded_dirs: Vec<PathBuf> = vtcode_commons::exclusions::DEFAULT_EXCLUDED_DIRS
107            .iter()
108            .map(|name| workspace_root.join(name))
109            .collect();
110        excluded_dirs.push(index_dir.clone());
111        excluded_dirs.push(vtcode_dir);
112
113        excluded_dirs.dedup();
114
115        Self {
116            workspace_root,
117            index_dir,
118            ignore_hidden: true,
119            excluded_dirs,
120            allowed_dirs: vec![external_dir],
121        }
122    }
123
124    /// Updates the index directory used for persisted metadata.
125    pub fn with_index_dir(mut self, index_dir: impl Into<PathBuf>) -> Self {
126        let index_dir = index_dir.into();
127        self.index_dir = index_dir.clone();
128        self.push_unique_excluded(index_dir);
129        self
130    }
131
132    /// Adds an allowed directory that should be indexed even if hidden or inside an excluded parent.
133    pub fn add_allowed_dir(mut self, path: impl Into<PathBuf>) -> Self {
134        let path = path.into();
135        if !self.allowed_dirs.iter().any(|existing| existing == &path) {
136            self.allowed_dirs.push(path);
137        }
138        self
139    }
140
141    /// Adds an additional excluded directory to skip during traversal.
142    pub fn add_excluded_dir(mut self, path: impl Into<PathBuf>) -> Self {
143        let path = path.into();
144        self.push_unique_excluded(path);
145        self
146    }
147
148    /// Toggles whether hidden directories (prefix `.`) are ignored.
149    fn ignore_hidden(mut self, ignore_hidden: bool) -> Self {
150        self.ignore_hidden = ignore_hidden;
151        self
152    }
153
154    /// Workspace root accessor.
155    pub fn workspace_root(&self) -> &Path {
156        &self.workspace_root
157    }
158
159    /// Index directory accessor.
160    fn index_dir(&self) -> &Path {
161        &self.index_dir
162    }
163
164    fn push_unique_excluded(&mut self, path: PathBuf) {
165        if !self.excluded_dirs.iter().any(|existing| existing == &path) {
166            self.excluded_dirs.push(path);
167        }
168    }
169}
170
171/// Simple file index entry.
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct FileIndex {
174    /// File path.
175    path: String,
176    /// File content hash for change detection.
177    hash: String,
178    /// Last modified timestamp.
179    modified: u64,
180    /// Subsecond part of the modification time; absent in legacy entries.
181    #[serde(default)]
182    modified_nanos: Option<u32>,
183    /// File size.
184    size: u64,
185    /// Language/extension.
186    language: String,
187    /// Simple tags.
188    tags: Vec<String>,
189}
190
191/// Simple search result.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct SearchResult {
194    file_path: String,
195    line_number: usize,
196    line_content: String,
197    matches: Vec<String>,
198}
199
200/// Simple file indexer.
201pub struct SimpleIndexer {
202    config: SimpleIndexerConfig,
203    index_cache: HashMap<String, FileIndex>,
204    content_cache: HashMap<String, (String, Arc<str>)>,
205    storage: Arc<dyn IndexStorage>,
206    filter: Arc<dyn TraversalFilter>,
207}
208
209impl SimpleIndexer {
210    /// Create a new simple indexer with default VT Code paths.
211    pub fn new(workspace_root: PathBuf) -> Self {
212        Self::with_components(
213            SimpleIndexerConfig::new(workspace_root),
214            Arc::new(MarkdownIndexStorage),
215            Arc::new(ConfigTraversalFilter),
216        )
217    }
218
219    /// Create a simple indexer with the provided configuration.
220    fn with_config(config: SimpleIndexerConfig) -> Self {
221        Self::with_components(config, Arc::new(MarkdownIndexStorage), Arc::new(ConfigTraversalFilter))
222    }
223
224    /// Create a new simple indexer using a custom index directory.
225    pub fn with_index_dir(workspace_root: PathBuf, index_dir: PathBuf) -> Self {
226        let config = SimpleIndexerConfig::new(workspace_root).with_index_dir(index_dir);
227        Self::with_config(config)
228    }
229
230    /// Create an indexer with explicit storage and traversal filter implementations.
231    fn with_components(
232        config: SimpleIndexerConfig,
233        storage: Arc<dyn IndexStorage>,
234        filter: Arc<dyn TraversalFilter>,
235    ) -> Self {
236        Self {
237            config,
238            index_cache: HashMap::new(),
239            content_cache: HashMap::new(),
240            storage,
241            filter,
242        }
243    }
244
245    /// Replace the storage backend used to persist index entries.
246    fn with_storage(self, storage: Arc<dyn IndexStorage>) -> Self {
247        Self { storage, ..self }
248    }
249
250    /// Replace the traversal filter used to decide which files and directories are indexed.
251    fn with_filter(self, filter: Arc<dyn TraversalFilter>) -> Self {
252        Self { filter, ..self }
253    }
254
255    /// Initialize the index directory.
256    pub fn init(&self) -> Result<()> {
257        self.storage.init(self.config.index_dir())
258    }
259
260    /// Populate the index cache from the persisted snapshot so re-index runs
261    /// can skip unchanged files (see [`Self::index_directory`]). Entries
262    /// outside the workspace root, in excluded directories, with hidden
263    /// or sensitive names, or with `..` segments are discarded so a tampered
264    /// snapshot can never surface files the indexer would refuse to index.
265    /// Existence is deliberately unchecked: the re-index diff needs deleted
266    /// files' entries to prune them. A missing or malformed snapshot leaves
267    /// the cache empty and never fails. Returns the hydrated count.
268    pub fn hydrate_from_snapshot(&mut self) -> usize {
269        let root = self.config.workspace_root().to_path_buf();
270        let mut hydrated = 0;
271        for entry in snapshot::load_snapshot_entries(self.config.index_dir()) {
272            let path = Path::new(&entry.path);
273            if path.starts_with(&root)
274                && !snapshot::has_parent_reference(path)
275                && (self.is_allowed_path(path) || !self.is_excluded_path(path))
276                && snapshot::has_indexable_file_name(path, &self.config)
277            {
278                self.index_cache.insert(entry.path.clone(), entry);
279                hydrated += 1;
280            }
281        }
282        tracing::debug!(hydrated, total = self.index_cache.len(), "index cache hydrated from snapshot");
283        hydrated
284    }
285
286    /// Get the workspace root path.
287    pub fn workspace_root(&self) -> &Path {
288        self.config.workspace_root()
289    }
290
291    /// Get the index directory used for persisted metadata.
292    pub fn index_dir(&self) -> &Path {
293        self.config.index_dir()
294    }
295
296    /// Index a single file.
297    fn index_file(&mut self, file_path: &Path) -> Result<()> {
298        let cache_key = file_path.to_string_lossy().into_owned();
299
300        if self.storage.prefers_snapshot_persistence() {
301            let next_entry = if file_path.exists() && self.should_process_file_path(file_path) {
302                self.build_file_index(file_path)?
303            } else {
304                None
305            };
306
307            self.apply_snapshot_file_update(cache_key, next_entry)?;
308            return Ok(());
309        }
310
311        if !file_path.exists() || !self.should_process_file_path(file_path) {
312            self.index_cache.remove(cache_key.as_str());
313            self.storage.remove(self.config.index_dir(), file_path)?;
314            return Ok(());
315        }
316
317        if let Some(index) = self.build_file_index(file_path)? {
318            self.storage.persist(self.config.index_dir(), &index)?;
319            self.index_cache.insert(index.path.clone(), index);
320        } else {
321            self.index_cache.remove(cache_key.as_str());
322            self.storage.remove(self.config.index_dir(), file_path)?;
323        }
324
325        Ok(())
326    }
327
328    /// Index all files in directory recursively.
329    /// Respects .gitignore, .ignore, and other ignore files.
330    /// SECURITY: Always skips hidden files and sensitive data (.env, .git, etc.)
331    ///
332    /// Hydrated entries matching size and mtime are served without a read or
333    /// hash (see `cached_or_built_index`); an unchanged directory also skips
334    /// the whole-snapshot rewrite.
335    pub fn index_directory(&mut self, dir_path: &Path) -> Result<()> {
336        let walker = self.build_walker(dir_path);
337
338        let mut entries = Vec::new();
339        let mut rebuilt_any = false;
340
341        for entry in walker.filter_map(|e| e.ok()) {
342            let path = entry.path();
343
344            // Only index files, not directories
345            if entry.file_type().is_some_and(|ft| ft.is_file())
346                && let Some(index) = self.cached_or_built_index(path, &mut rebuilt_any)?
347            {
348                entries.push(index);
349            }
350        }
351
352        if self.storage.prefers_snapshot_persistence() {
353            if rebuilt_any || self.cached_subdirectory_differs(dir_path, &entries) {
354                self.apply_snapshot_directory_update(dir_path, &entries)?;
355            }
356            self.prune_orphaned_content(dir_path);
357            return Ok(());
358        }
359
360        entries.sort_unstable_by(|left, right| left.path.cmp(&right.path));
361        self.storage.persist_batch(self.config.index_dir(), &entries)?;
362        self.replace_cached_entries(dir_path, &entries);
363
364        Ok(())
365    }
366
367    /// Serve a cached [`FileIndex`] when size and mtime still match the
368    /// hydrated entry, avoiding a full read + SHA-256 per unchanged file;
369    /// otherwise build. Sets `rebuilt_any` when a file is built so the caller
370    /// can skip no-op snapshot rewrites (entry-set drops are caught by the
371    /// caller's directory diff). Matching metadata is a heuristic: changes
372    /// that preserve both size and the filesystem timestamp can be missed.
373    fn cached_or_built_index(&mut self, file_path: &Path, rebuilt_any: &mut bool) -> Result<Option<FileIndex>> {
374        // Stat once and reuse the metadata for the unchanged screen, the
375        // traversal filter, and the rebuilt entry instead of stat-ing up to
376        // four times per file (filter, screen, filter, mtime).
377        let metadata = match fs::metadata(file_path) {
378            Ok(metadata) => metadata,
379            Err(_) => {
380                // Missing/unreadable: preserve `build_file_index` semantics,
381                // which maps missing files to `None` unless a custom filter
382                // claims the path (in which case the read error propagates).
383                let built = self.build_file_index(file_path)?;
384                *rebuilt_any |= built.is_some();
385                return Ok(built);
386            }
387        };
388
389        let cache_key = file_path.to_string_lossy();
390        if let Some(cached) = self.index_cache.get(cache_key.as_ref())
391            && self.should_process_file_path_with_metadata(file_path, &metadata)
392            && let Ok(modified) = metadata.modified()
393            && let Ok(elapsed) = modified.duration_since(SystemTime::UNIX_EPOCH)
394            && elapsed.as_secs() == cached.modified
395            && cached.modified_nanos == Some(elapsed.subsec_nanos())
396            && metadata.len() == cached.size
397        {
398            return Ok(Some(cached.clone()));
399        }
400
401        let built = self.build_file_index_with_metadata(file_path, &metadata)?;
402        *rebuilt_any |= built.is_some();
403        Ok(built)
404    }
405
406    /// Whether the walked entries differ from the cached entries under
407    /// `dir_path`. Deletions show up here; additions and content changes set
408    /// `rebuilt_any` in [`Self::cached_or_built_index`] instead.
409    ///
410    /// Compares by count plus membership instead of materializing two `HashSet`s.
411    /// Requires: `entries` holds at most one entry per path, as produced by the
412    /// [`Self::index_directory`] walker loop — equal counts plus every walked path
413    /// present in the cache then means the sets match.
414    /// Uniqueness precondition shared by [`Self::cached_subdirectory_differs`].
415    #[cfg(debug_assertions)]
416    fn walked_paths_are_unique(entries: &[FileIndex]) -> bool {
417        let mut seen = std::collections::HashSet::new();
418        entries.iter().all(|entry| seen.insert(entry.path.as_str()))
419    }
420
421    #[must_use]
422    fn cached_subdirectory_differs(&self, dir_path: &Path, entries: &[FileIndex]) -> bool {
423        debug_assert!(
424            Self::walked_paths_are_unique(entries),
425            "cached_subdirectory_differs requires at most one entry per path"
426        );
427        let cached_count = self
428            .index_cache
429            .keys()
430            .filter(|path| Path::new(path).starts_with(dir_path))
431            .count();
432        if cached_count != entries.len() {
433            return true;
434        }
435        entries.iter().any(|entry| !self.index_cache.contains_key(entry.path.as_str()))
436    }
437
438    /// Discover all files in directory recursively without indexing them.
439    /// This is much faster than `index_directory` as it avoids hashing and persistence.
440    pub fn discover_files(&self, dir_path: &Path) -> Vec<String> {
441        let walker = self.build_walker(dir_path);
442
443        let mut files = walker
444            .filter_map(|e| e.ok())
445            .filter(|e| {
446                if !e.file_type().is_some_and(|ft| ft.is_file()) {
447                    return false;
448                }
449
450                self.should_process_file_path(e.path())
451            })
452            .map(|e| e.path().to_string_lossy().into_owned())
453            .collect::<Vec<_>>();
454        files.sort_unstable();
455        files
456    }
457
458    /// List the immediate children of `dir_path` (one level deep) without
459    /// recursing into subdirectories.
460    ///
461    /// Uses the same ignore/hidden/excluded-directory rules as [`Self::discover_files`]
462    /// (via the shared traversal filter), so expensive subtrees such as
463    /// `node_modules`, `.git`, and build directories are never listed. This lets
464    /// callers build a directory navigator that only touches the directories the
465    /// user actually opens, instead of walking the entire workspace up front.
466    ///
467    /// Returns `(path, is_dir)` pairs with directories sorted before files.
468    pub fn discover_dir_entries(&self, dir_path: &Path) -> Vec<(PathBuf, bool)> {
469        let walker = self.build_shallow_walker(dir_path);
470
471        let mut entries: Vec<(PathBuf, bool)> = walker
472            .filter_map(|e| e.ok())
473            .filter(|e| e.path() != dir_path)
474            .map(|e| {
475                let path = e.path().to_path_buf();
476                let is_dir = e.file_type().is_some_and(|ft| ft.is_dir());
477                (path, is_dir)
478            })
479            .filter(|(path, is_dir)| {
480                if *is_dir {
481                    !should_skip_dir(path, &self.config)
482                } else {
483                    self.should_process_file_path(path)
484                }
485            })
486            .collect();
487
488        entries.sort_by_cached_key(|(path, is_dir)| {
489            // Cache the lowercased path once per entry: a plain `sort_by` would
490            // allocate two temporary strings on every one of the ~N·log N
491            // comparisons, and this runs on the interactive file-palette path.
492            (std::cmp::Reverse(*is_dir), path.to_string_lossy().to_lowercase())
493        });
494        entries
495    }
496
497    /// Internal helper for regex-based file content search.
498    /// Used by both `search()` and `grep()` to avoid code duplication.
499    fn search_files_internal(
500        &self,
501        regex: &Regex,
502        path_filter: Option<&str>,
503        extract_matches: bool,
504    ) -> Vec<SearchResult> {
505        const PARALLEL_THRESHOLD: usize = 64;
506
507        let candidate_paths: Vec<&String> = self
508            .index_cache
509            .keys()
510            .filter(|file_path| path_filter.is_none_or(|filter| file_path.contains(filter)))
511            .collect();
512
513        let mut content_lookup: HashMap<&String, Arc<str>> = HashMap::with_capacity(candidate_paths.len());
514        for path in &candidate_paths {
515            if let Some(index) = self.index_cache.get(*path)
516                && let Some((hash, content)) = self.content_cache.get(*path)
517                && hash == &index.hash
518            {
519                content_lookup.insert(*path, content.clone());
520            }
521        }
522
523        let map_file = move |file_path: &&String| -> Vec<SearchResult> {
524            if let Some(cached) = content_lookup.get(file_path) {
525                return Self::search_content(cached.as_ref(), regex, file_path, extract_matches);
526            }
527            let text = match fs::read_to_string(file_path) {
528                Ok(text) => text,
529                Err(_) => return Vec::new(),
530            };
531            Self::search_content(&text, regex, file_path, extract_matches)
532        };
533
534        let mut results: Vec<SearchResult> = if candidate_paths.len() <= PARALLEL_THRESHOLD {
535            candidate_paths.iter().flat_map(map_file).collect()
536        } else {
537            candidate_paths.par_iter().flat_map(map_file).collect()
538        };
539
540        results.sort_unstable_by(|left, right| {
541            left.file_path
542                .cmp(&right.file_path)
543                .then_with(|| left.line_number.cmp(&right.line_number))
544        });
545        results
546    }
547
548    #[inline]
549    fn search_content(content: &str, regex: &Regex, file_path: &&String, extract_matches: bool) -> Vec<SearchResult> {
550        let mut local = Vec::new();
551        for (line_num, line) in content.lines().enumerate() {
552            if regex.is_match(line) {
553                let line_content = line.to_string();
554                let matches = if extract_matches {
555                    regex.find_iter(line).map(|m| m.as_str().to_string()).collect()
556                } else {
557                    vec![line_content.clone()]
558                };
559
560                local.push(SearchResult {
561                    file_path: (*file_path).clone(),
562                    line_number: line_num + 1,
563                    line_content,
564                    matches,
565                });
566            }
567        }
568        local
569    }
570
571    /// Search files using regex pattern.
572    pub fn search(&self, pattern: &str, path_filter: Option<&str>) -> Result<Vec<SearchResult>> {
573        let regex = Regex::new(pattern)?;
574        Ok(self.search_files_internal(&regex, path_filter, true))
575    }
576
577    /// Find files by name pattern.
578    fn find_files(&self, pattern: &str) -> Result<Vec<String>> {
579        let regex = Regex::new(pattern)?;
580        let mut results = Vec::with_capacity(self.index_cache.len());
581
582        for file_path in self.index_cache.keys() {
583            if regex.is_match(file_path) {
584                results.push(file_path.clone());
585            }
586        }
587
588        results.sort_unstable();
589        Ok(results)
590    }
591
592    /// Get all indexed files without pattern matching.
593    /// This is more efficient than using find_files(".*").
594    fn all_files(&self) -> Vec<String> {
595        let mut files = self.index_cache.keys().cloned().collect::<Vec<_>>();
596        files.sort_unstable();
597        files
598    }
599
600    /// Get file content with line numbers.
601    fn get_file_content(&self, file_path: &str, start_line: Option<usize>, end_line: Option<usize>) -> Result<String> {
602        let content = fs::read_to_string(file_path)?;
603        let start = start_line.unwrap_or(1).max(1);
604        let end = end_line.unwrap_or(usize::MAX);
605
606        if start > end {
607            return Ok(String::new());
608        }
609
610        let mut result = String::with_capacity(content.len());
611        for (line_number, line) in content.lines().enumerate() {
612            let line_number = line_number + 1;
613            if line_number < start {
614                continue;
615            }
616            if line_number > end {
617                break;
618            }
619            writeln!(&mut result, "{line_number}: {line}")?;
620        }
621
622        Ok(result)
623    }
624
625    /// List files in directory (like ls).
626    pub fn list_files(&self, dir_path: &str, show_hidden: bool) -> Result<Vec<String>> {
627        let path = Path::new(dir_path);
628        if !path.exists() {
629            return Ok(vec![]);
630        }
631
632        let mut files = Vec::new();
633
634        for entry in fs::read_dir(path)? {
635            let entry = entry?;
636            let file_name = entry.file_name().to_string_lossy().into_owned();
637
638            if !show_hidden && file_name.starts_with('.') {
639                continue;
640            }
641
642            files.push(file_name);
643        }
644
645        files.sort_unstable();
646        Ok(files)
647    }
648
649    /// Grep-like search (like grep command).
650    pub fn grep(&self, pattern: &str, file_pattern: Option<&str>) -> Result<Vec<SearchResult>> {
651        let regex = Regex::new(pattern)?;
652        Ok(self.search_files_internal(&regex, file_pattern, false))
653    }
654
655    fn is_allowed_path(&self, path: &Path) -> bool {
656        self.config.allowed_dirs.iter().any(|allowed| path.starts_with(allowed))
657    }
658
659    #[inline]
660    fn get_modified_time(&self, file_path: &Path) -> Result<std::time::Duration> {
661        metadata_modified_time(&fs::metadata(file_path)?)
662    }
663
664    #[inline]
665    fn detect_language(&self, file_path: &Path) -> String {
666        file_path
667            .extension()
668            .and_then(|ext| ext.to_str())
669            .unwrap_or("unknown")
670            .to_string()
671    }
672
673    fn build_file_index(&mut self, file_path: &Path) -> Result<Option<FileIndex>> {
674        if !self.should_process_file_path(file_path) {
675            return Ok(None);
676        }
677
678        let content = match fs::read_to_string(file_path) {
679            Ok(text) => text,
680            Err(err) => {
681                if err.kind() == ErrorKind::InvalidData {
682                    return Ok(None);
683                }
684                return Err(err.into());
685            }
686        };
687
688        let modified = self.get_modified_time(file_path)?;
689        Ok(Some(self.finish_file_index(file_path, content, modified)))
690    }
691
692    /// [`Self::build_file_index`] reusing an already-observed `metadata`.
693    ///
694    /// Used by the directory-walk hot loop so each file is stat-ed once.
695    /// A file that vanishes between the stat and the read maps to `None`,
696    /// matching the legacy path's existence re-check. (A custom filter that
697    /// accepts nonexistent paths would have surfaced the read error in the
698    /// legacy path; here the transient delete is skipped instead.)
699    fn build_file_index_with_metadata(
700        &mut self,
701        file_path: &Path,
702        metadata: &fs::Metadata,
703    ) -> Result<Option<FileIndex>> {
704        if !self.should_process_file_path_with_metadata(file_path, metadata) {
705            return Ok(None);
706        }
707
708        let content = match fs::read_to_string(file_path) {
709            Ok(text) => text,
710            Err(err) => {
711                if err.kind() == ErrorKind::InvalidData || err.kind() == ErrorKind::NotFound {
712                    return Ok(None);
713                }
714                return Err(err.into());
715            }
716        };
717
718        let modified = metadata_modified_time(metadata)?;
719        Ok(Some(self.finish_file_index(file_path, content, modified)))
720    }
721
722    /// Assemble a [`FileIndex`] from already-read content and mtime, and cache
723    /// the content for hash-verified searches.
724    fn finish_file_index(&mut self, file_path: &Path, content: String, modified: std::time::Duration) -> FileIndex {
725        let index = FileIndex {
726            path: file_path.to_string_lossy().into_owned(),
727            hash: calculate_hash(&content),
728            modified: modified.as_secs(),
729            modified_nanos: Some(modified.subsec_nanos()),
730            size: content.len() as u64,
731            language: self.detect_language(file_path),
732            tags: vec![],
733        };
734
735        self.content_cache
736            .insert(index.path.clone(), (index.hash.clone(), Arc::from(content)));
737
738        index
739    }
740
741    #[inline]
742    fn is_excluded_path(&self, path: &Path) -> bool {
743        self.config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded))
744    }
745
746    #[inline]
747    fn should_index_file_path(&self, path: &Path) -> bool {
748        self.filter.should_index_file(path, &self.config)
749    }
750
751    #[inline]
752    fn should_process_file_path(&self, path: &Path) -> bool {
753        self.should_process_with(path, || self.should_index_file_path(path))
754    }
755
756    #[inline]
757    fn should_process_file_path_with_metadata(&self, path: &Path, metadata: &fs::Metadata) -> bool {
758        self.should_process_with(path, || self.filter.should_index_file_with_metadata(path, metadata, &self.config))
759    }
760
761    /// Allowed/excluded scope gate shared by both file filters.
762    ///
763    /// Allowed directories bypass exclusion; everywhere else an excluded path
764    /// short-circuits before the (potentially stat-ing) filter runs.
765    #[inline]
766    fn should_process_with(&self, path: &Path, indexable: impl FnOnce() -> bool) -> bool {
767        if self.is_allowed_path(path) {
768            return indexable();
769        }
770
771        !self.is_excluded_path(path) && indexable()
772    }
773
774    fn build_walker(&self, dir_path: &Path) -> Walk {
775        let walk_root = dir_path.to_path_buf();
776        let config = self.config.clone();
777        let filter = Arc::clone(&self.filter);
778
779        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
780        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
781        builder.build()
782    }
783
784    fn build_shallow_walker(&self, dir_path: &Path) -> Walk {
785        let walk_root = dir_path.to_path_buf();
786        let config = self.config.clone();
787        let filter = Arc::clone(&self.filter);
788
789        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
790        // Only immediate children — directory navigation lists one level at a time.
791        builder.max_depth(Some(1));
792        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
793        builder.build()
794    }
795
796    fn replace_cached_entries(&mut self, dir_path: &Path, entries: &[FileIndex]) {
797        self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
798        self.content_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
799
800        self.index_cache
801            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
802    }
803
804    /// Drop content entries under `dir_path` without an index entry (deleted,
805    /// rejected, or unindexable); content for still-indexed files is kept so
806    /// searches avoid a disk read.
807    fn prune_orphaned_content(&mut self, dir_path: &Path) {
808        self.content_cache
809            .retain(|path, _| !Path::new(path).starts_with(dir_path) || self.index_cache.contains_key(path.as_str()));
810    }
811
812    fn apply_snapshot_file_update(&mut self, cache_key: String, next_entry: Option<FileIndex>) -> Result<()> {
813        let previous_entry = match next_entry {
814            Some(entry) => self.index_cache.insert(cache_key.clone(), entry),
815            None => self.index_cache.remove(cache_key.as_str()),
816        };
817        let previous_content = self.content_cache.remove(cache_key.as_str());
818
819        if let Err(err) = self.persist_current_snapshot() {
820            match previous_entry {
821                Some(entry) => {
822                    self.index_cache.insert(cache_key.clone(), entry);
823                }
824                None => {
825                    self.index_cache.remove(cache_key.as_str());
826                }
827            }
828            if let Some(content) = previous_content {
829                self.content_cache.insert(cache_key, content);
830            }
831            return Err(err);
832        }
833
834        Ok(())
835    }
836
837    fn apply_snapshot_directory_update(&mut self, dir_path: &Path, entries: &[FileIndex]) -> Result<()> {
838        let previous_entries = self.take_cached_entries(dir_path);
839        self.index_cache
840            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
841
842        if let Err(err) = self.persist_current_snapshot() {
843            self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
844            self.index_cache
845                .extend(previous_entries.into_iter().map(|entry| (entry.path.clone(), entry)));
846            return Err(err);
847        }
848
849        Ok(())
850    }
851
852    fn take_cached_entries(&mut self, dir_path: &Path) -> Vec<FileIndex> {
853        let keys = self
854            .index_cache
855            .keys()
856            .filter(|path| Path::new(path).starts_with(dir_path))
857            .cloned()
858            .collect::<Vec<_>>();
859
860        keys.into_iter()
861            .filter_map(|path| self.index_cache.remove(path.as_str()))
862            .collect()
863    }
864
865    fn persist_current_snapshot(&self) -> Result<()> {
866        let mut snapshot = self.index_cache.values().collect::<Vec<_>>();
867        snapshot.sort_unstable_by(|left, right| left.path.cmp(&right.path));
868        self.storage.persist_batch_refs(self.config.index_dir(), &snapshot)
869    }
870}
871
872impl Clone for SimpleIndexer {
873    fn clone(&self) -> Self {
874        Self {
875            config: self.config.clone(),
876            index_cache: self.index_cache.clone(),
877            content_cache: self.content_cache.clone(),
878            storage: self.storage.clone(),
879            filter: self.filter.clone(),
880        }
881    }
882}
883
884fn should_skip_dir(path: &Path, config: &SimpleIndexerConfig) -> bool {
885    if is_allowed_path_or_ancestor(path, config) {
886        return false;
887    }
888
889    if config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded)) {
890        return true;
891    }
892
893    if config.ignore_hidden
894        && path
895            .file_name()
896            .and_then(|name| name.to_str())
897            .is_some_and(|name_str| name_str.starts_with('.'))
898    {
899        return true;
900    }
901
902    false
903}
904
905fn is_allowed_path_or_ancestor(path: &Path, config: &SimpleIndexerConfig) -> bool {
906    config
907        .allowed_dirs
908        .iter()
909        .any(|allowed| path.starts_with(allowed) || allowed.starts_with(path))
910}
911
912fn should_visit_entry(
913    entry: &DirEntry,
914    walk_root: &Path,
915    config: &SimpleIndexerConfig,
916    filter: &dyn TraversalFilter,
917) -> bool {
918    if entry.path() == walk_root {
919        return true;
920    }
921
922    if !entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
923        return true;
924    }
925
926    filter.should_descend(entry.path(), config)
927}
928
929#[inline]
930fn calculate_hash(content: &str) -> String {
931    vtcode_commons::utils::calculate_sha256(content.as_bytes())
932}
933
934/// Full mtime shared by the index builder and the unchanged
935/// screen so both observe the same clock reading for one stat.
936#[inline]
937fn metadata_modified_time(metadata: &fs::Metadata) -> Result<std::time::Duration> {
938    Ok(metadata.modified()?.duration_since(SystemTime::UNIX_EPOCH)?)
939}
940
941#[cfg(test)]
942mod tests;