Skip to main content

arbor_watcher/
indexer.rs

1//! Directory indexing.
2//!
3//! Walks directories to find and parse source files, building
4//! the initial code graph.
5
6use arbor_core::{parse_file, CodeNode};
7use arbor_graph::{ArborGraph, GraphBuilder, GraphStore};
8use ignore::gitignore::{Gitignore, GitignoreBuilder};
9use ignore::WalkBuilder;
10use rayon::prelude::*;
11use serde::Deserialize;
12use std::collections::HashSet;
13use std::path::{Path, PathBuf};
14use std::time::Instant;
15use tracing::{debug, info, warn};
16
17/// Result of indexing a directory.
18pub struct IndexResult {
19    /// The built graph.
20    pub graph: ArborGraph,
21
22    /// Number of files processed (parsed fresh).
23    pub files_indexed: usize,
24
25    /// Number of files loaded from cache.
26    pub cache_hits: usize,
27
28    /// Number of nodes extracted.
29    pub nodes_extracted: usize,
30
31    /// Time taken in milliseconds.
32    pub duration_ms: u64,
33
34    /// Files that failed to parse.
35    pub errors: Vec<(String, String)>,
36}
37
38/// Options for directory indexing.
39#[derive(Debug, Clone, Default)]
40pub struct IndexOptions {
41    /// Follow symbolic links when walking directories.
42    pub follow_symlinks: bool,
43
44    /// Path to cache directory (e.g., `.arbor/cache`).
45    /// If None, caching is disabled.
46    pub cache_path: Option<PathBuf>,
47}
48
49const DEFAULT_EXCLUDE_PATTERNS: &[&str] = &[
50    ".git/",
51    ".arbor/",
52    "node_modules/",
53    "venv/",
54    ".venv/",
55    "site-packages/",
56    "__pycache__/",
57    "target/",
58    "dist/",
59    "build/",
60    "out/",
61    // Bundled third-party trees and minified assets. `vendor/` matches that
62    // directory at any depth, including Android `assets/**/vendor`.
63    "vendor/",
64    "*.min.js",
65    "*.min.css",
66];
67
68#[derive(Debug, Deserialize)]
69struct ArborConfig {
70    #[serde(default)]
71    ignore: Vec<String>,
72}
73
74/// Shared ignore matcher used by both the directory walker and the file watcher.
75///
76/// Combines Arbor's built-in excludes (`.git/`, `target/`, `node_modules/`, ...),
77/// the root `.gitignore` and `.arborignore` files, and any custom patterns from
78/// `.arbor/config.json`.
79pub struct IgnoreMatcher {
80    inner: Option<Gitignore>,
81}
82
83impl IgnoreMatcher {
84    /// Build a matcher rooted at `root`.
85    pub fn new(root: &Path) -> Self {
86        let mut builder = GitignoreBuilder::new(root);
87
88        for pattern in DEFAULT_EXCLUDE_PATTERNS {
89            if let Err(e) = builder.add_line(None, pattern) {
90                warn!("Invalid built-in ignore pattern '{}': {}", pattern, e);
91            }
92        }
93
94        // Root-level ignore files. (Nested `.gitignore` files are honored by
95        // `WalkBuilder` during the initial walk; this matcher is enough for the
96        // watcher and for root-level rules in the indexer.)
97        for ignore_file in [".gitignore", ".arborignore"] {
98            let path = root.join(ignore_file);
99            if path.exists() {
100                if let Some(e) = builder.add(&path) {
101                    warn!("Failed to add {}: {}", path.display(), e);
102                }
103            }
104        }
105
106        // Custom ignore patterns from `.arbor/config.json`
107        let config_path = root.join(".arbor").join("config.json");
108        if config_path.exists() {
109            match std::fs::read_to_string(&config_path) {
110                Ok(text) => match serde_json::from_str::<ArborConfig>(&text) {
111                    Ok(config) => {
112                        for pattern in config.ignore {
113                            let trimmed = pattern.trim();
114                            if trimmed.is_empty() {
115                                continue;
116                            }
117                            if let Err(e) = builder.add_line(None, trimmed) {
118                                warn!(
119                                    "Invalid ignore pattern '{}' in {}: {}",
120                                    trimmed,
121                                    config_path.display(),
122                                    e
123                                );
124                            }
125                        }
126                    }
127                    Err(e) => warn!("Failed to parse {}: {}", config_path.display(), e),
128                },
129                Err(e) => warn!("Failed to read {}: {}", config_path.display(), e),
130            }
131        }
132
133        match builder.build() {
134            Ok(matcher) => Self {
135                inner: Some(matcher),
136            },
137            Err(e) => {
138                warn!("Failed to build ignore matcher: {}", e);
139                Self { inner: None }
140            }
141        }
142    }
143
144    /// Returns `true` if `path` should be ignored.
145    pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
146        self.inner
147            .as_ref()
148            .map(|m| m.matched_path_or_any_parents(path, is_dir).is_ignore())
149            .unwrap_or(false)
150    }
151}
152
153/// Indexes a directory and returns the code graph.
154///
155/// This walks all source files, parses them, and builds the
156/// relationship graph. It respects .gitignore patterns.
157///
158/// If `options.cache_path` is set, files are cached with their mtimes.
159/// Only files with changed mtimes are re-parsed.
160///
161/// # Example
162///
163/// ```no_run
164/// use arbor_watcher::{index_directory, IndexOptions};
165/// use std::path::Path;
166///
167/// let result = index_directory(Path::new("./src"), IndexOptions::default()).unwrap();
168/// println!("Indexed {} files, {} nodes", result.files_indexed, result.nodes_extracted);
169/// ```
170pub fn index_directory(root: &Path, options: IndexOptions) -> Result<IndexResult, std::io::Error> {
171    let start = Instant::now();
172    let mut builder = GraphBuilder::new();
173    let mut files_indexed = 0;
174    let mut cache_hits = 0;
175    let mut nodes_extracted = 0;
176    let mut errors = Vec::new();
177
178    info!("Starting index of {}", root.display());
179
180    // Open cache if configured
181    let store =
182        options
183            .cache_path
184            .as_ref()
185            .and_then(|path| match GraphStore::open_or_reset(path) {
186                Ok(s) => Some(s),
187                Err(e) => {
188                    warn!("Failed to open cache: {}, proceeding without cache", e);
189                    None
190                }
191            });
192
193    // Walk the directory, respecting ignore files and collecting supported files.
194    let ignore_matcher = IgnoreMatcher::new(root);
195    let walker = WalkBuilder::new(root)
196        .hidden(true) // Skip hidden files
197        .git_ignore(true) // Respect .gitignore
198        .ignore(true) // Respect .ignore and custom ignore files
199        .require_git(false) // Respect .gitignore even outside a git repository
200        .git_global(true)
201        .git_exclude(true)
202        .add_custom_ignore_filename(".arborignore")
203        .follow_links(options.follow_symlinks)
204        .build();
205
206    let candidates: Vec<PathBuf> = walker
207        .filter_map(Result::ok)
208        .filter(|entry| {
209            let path = entry.path();
210            if ignore_matcher.is_ignored(
211                path,
212                entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false),
213            ) {
214                return false;
215            }
216            if path.is_dir() {
217                return false;
218            }
219            match path.extension().and_then(|e| e.to_str()) {
220                Some(ext) => arbor_core::languages::is_supported(ext),
221                None => false,
222            }
223        })
224        .map(|entry| entry.into_path())
225        .collect();
226
227    // Track files we've seen (for detecting deleted files)
228    let seen_files: HashSet<String> = candidates.iter().map(|p| p.display().to_string()).collect();
229
230    // Parse files in parallel. parse_file creates its own tree-sitter parser
231    // per call and sled handles concurrent reads/writes, so both the cache
232    // check and the parse can fan out. Results collect in walk order, keeping
233    // graph construction deterministic.
234    enum Outcome {
235        CacheHit(Vec<CodeNode>),
236        Parsed(Vec<CodeNode>),
237        Failed(String),
238    }
239
240    let store_ref = store.as_ref();
241    let outcomes: Vec<(String, Outcome)> = candidates
242        .par_iter()
243        .map(|path| {
244            let path_str = path.display().to_string();
245
246            let current_mtime = mtime_nanos(path).unwrap_or(0);
247
248            if let Some(store) = store_ref {
249                if let Ok(Some(cached_mtime)) = store.get_mtime(&path_str) {
250                    if cached_mtime == current_mtime {
251                        // File unchanged, load from cache
252                        if let Ok(Some(cached_nodes)) = store.get_file_nodes(&path_str) {
253                            debug!("Cache hit: {}", path.display());
254                            return (path_str, Outcome::CacheHit(cached_nodes));
255                        }
256                    }
257                }
258            }
259
260            debug!("Parsing: {}", path.display());
261            match parse_file(path) {
262                Ok(nodes) => {
263                    if let Some(store) = store_ref {
264                        if let Err(e) = store.update_file(&path_str, &nodes, current_mtime) {
265                            warn!("Failed to update cache for {}: {}", path_str, e);
266                        }
267                    }
268                    (path_str, Outcome::Parsed(nodes))
269                }
270                Err(e) => {
271                    warn!("Failed to parse {}: {}", path.display(), e);
272                    (path_str, Outcome::Failed(e.to_string()))
273                }
274            }
275        })
276        .collect();
277
278    for (path_str, outcome) in outcomes {
279        match outcome {
280            Outcome::CacheHit(nodes) => {
281                nodes_extracted += nodes.len();
282                cache_hits += 1;
283                builder.add_nodes(nodes);
284            }
285            Outcome::Parsed(nodes) => {
286                nodes_extracted += nodes.len();
287                files_indexed += 1;
288                builder.add_nodes(nodes);
289            }
290            Outcome::Failed(error) => {
291                errors.push((path_str, error));
292            }
293        }
294    }
295
296    // Handle deleted files: remove from cache any files that no longer exist
297    if let Some(ref store) = store {
298        if let Ok(cached_files) = store.list_cached_files() {
299            for cached_file in cached_files {
300                if !seen_files.contains(&cached_file) {
301                    debug!("Removing deleted file from cache: {}", cached_file);
302                    if let Err(e) = store.remove_file(&cached_file) {
303                        warn!("Failed to remove {} from cache: {}", cached_file, e);
304                    }
305                }
306            }
307        }
308    }
309
310    let graph = builder.build();
311    let duration = start.elapsed();
312
313    info!(
314        "Indexed {} files, {} cache hits ({} nodes) in {:?}",
315        files_indexed, cache_hits, nodes_extracted, duration
316    );
317
318    Ok(IndexResult {
319        graph,
320        files_indexed,
321        cache_hits,
322        nodes_extracted,
323        duration_ms: duration.as_millis() as u64,
324        errors,
325    })
326}
327
328/// Parses a single file and returns its nodes.
329#[allow(dead_code)]
330pub fn parse_single_file(path: &Path) -> Result<Vec<CodeNode>, arbor_core::ParseError> {
331    parse_file(path)
332}
333
334/// Returns true if any supported source file under `root` is newer than `cache_mtime`.
335///
336/// Used by read commands to detect a stale `graph.bin` before trusting it.
337/// Walks the same gitignore-respecting tree as [`index_directory`] but only
338/// stats files — no parsing — and early-exits on the first newer file.
339///
340/// `cache_mtime` is the modified time of the cache file, in seconds since the
341/// UNIX epoch. Catches edits and additions; a lone deletion leaves no newer
342/// file, so it is picked up on the next edit instead.
343/// A file's modification time in nanoseconds since the Unix epoch.
344///
345/// Whole seconds were not enough: an edit in the same second as the last
346/// index (easy for a coding agent) looked unchanged to both the per-file
347/// cache and the staleness check, so the graph silently missed it. Caches
348/// written with second precision simply miss once and are rebuilt.
349pub fn mtime_nanos(path: &Path) -> Option<u64> {
350    let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
351    let since_epoch = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
352    u64::try_from(since_epoch.as_nanos()).ok()
353}
354
355/// True when any supported source file under `root` was modified after
356/// `cache_mtime` (nanoseconds since the Unix epoch, see [`mtime_nanos`]).
357pub fn sources_newer_than(root: &Path, cache_mtime: u64, follow_symlinks: bool) -> bool {
358    let ignore_matcher = IgnoreMatcher::new(root);
359    let walker = WalkBuilder::new(root)
360        .hidden(true)
361        .git_ignore(true)
362        .ignore(true)
363        .require_git(false)
364        .git_global(true)
365        .git_exclude(true)
366        .add_custom_ignore_filename(".arborignore")
367        .follow_links(follow_symlinks)
368        .build();
369
370    for entry in walker.filter_map(Result::ok) {
371        let path = entry.path();
372        if ignore_matcher.is_ignored(
373            path,
374            entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false),
375        ) {
376            continue;
377        }
378        if path.is_dir() {
379            continue;
380        }
381        match path.extension().and_then(|e| e.to_str()) {
382            Some(ext) if arbor_core::languages::is_supported(ext) => {}
383            _ => continue,
384        }
385        let Some(mtime) = mtime_nanos(path) else {
386            continue;
387        };
388        if mtime > cache_mtime {
389            return true;
390        }
391    }
392    false
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use std::fs;
399    use tempfile::tempdir;
400
401    #[test]
402    fn test_index_empty_directory() {
403        let dir = tempdir().unwrap();
404        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
405        assert_eq!(result.files_indexed, 0);
406        assert_eq!(result.nodes_extracted, 0);
407    }
408
409    #[test]
410    fn test_sources_newer_than_detects_fresh_edit() {
411        let dir = tempdir().unwrap();
412        fs::write(dir.path().join("a.rs"), "pub fn a() {}").unwrap();
413
414        // Cache mtime far in the past → the source file is newer → stale.
415        assert!(sources_newer_than(dir.path(), 0, false));
416
417        // Cache mtime far in the future → nothing newer → fresh.
418        let far_future = u64::MAX;
419        assert!(!sources_newer_than(dir.path(), far_future, false));
420    }
421
422    #[test]
423    fn an_edit_within_the_same_second_is_still_newer() {
424        let dir = tempdir().unwrap();
425        let file = dir.path().join("a.rs");
426        fs::write(&file, "pub fn a() {}").unwrap();
427        let before = mtime_nanos(&file).unwrap();
428        // Well under a second later: whole-second precision would call this equal.
429        std::thread::sleep(std::time::Duration::from_millis(20));
430        fs::write(&file, "pub fn a() { let _ = 1; }").unwrap();
431        let after = mtime_nanos(&file).unwrap();
432        assert!(after > before, "{after} should be newer than {before}");
433        assert!(sources_newer_than(dir.path(), before, false));
434    }
435
436    #[test]
437    fn test_sources_newer_than_ignores_unsupported_files() {
438        let dir = tempdir().unwrap();
439        // Only an unsupported file exists; it must not mark the cache stale.
440        fs::write(dir.path().join("notes.txt"), "hello").unwrap();
441        assert!(!sources_newer_than(dir.path(), 0, false));
442    }
443
444    #[test]
445    fn test_index_with_rust_file() {
446        let dir = tempdir().unwrap();
447        let file_path = dir.path().join("test.rs");
448
449        fs::write(
450            &file_path,
451            r#"
452            pub fn hello() {
453                println!("Hello!");
454            }
455        "#,
456        )
457        .unwrap();
458
459        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
460        assert_eq!(result.files_indexed, 1);
461        assert!(result.nodes_extracted > 0);
462    }
463
464    /// Helper to create a directory symlink cross-platform.
465    /// Returns None if symlink creation fails (e.g., no privileges on Windows).
466    fn create_dir_symlink(original: &std::path::Path, link: &std::path::Path) -> Option<()> {
467        #[cfg(unix)]
468        {
469            std::os::unix::fs::symlink(original, link).ok()
470        }
471        #[cfg(windows)]
472        {
473            std::os::windows::fs::symlink_dir(original, link).ok()
474        }
475        #[cfg(not(any(unix, windows)))]
476        {
477            None
478        }
479    }
480
481    #[test]
482    fn test_index_does_not_follow_symlinks_by_default() {
483        let dir = tempdir().unwrap();
484        let linked_dir = tempdir().unwrap();
485
486        // Create a file in the linked directory
487        let linked_file = linked_dir.path().join("linked.rs");
488        fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
489
490        // Create a symlink to the linked directory
491        let symlink_path = dir.path().join("linked");
492        if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
493            // Skip test if symlinks not supported (e.g., Windows without privileges)
494            return;
495        }
496
497        // Index without following symlinks (default)
498        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
499        assert_eq!(result.files_indexed, 0);
500    }
501
502    #[test]
503    fn test_index_follows_symlinks_when_enabled() {
504        let dir = tempdir().unwrap();
505        let linked_dir = tempdir().unwrap();
506
507        // Create a file in the linked directory
508        let linked_file = linked_dir.path().join("linked.rs");
509        fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
510
511        // Create a symlink to the linked directory
512        let symlink_path = dir.path().join("linked");
513        if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
514            // Skip test if symlinks not supported (e.g., Windows without privileges)
515            return;
516        }
517
518        // Index with follow_symlinks enabled
519        let options = IndexOptions {
520            follow_symlinks: true,
521            cache_path: None,
522        };
523        let result = index_directory(dir.path(), options).unwrap();
524        assert_eq!(result.files_indexed, 1);
525        assert!(result.nodes_extracted > 0);
526    }
527
528    #[test]
529    fn test_index_honors_gitignore_outside_git_repo() {
530        let dir = tempdir().unwrap();
531        fs::create_dir_all(dir.path().join("venv")).unwrap();
532        fs::write(dir.path().join(".gitignore"), "venv/\n").unwrap();
533        fs::write(
534            dir.path().join("venv").join("ignored.rs"),
535            "pub fn ignored() {}",
536        )
537        .unwrap();
538        fs::write(dir.path().join("kept.rs"), "pub fn kept() {}").unwrap();
539
540        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
541        assert_eq!(result.files_indexed, 1);
542        assert!(result.graph.find_by_name("kept").len() == 1);
543        assert!(result.graph.find_by_name("ignored").is_empty());
544    }
545
546    #[test]
547    fn test_index_honors_arborignore() {
548        let dir = tempdir().unwrap();
549        fs::create_dir_all(dir.path().join("vendor")).unwrap();
550        fs::write(dir.path().join(".arborignore"), "vendor/\n").unwrap();
551        fs::write(
552            dir.path().join("vendor").join("ignored.rs"),
553            "pub fn ignored() {}",
554        )
555        .unwrap();
556        fs::write(dir.path().join("kept.rs"), "pub fn kept() {}").unwrap();
557
558        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
559        assert_eq!(result.files_indexed, 1);
560        assert!(result.graph.find_by_name("kept").len() == 1);
561        assert!(result.graph.find_by_name("ignored").is_empty());
562    }
563
564    #[test]
565    fn test_index_ignores_vendor_and_minified_assets_by_default() {
566        let dir = tempdir().unwrap();
567        let vendor_path = dir
568            .path()
569            .join("android")
570            .join("app")
571            .join("src")
572            .join("main")
573            .join("assets")
574            .join("instrument")
575            .join("vendor");
576        fs::create_dir_all(&vendor_path).unwrap();
577        fs::write(vendor_path.join("maplibre-gl.js"), "function el() {}").unwrap();
578        fs::write(dir.path().join("app.min.js"), "function boot() {}").unwrap();
579        fs::write(dir.path().join("kept.rs"), "pub fn kept() {}").unwrap();
580
581        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
582        assert_eq!(result.files_indexed, 1);
583        assert!(result.graph.find_by_name("kept").len() == 1);
584        assert!(result.graph.find_by_name("el").is_empty());
585        assert!(result.graph.find_by_name("boot").is_empty());
586    }
587
588    #[test]
589    fn test_index_honors_arbor_config_ignore_patterns() {
590        let dir = tempdir().unwrap();
591        fs::create_dir_all(dir.path().join(".arbor")).unwrap();
592        fs::create_dir_all(dir.path().join("third_party")).unwrap();
593        fs::write(
594            dir.path().join(".arbor").join("config.json"),
595            r#"{"version":"1.0","ignore":["third_party/"]}"#,
596        )
597        .unwrap();
598        fs::write(
599            dir.path().join("third_party").join("ignored.rs"),
600            "pub fn ignored() {}",
601        )
602        .unwrap();
603        fs::write(dir.path().join("kept.rs"), "pub fn kept() {}").unwrap();
604
605        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
606        assert_eq!(result.files_indexed, 1);
607        assert!(result.graph.find_by_name("kept").len() == 1);
608        assert!(result.graph.find_by_name("ignored").is_empty());
609    }
610}