1use 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
15pub struct IndexResult {
17 pub graph: ArborGraph,
19
20 pub files_indexed: usize,
22
23 pub cache_hits: usize,
25
26 pub nodes_extracted: usize,
28
29 pub duration_ms: u64,
31
32 pub errors: Vec<(String, String)>,
34}
35
36#[derive(Debug, Clone, Default)]
38pub struct IndexOptions {
39 pub follow_symlinks: bool,
41
42 pub cache_path: Option<PathBuf>,
45}
46
47pub 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 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 let walker = WalkBuilder::new(root)
89 .hidden(true) .git_ignore(true) .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 let seen_files: HashSet<String> = candidates.iter().map(|p| p.display().to_string()).collect();
113
114 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 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 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#[allow(dead_code)]
222pub fn parse_single_file(path: &Path) -> Result<Vec<CodeNode>, arbor_core::ParseError> {
223 parse_file(path)
224}
225
226pub 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 assert!(sources_newer_than(dir.path(), 0, false));
288
289 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 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 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 let linked_file = linked_dir.path().join("linked.rs");
346 fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
347
348 let symlink_path = dir.path().join("linked");
350 if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
351 return;
353 }
354
355 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 let linked_file = linked_dir.path().join("linked.rs");
367 fs::write(&linked_file, "pub fn linked_func() {}").unwrap();
368
369 let symlink_path = dir.path().join("linked");
371 if create_dir_symlink(linked_dir.path(), &symlink_path).is_none() {
372 return;
374 }
375
376 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}