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::WalkBuilder;
9use rayon::prelude::*;
10use std::collections::HashSet;
11use std::path::{Path, PathBuf};
12use std::time::Instant;
13use tracing::{debug, info, warn};
14
15/// Result of indexing a directory.
16pub struct IndexResult {
17    /// The built graph.
18    pub graph: ArborGraph,
19
20    /// Number of files processed (parsed fresh).
21    pub files_indexed: usize,
22
23    /// Number of files loaded from cache.
24    pub cache_hits: usize,
25
26    /// Number of nodes extracted.
27    pub nodes_extracted: usize,
28
29    /// Time taken in milliseconds.
30    pub duration_ms: u64,
31
32    /// Files that failed to parse.
33    pub errors: Vec<(String, String)>,
34}
35
36/// Options for directory indexing.
37#[derive(Debug, Clone, Default)]
38pub struct IndexOptions {
39    /// Follow symbolic links when walking directories.
40    pub follow_symlinks: bool,
41
42    /// Path to cache directory (e.g., `.arbor/cache`).
43    /// If None, caching is disabled.
44    pub cache_path: Option<PathBuf>,
45}
46
47/// Indexes a directory and returns the code graph.
48///
49/// This walks all source files, parses them, and builds the
50/// relationship graph. It respects .gitignore patterns.
51///
52/// If `options.cache_path` is set, files are cached with their mtimes.
53/// Only files with changed mtimes are re-parsed.
54///
55/// # Example
56///
57/// ```no_run
58/// use arbor_watcher::{index_directory, IndexOptions};
59/// use std::path::Path;
60///
61/// let result = index_directory(Path::new("./src"), IndexOptions::default()).unwrap();
62/// println!("Indexed {} files, {} nodes", result.files_indexed, result.nodes_extracted);
63/// ```
64pub fn index_directory(root: &Path, options: IndexOptions) -> Result<IndexResult, std::io::Error> {
65    let start = Instant::now();
66    let mut builder = GraphBuilder::new();
67    let mut files_indexed = 0;
68    let mut cache_hits = 0;
69    let mut nodes_extracted = 0;
70    let mut errors = Vec::new();
71
72    info!("Starting index of {}", root.display());
73
74    // Open cache if configured
75    let store =
76        options
77            .cache_path
78            .as_ref()
79            .and_then(|path| match GraphStore::open_or_reset(path) {
80                Ok(s) => Some(s),
81                Err(e) => {
82                    warn!("Failed to open cache: {}, proceeding without cache", e);
83                    None
84                }
85            });
86
87    // Walk the directory, respecting .gitignore, collecting supported files
88    let walker = WalkBuilder::new(root)
89        .hidden(true) // Skip hidden files
90        .git_ignore(true) // Respect .gitignore
91        .git_global(true)
92        .git_exclude(true)
93        .follow_links(options.follow_symlinks)
94        .build();
95
96    let candidates: Vec<PathBuf> = walker
97        .filter_map(Result::ok)
98        .filter(|entry| {
99            let path = entry.path();
100            if path.is_dir() {
101                return false;
102            }
103            match path.extension().and_then(|e| e.to_str()) {
104                Some(ext) => arbor_core::languages::is_supported(ext),
105                None => false,
106            }
107        })
108        .map(|entry| entry.into_path())
109        .collect();
110
111    // Track files we've seen (for detecting deleted files)
112    let seen_files: HashSet<String> = candidates.iter().map(|p| p.display().to_string()).collect();
113
114    // Parse files in parallel. parse_file creates its own tree-sitter parser
115    // per call and sled handles concurrent reads/writes, so both the cache
116    // check and the parse can fan out. Results collect in walk order, keeping
117    // graph construction deterministic.
118    enum Outcome {
119        CacheHit(Vec<CodeNode>),
120        Parsed(Vec<CodeNode>),
121        Failed(String),
122    }
123
124    let store_ref = store.as_ref();
125    let outcomes: Vec<(String, Outcome)> = candidates
126        .par_iter()
127        .map(|path| {
128            let path_str = path.display().to_string();
129
130            let current_mtime = match std::fs::metadata(path) {
131                Ok(meta) => meta
132                    .modified()
133                    .ok()
134                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
135                    .map(|d| d.as_secs())
136                    .unwrap_or(0),
137                Err(_) => 0,
138            };
139
140            if let Some(store) = store_ref {
141                if let Ok(Some(cached_mtime)) = store.get_mtime(&path_str) {
142                    if cached_mtime == current_mtime {
143                        // File unchanged, load from cache
144                        if let Ok(Some(cached_nodes)) = store.get_file_nodes(&path_str) {
145                            debug!("Cache hit: {}", path.display());
146                            return (path_str, Outcome::CacheHit(cached_nodes));
147                        }
148                    }
149                }
150            }
151
152            debug!("Parsing: {}", path.display());
153            match parse_file(path) {
154                Ok(nodes) => {
155                    if let Some(store) = store_ref {
156                        if let Err(e) = store.update_file(&path_str, &nodes, current_mtime) {
157                            warn!("Failed to update cache for {}: {}", path_str, e);
158                        }
159                    }
160                    (path_str, Outcome::Parsed(nodes))
161                }
162                Err(e) => {
163                    warn!("Failed to parse {}: {}", path.display(), e);
164                    (path_str, Outcome::Failed(e.to_string()))
165                }
166            }
167        })
168        .collect();
169
170    for (path_str, outcome) in outcomes {
171        match outcome {
172            Outcome::CacheHit(nodes) => {
173                nodes_extracted += nodes.len();
174                cache_hits += 1;
175                builder.add_nodes(nodes);
176            }
177            Outcome::Parsed(nodes) => {
178                nodes_extracted += nodes.len();
179                files_indexed += 1;
180                builder.add_nodes(nodes);
181            }
182            Outcome::Failed(error) => {
183                errors.push((path_str, error));
184            }
185        }
186    }
187
188    // Handle deleted files: remove from cache any files that no longer exist
189    if let Some(ref store) = store {
190        if let Ok(cached_files) = store.list_cached_files() {
191            for cached_file in cached_files {
192                if !seen_files.contains(&cached_file) {
193                    debug!("Removing deleted file from cache: {}", cached_file);
194                    if let Err(e) = store.remove_file(&cached_file) {
195                        warn!("Failed to remove {} from cache: {}", cached_file, e);
196                    }
197                }
198            }
199        }
200    }
201
202    let graph = builder.build();
203    let duration = start.elapsed();
204
205    info!(
206        "Indexed {} files, {} cache hits ({} nodes) in {:?}",
207        files_indexed, cache_hits, nodes_extracted, duration
208    );
209
210    Ok(IndexResult {
211        graph,
212        files_indexed,
213        cache_hits,
214        nodes_extracted,
215        duration_ms: duration.as_millis() as u64,
216        errors,
217    })
218}
219
220/// Parses a single file and returns its nodes.
221#[allow(dead_code)]
222pub fn parse_single_file(path: &Path) -> Result<Vec<CodeNode>, arbor_core::ParseError> {
223    parse_file(path)
224}
225
226/// Returns true if any supported source file under `root` is newer than `cache_mtime`.
227///
228/// Used by read commands to detect a stale `graph.bin` before trusting it.
229/// Walks the same gitignore-respecting tree as [`index_directory`] but only
230/// stats files — no parsing — and early-exits on the first newer file.
231///
232/// `cache_mtime` is the modified time of the cache file, in seconds since the
233/// UNIX epoch. Catches edits and additions; a lone deletion leaves no newer
234/// file, so it is picked up on the next edit instead.
235pub fn sources_newer_than(root: &Path, cache_mtime: u64, follow_symlinks: bool) -> bool {
236    let walker = WalkBuilder::new(root)
237        .hidden(true)
238        .git_ignore(true)
239        .git_global(true)
240        .git_exclude(true)
241        .follow_links(follow_symlinks)
242        .build();
243
244    for entry in walker.filter_map(Result::ok) {
245        let path = entry.path();
246        if path.is_dir() {
247            continue;
248        }
249        match path.extension().and_then(|e| e.to_str()) {
250            Some(ext) if arbor_core::languages::is_supported(ext) => {}
251            _ => continue,
252        }
253        let mtime = match std::fs::metadata(path).and_then(|m| m.modified()) {
254            Ok(t) => t
255                .duration_since(std::time::UNIX_EPOCH)
256                .map(|d| d.as_secs())
257                .unwrap_or(0),
258            Err(_) => continue,
259        };
260        if mtime > cache_mtime {
261            return true;
262        }
263    }
264    false
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use std::fs;
271    use tempfile::tempdir;
272
273    #[test]
274    fn test_index_empty_directory() {
275        let dir = tempdir().unwrap();
276        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
277        assert_eq!(result.files_indexed, 0);
278        assert_eq!(result.nodes_extracted, 0);
279    }
280
281    #[test]
282    fn test_sources_newer_than_detects_fresh_edit() {
283        let dir = tempdir().unwrap();
284        fs::write(dir.path().join("a.rs"), "pub fn a() {}").unwrap();
285
286        // Cache mtime far in the past → the source file is newer → stale.
287        assert!(sources_newer_than(dir.path(), 0, false));
288
289        // Cache mtime far in the future → nothing newer → fresh.
290        let far_future = u64::MAX;
291        assert!(!sources_newer_than(dir.path(), far_future, false));
292    }
293
294    #[test]
295    fn test_sources_newer_than_ignores_unsupported_files() {
296        let dir = tempdir().unwrap();
297        // Only an unsupported file exists; it must not mark the cache stale.
298        fs::write(dir.path().join("notes.txt"), "hello").unwrap();
299        assert!(!sources_newer_than(dir.path(), 0, false));
300    }
301
302    #[test]
303    fn test_index_with_rust_file() {
304        let dir = tempdir().unwrap();
305        let file_path = dir.path().join("test.rs");
306
307        fs::write(
308            &file_path,
309            r#"
310            pub fn hello() {
311                println!("Hello!");
312            }
313        "#,
314        )
315        .unwrap();
316
317        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
318        assert_eq!(result.files_indexed, 1);
319        assert!(result.nodes_extracted > 0);
320    }
321
322    /// Helper to create a directory symlink cross-platform.
323    /// Returns None if symlink creation fails (e.g., no privileges on Windows).
324    fn create_dir_symlink(original: &std::path::Path, link: &std::path::Path) -> Option<()> {
325        #[cfg(unix)]
326        {
327            std::os::unix::fs::symlink(original, link).ok()
328        }
329        #[cfg(windows)]
330        {
331            std::os::windows::fs::symlink_dir(original, link).ok()
332        }
333        #[cfg(not(any(unix, windows)))]
334        {
335            None
336        }
337    }
338
339    #[test]
340    fn test_index_does_not_follow_symlinks_by_default() {
341        let dir = tempdir().unwrap();
342        let linked_dir = tempdir().unwrap();
343
344        // Create a file in the linked directory
345        let linked_file = linked_dir.path().join("linked.rs");
346        fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
347
348        // Create a symlink to the linked directory
349        let symlink_path = dir.path().join("linked");
350        if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
351            // Skip test if symlinks not supported (e.g., Windows without privileges)
352            return;
353        }
354
355        // Index without following symlinks (default)
356        let result = index_directory(dir.path(), IndexOptions::default()).unwrap();
357        assert_eq!(result.files_indexed, 0);
358    }
359
360    #[test]
361    fn test_index_follows_symlinks_when_enabled() {
362        let dir = tempdir().unwrap();
363        let linked_dir = tempdir().unwrap();
364
365        // Create a file in the linked directory
366        let linked_file = linked_dir.path().join("linked.rs");
367        fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
368
369        // Create a symlink to the linked directory
370        let symlink_path = dir.path().join("linked");
371        if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
372            // Skip test if symlinks not supported (e.g., Windows without privileges)
373            return;
374        }
375
376        // Index with follow_symlinks enabled
377        let options = IndexOptions {
378            follow_symlinks: true,
379            cache_path: None,
380        };
381        let result = index_directory(dir.path(), options).unwrap();
382        assert_eq!(result.files_indexed, 1);
383        assert!(result.nodes_extracted > 0);
384    }
385}