1use anyhow::{Context, Result};
34use rusqlite::Connection;
35use std::collections::{HashMap, HashSet, VecDeque};
36use std::path::PathBuf;
37
38use crate::cache::CacheManager;
39use crate::models::{Dependency, DependencyInfo, ImportType};
40
41pub struct PathResolver {
55 exact: HashMap<String, i64>,
57 suffix: Vec<(Vec<u8>, i64)>,
60}
61
62impl PathResolver {
63 pub fn from_conn(conn: &Connection) -> Result<Self> {
65 let mut stmt = conn
66 .prepare("SELECT id, path FROM files")
67 .context("Failed to prepare files query")?;
68 let rows = stmt
69 .query_map([], |row| {
70 Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
71 })
72 .context("Failed to read files table")?
73 .collect::<std::result::Result<Vec<_>, _>>()
74 .context("Failed to read files rows")?;
75 Ok(Self::from_rows(rows))
76 }
77
78 pub fn from_rows(rows: impl IntoIterator<Item = (i64, String)>) -> Self {
80 let rows = rows.into_iter();
81 let (lower, _) = rows.size_hint();
82 let mut exact = HashMap::with_capacity(lower);
83 let mut suffix = Vec::with_capacity(lower);
84 for (id, path) in rows {
85 suffix.push((Self::suffix_key(&path), id));
86 exact.insert(path, id);
87 }
88 suffix.sort_unstable();
89 Self { exact, suffix }
90 }
91
92 pub fn len(&self) -> usize {
94 self.exact.len()
95 }
96
97 pub fn is_empty(&self) -> bool {
99 self.exact.is_empty()
100 }
101
102 fn suffix_key(path: &str) -> Vec<u8> {
103 path.bytes().rev().map(|b| b.to_ascii_lowercase()).collect()
104 }
105
106 pub fn insert(&mut self, id: i64, path: &str) {
108 if let Some(old) = self.exact.insert(path.to_string(), id) {
109 self.remove_suffix(path, old);
110 }
111 let entry = (Self::suffix_key(path), id);
112 let at = self.suffix.partition_point(|e| *e < entry);
113 self.suffix.insert(at, entry);
114 }
115
116 pub fn remove(&mut self, path: &str) {
118 if let Some(id) = self.exact.remove(path) {
119 self.remove_suffix(path, id);
120 }
121 }
122
123 fn remove_suffix(&mut self, path: &str, id: i64) {
124 let entry = (Self::suffix_key(path), id);
125 if let Ok(at) = self.suffix.binary_search(&entry) {
126 self.suffix.remove(at);
127 }
128 }
129
130 pub fn get_exact(&self, path: &str) -> Option<i64> {
132 self.exact.get(&normalize_path_for_lookup(path)).copied()
133 }
134
135 pub fn get_file_id_by_path(&self, path: &str) -> Result<Option<i64>> {
139 let normalized = normalize_path_for_lookup(path);
140 if let Some(&id) = self.exact.get(&normalized) {
141 return Ok(Some(id));
142 }
143
144 let probe = Self::suffix_key(&normalized);
147 let start = self
148 .suffix
149 .partition_point(|(key, _)| key.as_slice() < probe.as_slice());
150 let mut matches = self.suffix[start..]
151 .iter()
152 .take_while(|(key, _)| key.starts_with(&probe))
153 .filter(|(key, _)| key.len() == probe.len() || key[probe.len()] == b'/');
154 match (matches.next(), matches.next()) {
155 (None, _) => Ok(None),
156 (Some((_, id)), None) => Ok(Some(*id)),
157 (Some(_), Some(_)) => anyhow::bail!(
158 "Ambiguous path '{}' matches multiple files\n\nPlease be more specific.",
159 path
160 ),
161 }
162 }
163}
164
165pub struct DependencyWriter<'c> {
172 tx: &'c Connection,
173 deps: usize,
174 exports: usize,
175}
176
177impl<'c> DependencyWriter<'c> {
178 const INSERT_DEPENDENCY: &'static str = "INSERT INTO file_dependencies \
179 (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols, \
180 resolved_package, resolved_member) \
181 VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
182 const INSERT_EXPORT: &'static str = "INSERT INTO file_exports \
183 (file_id, exported_symbol, source_path, resolved_source_id, line_number) \
184 VALUES (?, ?, ?, ?, ?)";
185
186 pub fn new(conn: &'c Connection) -> Self {
188 Self {
189 tx: conn,
190 deps: 0,
191 exports: 0,
192 }
193 }
194
195 pub fn replace_dependencies(&mut self, file_id: i64, deps: &[Dependency]) -> Result<()> {
199 self.tx
200 .prepare_cached("DELETE FROM file_dependencies WHERE file_id = ?")?
201 .execute([file_id])?;
202 if deps.is_empty() {
203 return Ok(());
204 }
205 let mut stmt = self.tx.prepare_cached(Self::INSERT_DEPENDENCY)?;
206 for dep in deps {
207 let symbols_json = dep
208 .imported_symbols
209 .as_ref()
210 .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
211 stmt.execute(rusqlite::params![
212 dep.file_id,
213 dep.imported_path,
214 dep.resolved_file_id,
215 import_type_str(&dep.import_type),
216 dep.line_number as i64,
217 symbols_json,
218 dep.resolved_package,
219 dep.resolved_member,
220 ])?;
221 }
222 self.deps += deps.len();
223 Ok(())
224 }
225
226 pub fn replace_members(&mut self, file_id: i64, members: &[(String, String)]) -> Result<()> {
229 self.tx
230 .prepare_cached("DELETE FROM package_members WHERE file_id = ?")?
231 .execute([file_id])?;
232 let mut stmt = self.tx.prepare_cached(
233 "INSERT OR IGNORE INTO package_members (package, member, file_id) VALUES (?, ?, ?)",
234 )?;
235 for (package, member) in members {
236 stmt.execute(rusqlite::params![package, member, file_id])?;
237 }
238 Ok(())
239 }
240
241 pub fn clear_all(&mut self) -> Result<()> {
244 self.tx.execute_batch(
245 "DELETE FROM file_dependencies;
246 DELETE FROM file_exports;
247 DELETE FROM package_members;",
248 )?;
249 Ok(())
250 }
251
252 pub fn clear_exports(&mut self, file_id: i64) -> Result<()> {
254 self.tx
255 .prepare_cached("DELETE FROM file_exports WHERE file_id = ?")?
256 .execute([file_id])?;
257 Ok(())
258 }
259
260 pub fn insert_export(
262 &mut self,
263 file_id: i64,
264 exported_symbol: Option<&str>,
265 source_path: &str,
266 resolved_source_id: Option<i64>,
267 line_number: usize,
268 ) -> Result<()> {
269 self.tx
270 .prepare_cached(Self::INSERT_EXPORT)?
271 .execute(rusqlite::params![
272 file_id,
273 exported_symbol,
274 source_path,
275 resolved_source_id,
276 line_number as i64,
277 ])?;
278 self.exports += 1;
279 Ok(())
280 }
281
282 pub fn counts(&self) -> (usize, usize) {
284 (self.deps, self.exports)
285 }
286}
287
288fn import_type_str(import_type: &ImportType) -> &'static str {
289 match import_type {
290 ImportType::Internal => "internal",
291 ImportType::External => "external",
292 ImportType::Stdlib => "stdlib",
293 ImportType::ModDecl => "mod_decl",
294 }
295}
296
297pub const LOW_RESOLUTION_MIN_IMPORTS: usize = 100;
299
300pub const LOW_RESOLUTION_RATE: f64 = 0.5;
302
303#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
305pub struct LanguageResolution {
306 pub language: String,
308 pub internal: usize,
309 pub resolved: usize,
310}
311
312impl LanguageResolution {
313 pub fn rate(&self) -> f64 {
314 if self.internal == 0 {
315 1.0
316 } else {
317 self.resolved as f64 / self.internal as f64
318 }
319 }
320
321 pub fn is_low(&self) -> bool {
322 self.internal >= LOW_RESOLUTION_MIN_IMPORTS && self.rate() < LOW_RESOLUTION_RATE
323 }
324
325 pub fn warning(&self) -> String {
326 let name = match self.language.as_str() {
327 "CSharp" => "C#",
328 "Cpp" => "C++",
329 other => other,
330 };
331 format!(
332 "{name}: {} of {} internal imports ({:.1}%) resolve to indexed files; \
333 islands, unused files, hotspots, cycles and dependents for {name} files are incomplete",
334 self.resolved,
335 self.internal,
336 self.rate() * 100.0
337 )
338 }
339}
340
341pub struct DependencyIndex {
343 cache: Option<CacheManager>,
344 db_path: PathBuf,
345}
346
347impl DependencyIndex {
348 pub fn new(cache: CacheManager) -> Self {
350 let db_path = cache.path().join("meta.db");
351 Self {
352 cache: Some(cache),
353 db_path,
354 }
355 }
356
357 pub fn from_db_path(db_path: impl Into<PathBuf>) -> Self {
361 Self {
362 cache: None,
363 db_path: db_path.into(),
364 }
365 }
366
367 pub fn get_cache(&self) -> &CacheManager {
371 self.cache
372 .as_ref()
373 .expect("DependencyIndex created with from_db_path has no CacheManager")
374 }
375
376 fn open_conn(&self) -> Result<Connection> {
378 crate::cache::open_meta_db(&self.db_path).context("Failed to open database")
379 }
380
381 pub fn insert_dependency(
392 &self,
393 file_id: i64,
394 imported_path: String,
395 resolved_file_id: Option<i64>,
396 import_type: ImportType,
397 line_number: usize,
398 imported_symbols: Option<Vec<String>>,
399 ) -> Result<()> {
400 let conn = self.open_conn()?;
401
402 let import_type_str = match import_type {
403 ImportType::Internal => "internal",
404 ImportType::External => "external",
405 ImportType::Stdlib => "stdlib",
406 ImportType::ModDecl => "mod_decl",
407 };
408
409 let symbols_json = imported_symbols
410 .as_ref()
411 .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
412
413 conn.execute(
414 "INSERT INTO file_dependencies (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols)
415 VALUES (?, ?, ?, ?, ?, ?)",
416 rusqlite::params![
417 file_id,
418 imported_path,
419 resolved_file_id,
420 import_type_str,
421 line_number as i64,
422 symbols_json,
423 ],
424 )?;
425
426 Ok(())
427 }
428
429 pub fn insert_export(
439 &self,
440 file_id: i64,
441 exported_symbol: Option<String>,
442 source_path: String,
443 resolved_source_id: Option<i64>,
444 line_number: usize,
445 ) -> Result<()> {
446 let conn = self.open_conn()?;
447
448 conn.execute(
449 "INSERT INTO file_exports (file_id, exported_symbol, source_path, resolved_source_id, line_number)
450 VALUES (?, ?, ?, ?, ?)",
451 rusqlite::params![
452 file_id,
453 exported_symbol,
454 source_path,
455 resolved_source_id,
456 line_number as i64,
457 ],
458 )?;
459
460 Ok(())
461 }
462
463 pub fn batch_insert_dependencies(&self, dependencies: &[Dependency]) -> Result<()> {
467 if dependencies.is_empty() {
468 return Ok(());
469 }
470
471 let mut conn = self.open_conn()?;
472
473 let tx = conn.transaction()?;
474
475 for dep in dependencies {
476 let import_type_str = match dep.import_type {
477 ImportType::Internal => "internal",
478 ImportType::External => "external",
479 ImportType::Stdlib => "stdlib",
480 ImportType::ModDecl => "mod_decl",
481 };
482
483 let symbols_json = dep
484 .imported_symbols
485 .as_ref()
486 .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
487
488 tx.execute(
489 DependencyWriter::INSERT_DEPENDENCY,
490 rusqlite::params![
491 dep.file_id,
492 dep.imported_path,
493 dep.resolved_file_id,
494 import_type_str,
495 dep.line_number as i64,
496 symbols_json,
497 dep.resolved_package,
498 dep.resolved_member,
499 ],
500 )?;
501 }
502
503 tx.commit()?;
504 log::debug!("Batch inserted {} dependencies", dependencies.len());
505 Ok(())
506 }
507
508 pub fn get_dependencies(&self, file_id: i64) -> Result<Vec<Dependency>> {
512 let conn = self.open_conn()?;
513
514 let mut stmt = conn.prepare(
515 "SELECT file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols,
516 resolved_package, resolved_member
517 FROM file_dependencies
518 WHERE file_id = ?
519 ORDER BY line_number",
520 )?;
521
522 let deps = stmt
523 .query_map([file_id], |row| {
524 let import_type_str: String = row.get(3)?;
525 let import_type = match import_type_str.as_str() {
526 "internal" => ImportType::Internal,
527 "external" => ImportType::External,
528 "stdlib" => ImportType::Stdlib,
529 "mod_decl" => ImportType::ModDecl,
530 _ => ImportType::External,
531 };
532
533 let symbols_json: Option<String> = row.get(5)?;
534 let imported_symbols =
535 symbols_json.and_then(|json| serde_json::from_str(&json).ok());
536
537 Ok(Dependency {
538 file_id: row.get(0)?,
539 imported_path: row.get(1)?,
540 resolved_file_id: row.get(2)?,
541 resolved_package: row.get(6)?,
542 resolved_member: row.get(7)?,
543 import_type,
544 line_number: row.get::<_, i64>(4)? as usize,
545 imported_symbols,
546 })
547 })?
548 .collect::<Result<Vec<_>, _>>()?;
549
550 Ok(deps)
551 }
552
553 pub fn get_dependents(&self, file_id: i64) -> Result<Vec<i64>> {
558 let conn = self.open_conn()?;
559
560 let mut stmt = conn.prepare(
563 "SELECT f.id
564 FROM files f
565 WHERE f.id IN (SELECT src FROM import_edges WHERE dst = ?)
566 ORDER BY f.walk_seq",
567 )?;
568
569 let dependents: Vec<i64> = stmt
570 .query_map([file_id], |row| row.get(0))?
571 .collect::<Result<Vec<_>, _>>()?;
572
573 Ok(dependents)
574 }
575
576 fn direct_targets(&self, file_id: i64) -> Result<Vec<i64>> {
578 let conn = self.open_conn()?;
579 let mut stmt = conn.prepare_cached(
580 "SELECT e.dst FROM import_edges e JOIN files t ON t.id = e.dst
581 WHERE e.src = ? ORDER BY e.dep_id, t.walk_seq",
582 )?;
583 let mut seen = HashSet::new();
584 let targets = stmt
585 .query_map([file_id], |row| row.get::<_, i64>(0))?
586 .collect::<Result<Vec<_>, _>>()?;
587 Ok(targets.into_iter().filter(|id| seen.insert(*id)).collect())
588 }
589
590 fn package_targets(&self, file_id: i64) -> Result<HashMap<(usize, String), Vec<String>>> {
593 let conn = self.open_conn()?;
594 let mut stmt = conn.prepare(
595 "SELECT d.line_number, d.imported_path, t.path
596 FROM import_edges e
597 JOIN file_dependencies d ON d.id = e.dep_id
598 JOIN files t ON t.id = e.dst
599 WHERE e.src = ?
600 ORDER BY d.id, t.id != COALESCE(d.resolved_file_id, -1), t.path",
601 )?;
602 let mut out: HashMap<(usize, String), Vec<String>> = HashMap::new();
603 let rows = stmt.query_map([file_id], |row| {
604 Ok((
605 row.get::<_, i64>(0)? as usize,
606 row.get::<_, String>(1)?,
607 row.get::<_, String>(2)?,
608 ))
609 })?;
610 for row in rows {
611 let (line, imported, path) = row?;
612 out.entry((line, imported)).or_default().push(path);
613 }
614 Ok(out)
615 }
616
617 pub fn get_dependencies_info(&self, file_id: i64) -> Result<Vec<DependencyInfo>> {
622 let deps = self.get_dependencies(file_id)?;
623
624 let mut packages = self.package_targets(file_id)?;
625 let dep_infos = deps
626 .into_iter()
627 .map(|dep| {
628 let reached = packages.remove(&(dep.line_number, dep.imported_path.clone()));
631 let resolved_paths = if dep.resolved_package.is_some() {
632 Some(reached.unwrap_or_default())
633 } else {
634 reached.filter(|paths| paths.len() > 1)
635 };
636 let path = if let Some(resolved_id) = dep.resolved_file_id {
638 self.get_file_path(resolved_id).unwrap_or(dep.imported_path)
640 } else {
641 dep.imported_path
642 };
643
644 DependencyInfo {
645 path,
646 line: Some(dep.line_number),
647 symbols: dep.imported_symbols,
648 resolved_paths,
649 }
650 })
651 .collect();
652
653 Ok(dep_infos)
654 }
655
656 pub fn get_transitive_deps(
671 &self,
672 file_id: i64,
673 max_depth: usize,
674 ) -> Result<HashMap<i64, usize>> {
675 let mut visited = HashMap::new();
676 let mut queue = VecDeque::new();
677
678 queue.push_back((file_id, 0));
680 visited.insert(file_id, 0);
681
682 while let Some((current_id, depth)) = queue.pop_front() {
683 if depth >= max_depth {
684 continue;
685 }
686
687 for resolved_id in self.direct_targets(current_id)? {
688 if let std::collections::hash_map::Entry::Vacant(e) = visited.entry(resolved_id) {
690 e.insert(depth + 1);
691 queue.push_back((resolved_id, depth + 1));
692 }
693 }
694 }
695
696 Ok(visited)
697 }
698
699 pub fn detect_circular_dependencies(&self) -> Result<Vec<Vec<i64>>> {
707 let conn = self.open_conn()?;
708
709 let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();
711
712 for (file_id, target_id) in load_edges(&conn, EdgeOrder::ImporterId, false)? {
716 graph.entry(file_id).or_default().push(target_id);
717 }
718
719 let all_files = self.get_all_file_ids()?;
721
722 let mut visited = HashSet::new();
723 let mut rec_stack = HashSet::new();
724 let mut path = Vec::new();
725 let mut cycles = Vec::new();
726
727 for file_id in all_files {
728 if !visited.contains(&file_id) {
729 self.dfs_cycle_detect(
730 file_id,
731 &graph,
732 &mut visited,
733 &mut rec_stack,
734 &mut path,
735 &mut cycles,
736 )?;
737 }
738 }
739
740 Ok(cycles)
741 }
742
743 fn dfs_cycle_detect(
747 &self,
748 start: i64,
749 graph: &HashMap<i64, Vec<i64>>,
750 visited: &mut HashSet<i64>,
751 rec_stack: &mut HashSet<i64>,
752 path: &mut Vec<i64>,
753 cycles: &mut Vec<Vec<i64>>,
754 ) -> Result<()> {
755 const NONE: &[i64] = &[];
756 let mut stack: Vec<(i64, usize)> = vec![(start, 0)];
758 visited.insert(start);
759 rec_stack.insert(start);
760 path.push(start);
761
762 while let Some((node, next)) = stack.last_mut() {
763 let neighbors = graph.get(node).map_or(NONE, Vec::as_slice);
764 if let Some(&target_id) = neighbors.get(*next) {
765 *next += 1;
766 if !visited.contains(&target_id) {
767 visited.insert(target_id);
768 rec_stack.insert(target_id);
769 path.push(target_id);
770 stack.push((target_id, 0));
771 } else if rec_stack.contains(&target_id) {
772 if let Some(cycle_start) = path.iter().position(|&id| id == target_id) {
774 cycles.push(path[cycle_start..].to_vec());
775 }
776 }
777 } else {
778 let node = *node;
779 stack.pop();
780 path.pop();
781 rec_stack.remove(&node);
782 }
783 }
784
785 Ok(())
786 }
787
788 pub fn get_file_paths(&self, file_ids: &[i64]) -> Result<HashMap<i64, String>> {
792 let conn = self.open_conn()?;
793
794 let mut paths = HashMap::new();
795
796 for &file_id in file_ids {
797 if let Ok(path) =
798 conn.query_row("SELECT path FROM files WHERE id = ?", [file_id], |row| {
799 row.get::<_, String>(0)
800 })
801 {
802 paths.insert(file_id, path);
803 }
804 }
805
806 Ok(paths)
807 }
808
809 pub fn walk_ranks(&self, file_ids: &[i64]) -> Result<HashMap<i64, i64>> {
813 let conn = self.open_conn()?;
814 let wanted: HashSet<i64> = file_ids.iter().copied().collect();
815 let mut stmt = conn.prepare("SELECT id FROM files ORDER BY walk_seq")?;
816 let mut ranks = HashMap::with_capacity(wanted.len());
817 let ids = stmt.query_map([], |row| row.get::<_, i64>(0))?;
818 for (i, id) in ids.enumerate() {
819 let id = id?;
820 if wanted.contains(&id) {
821 ranks.insert(id, i as i64 + 1);
822 }
823 }
824 Ok(ranks)
825 }
826
827 fn get_file_path(&self, file_id: i64) -> Result<String> {
829 let conn = self.open_conn()?;
830
831 let path = conn.query_row("SELECT path FROM files WHERE id = ?", [file_id], |row| {
832 row.get::<_, String>(0)
833 })?;
834
835 Ok(path)
836 }
837
838 fn get_all_file_ids(&self) -> Result<Vec<i64>> {
841 let conn = self.open_conn()?;
842
843 let mut stmt = conn.prepare(&format!(
844 "SELECT id FROM files WHERE {CODE_FILES} ORDER BY path"
845 ))?;
846 let file_ids = stmt
847 .query_map([], |row| row.get(0))?
848 .collect::<Result<Vec<_>, _>>()?;
849
850 Ok(file_ids)
851 }
852
853 pub fn find_hotspots(
864 &self,
865 limit: Option<usize>,
866 min_dependents: usize,
867 ) -> Result<Vec<(i64, usize)>> {
868 let conn = self.open_conn()?;
869
870 let mut stmt = conn.prepare(
873 "SELECT e.dst, COUNT(DISTINCT e.src) as count, MIN(f.walk_seq) AS ws
874 FROM import_edges e
875 JOIN files f ON f.id = e.dst
876 GROUP BY e.dst
877 ORDER BY count DESC, ws",
878 )?;
879
880 let mut hotspots: Vec<(i64, usize)> = stmt
882 .query_map([], |row| {
883 Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)? as usize))
884 })?
885 .collect::<Result<Vec<_>, _>>()?
886 .into_iter()
887 .filter(|(_, count)| *count >= min_dependents)
888 .collect();
889
890 if let Some(lim) = limit {
892 hotspots.truncate(lim);
893 }
894
895 Ok(hotspots)
896 }
897
898 pub fn find_unused_files(&self) -> Result<Vec<i64>> {
909 let conn = self.open_conn()?;
910
911 let mut used_files = HashSet::new();
913
914 let mut stmt = conn.prepare("SELECT DISTINCT dst FROM import_edges ORDER BY dst")?;
916
917 let direct_imports: Vec<i64> = stmt
918 .query_map([], |row| row.get(0))?
919 .collect::<Result<Vec<_>, _>>()?;
920
921 used_files.extend(&direct_imports);
922
923 for file_id in direct_imports {
925 let barrel_chain = self.resolve_through_barrel_exports(file_id)?;
927 used_files.extend(barrel_chain);
928 }
929
930 let mut stmt = conn.prepare(&format!(
933 "SELECT id, path FROM files WHERE {CODE_FILES} ORDER BY walk_seq"
934 ))?;
935 let all_files: Vec<(i64, String)> = stmt
936 .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
937 .collect::<Result<Vec<_>, _>>()?;
938
939 let entry_points: HashSet<i64> = all_files
942 .iter()
943 .filter(|(_, path)| is_entry_point(path))
944 .map(|(id, _)| *id)
945 .collect();
946 for group in sibling_groups(&conn)? {
947 if group
948 .iter()
949 .any(|id| used_files.contains(id) || entry_points.contains(id))
950 {
951 used_files.extend(group);
952 }
953 }
954
955 let unused: Vec<i64> = all_files
956 .into_iter()
957 .filter(|(id, path)| !used_files.contains(id) && !is_entry_point(path))
958 .map(|(id, _)| id)
959 .collect();
960
961 Ok(unused)
962 }
963
964 pub fn resolve_through_barrel_exports(&self, barrel_file_id: i64) -> Result<Vec<i64>> {
988 let conn = self.open_conn()?;
989
990 let mut resolved_files = Vec::new();
991 let mut visited = HashSet::new();
992 let mut queue = VecDeque::new();
993
994 queue.push_back(barrel_file_id);
996 visited.insert(barrel_file_id);
997
998 while let Some(current_id) = queue.pop_front() {
999 resolved_files.push(current_id);
1000
1001 let mut stmt = conn.prepare(
1003 "SELECT resolved_source_id
1004 FROM file_exports
1005 WHERE file_id = ? AND resolved_source_id IS NOT NULL",
1006 )?;
1007
1008 let exported_files: Vec<i64> = stmt
1009 .query_map([current_id], |row| row.get(0))?
1010 .collect::<Result<Vec<_>, _>>()?;
1011
1012 for exported_id in exported_files {
1014 if !visited.contains(&exported_id) {
1015 visited.insert(exported_id);
1016 queue.push_back(exported_id);
1017 }
1018 }
1019 }
1020
1021 Ok(resolved_files)
1022 }
1023
1024 pub fn find_islands(&self) -> Result<Vec<Vec<i64>>> {
1038 let conn = self.open_conn()?;
1039
1040 let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();
1042
1043 for (file_id, target_id) in load_edges(&conn, EdgeOrder::ImporterWalk, true)? {
1047 graph.entry(file_id).or_default().push(target_id);
1049 graph.entry(target_id).or_default().push(file_id);
1050 }
1051
1052 for group in sibling_groups(&conn)? {
1054 for pair in group.windows(2) {
1055 graph.entry(pair[0]).or_default().push(pair[1]);
1056 graph.entry(pair[1]).or_default().push(pair[0]);
1057 }
1058 }
1059
1060 let all_files = self.get_all_file_ids()?;
1062
1063 for file_id in &all_files {
1065 graph.entry(*file_id).or_default();
1066 }
1067
1068 let mut visited = HashSet::new();
1070 let mut islands = Vec::new();
1071
1072 for &file_id in &all_files {
1073 if !visited.contains(&file_id) {
1074 let mut island = Vec::new();
1075 self.dfs_island(&file_id, &graph, &mut visited, &mut island);
1076 islands.push(island);
1077 }
1078 }
1079
1080 islands.sort_by_key(|a: &Vec<_>| std::cmp::Reverse(a.len()));
1082
1083 log::info!("Found {} islands (connected components)", islands.len());
1084
1085 Ok(islands)
1086 }
1087
1088 fn dfs_island(
1091 &self,
1092 start: &i64,
1093 graph: &HashMap<i64, Vec<i64>>,
1094 visited: &mut HashSet<i64>,
1095 island: &mut Vec<i64>,
1096 ) {
1097 const NONE: &[i64] = &[];
1098 visited.insert(*start);
1099 island.push(*start);
1100 let mut stack: Vec<(i64, usize)> = vec![(*start, 0)];
1101 while let Some((node, next)) = stack.last_mut() {
1102 let neighbors = graph.get(node).map_or(NONE, Vec::as_slice);
1103 match neighbors.get(*next) {
1104 Some(&neighbor) => {
1105 *next += 1;
1106 if visited.insert(neighbor) {
1107 island.push(neighbor);
1108 stack.push((neighbor, 0));
1109 }
1110 }
1111 None => {
1112 stack.pop();
1113 }
1114 }
1115 }
1116 }
1117
1118 #[allow(dead_code)]
1142 fn build_resolution_cache(&self) -> Result<HashMap<String, i64>> {
1143 let conn = self.open_conn()?;
1144
1145 let mut stmt = conn.prepare("SELECT DISTINCT imported_path FROM file_dependencies")?;
1147
1148 let imported_paths: Vec<String> = stmt
1149 .query_map([], |row| row.get(0))?
1150 .collect::<Result<Vec<_>, _>>()?;
1151
1152 let total_paths = imported_paths.len();
1153 log::info!(
1154 "Building resolution cache for {} unique imported paths",
1155 total_paths
1156 );
1157
1158 let mut cache = HashMap::new();
1160
1161 for imported_path in imported_paths {
1162 if let Ok(Some(file_id)) = self.resolve_imported_path_to_file_id(&imported_path) {
1163 cache.insert(imported_path, file_id);
1164 }
1165 }
1166
1167 log::info!(
1168 "Resolution cache built: {} resolved, {} unresolved",
1169 cache.len(),
1170 total_paths - cache.len()
1171 );
1172
1173 Ok(cache)
1174 }
1175
1176 pub fn clear_dependencies(&self, file_id: i64) -> Result<()> {
1178 let conn = self.open_conn()?;
1179
1180 conn.execute("DELETE FROM file_dependencies WHERE file_id = ?", [file_id])?;
1181
1182 Ok(())
1183 }
1184
1185 pub fn resolve_imported_path_to_file_id(&self, imported_path: &str) -> Result<Option<i64>> {
1204 let path_variants = generate_path_variants(imported_path);
1205
1206 for variant in &path_variants {
1207 if let Ok(Some(file_id)) = self.get_file_id_by_path(variant) {
1208 log::trace!(
1209 "Resolved '{}' → '{}' (file_id: {})",
1210 imported_path,
1211 variant,
1212 file_id
1213 );
1214 return Ok(Some(file_id));
1215 }
1216 }
1217
1218 Ok(None)
1219 }
1220
1221 pub fn get_file_id_by_path(&self, path: &str) -> Result<Option<i64>> {
1232 let conn = self.open_conn()?;
1233
1234 let normalized_path = normalize_path_for_lookup(path);
1236
1237 match conn.query_row(
1239 "SELECT id FROM files WHERE path = ?",
1240 [&normalized_path],
1241 |row| row.get::<_, i64>(0),
1242 ) {
1243 Ok(id) => return Ok(Some(id)),
1244 Err(rusqlite::Error::QueryReturnedNoRows) => {
1245 }
1247 Err(e) => return Err(e.into()),
1248 }
1249
1250 let mut stmt = conn.prepare(
1253 "SELECT id, path FROM files
1254 WHERE lower(path) = lower(?1)
1255 OR lower(substr(path, -(length(?1) + 1))) = lower('/' || ?1)",
1256 )?;
1257
1258 let matches: Vec<(i64, String)> = stmt
1259 .query_map([&normalized_path], |row| Ok((row.get(0)?, row.get(1)?)))?
1260 .collect::<Result<Vec<_>, _>>()?;
1261
1262 match matches.len() {
1263 0 => Ok(None),
1264 1 => Ok(Some(matches[0].0)),
1265 _ => {
1266 let paths: Vec<String> = matches.iter().map(|(_, p)| p.clone()).collect();
1268 anyhow::bail!(
1269 "Ambiguous path '{}' matches multiple files:\n {}\n\nPlease be more specific.",
1270 path,
1271 paths.join("\n ")
1272 );
1273 }
1274 }
1275 }
1276
1277 pub fn internal_resolution_by_language(&self) -> Result<Vec<LanguageResolution>> {
1283 let conn = self.open_conn()?;
1284 let mut stmt = conn.prepare(
1285 "SELECT f.language, COUNT(*),
1286 SUM(d.resolved_file_id IS NOT NULL
1287 OR EXISTS (SELECT 1 FROM package_members m
1288 WHERE m.package = d.resolved_package
1289 AND m.member = COALESCE(d.resolved_member, '')
1290 AND m.file_id != d.file_id))
1291 FROM file_dependencies d
1292 JOIN files f ON d.file_id = f.id
1293 WHERE d.import_type = 'internal'
1294 -- vendored code's own imports are not the project's graph
1295 AND f.vendored = 0
1296 -- C# calls every non-System using internal: leave out the NuGet ones,
1297 -- whose root namespace (`Newtonsoft` of `Newtonsoft.Json`) no file declares
1298 AND NOT (COALESCE(d.resolved_package, '') LIKE 'cs:%' AND NOT EXISTS (
1299 SELECT 1 FROM package_members m,
1300 (SELECT 'cs:' || CASE WHEN instr(substr(d.resolved_package, 4), '.') > 0
1301 THEN substr(d.resolved_package, 4, instr(substr(d.resolved_package, 4), '.') - 1)
1302 ELSE substr(d.resolved_package, 4) END AS root)
1303 WHERE m.package = root
1304 OR (m.package > root || '.' AND m.package < root || '/')))
1305 GROUP BY f.language
1306 ORDER BY f.language",
1307 )?;
1308 let rows = stmt.query_map([], |row| {
1309 Ok(LanguageResolution {
1310 language: row.get(0)?,
1311 internal: row.get::<_, i64>(1)? as usize,
1312 resolved: row.get::<_, i64>(2)? as usize,
1313 })
1314 })?;
1315 Ok(rows.collect::<Result<Vec<_>, _>>()?)
1316 }
1317
1318 pub fn vendored_file_count(&self) -> Result<usize> {
1322 let conn = self.open_conn()?;
1323 let n: i64 = conn.query_row(
1324 "SELECT COUNT(*) FROM files
1325 WHERE vendored = 1 AND language NOT IN ('Text', 'Lock', 'Generated', 'Unknown')",
1326 [],
1327 |r| r.get(0),
1328 )?;
1329 Ok(n as usize)
1330 }
1331
1332 pub fn graph_warnings_for(&self, path: &str) -> Result<Vec<String>> {
1335 let Some(id) = self.get_file_id_by_path(path).ok().flatten() else {
1336 return Ok(Vec::new());
1337 };
1338 let conn = self.open_conn()?;
1339 let vendored: bool =
1340 conn.query_row("SELECT vendored FROM files WHERE id = ?", [id], |r| {
1341 r.get(0)
1342 })?;
1343 if vendored {
1344 return Ok(vec![format!(
1345 "{path} is vendored; vendored files are not in the import graph"
1346 )]);
1347 }
1348 Ok(self.low_resolution_warning_for(path)?.into_iter().collect())
1349 }
1350
1351 pub fn low_resolution_warning_for(&self, path: &str) -> Result<Option<String>> {
1352 let Some(id) = self.get_file_id_by_path(path).ok().flatten() else {
1353 return Ok(None);
1354 };
1355 let conn = self.open_conn()?;
1356 let language: Option<String> = conn
1357 .query_row("SELECT language FROM files WHERE id = ?", [id], |row| {
1358 row.get(0)
1359 })
1360 .ok();
1361 Ok(language.and_then(|language| {
1362 self.internal_resolution_by_language()
1363 .ok()?
1364 .into_iter()
1365 .find(|l| l.language == language && l.is_low())
1366 .map(|l| l.warning())
1367 }))
1368 }
1369
1370 pub fn low_resolution_warnings(&self) -> Result<Vec<String>> {
1375 Ok(self
1376 .internal_resolution_by_language()?
1377 .iter()
1378 .filter(|l| l.is_low())
1379 .map(LanguageResolution::warning)
1380 .collect())
1381 }
1382
1383 pub fn get_all_internal_dependencies(&self) -> Result<Vec<(String, String, Option<String>)>> {
1393 let conn = self.open_conn()?;
1394
1395 let mut stmt = conn.prepare(
1396 "SELECT
1397 f.path,
1398 d.imported_path,
1399 f2.path as resolved_path
1400 FROM file_dependencies d
1401 JOIN files f ON d.file_id = f.id
1402 LEFT JOIN files f2 ON d.resolved_file_id = f2.id
1403 WHERE d.import_type = 'internal'
1404 ORDER BY f.path",
1405 )?;
1406
1407 let mut deps = Vec::new();
1408
1409 let rows = stmt.query_map([], |row| {
1410 Ok((
1411 row.get::<_, String>(0)?,
1412 row.get::<_, String>(1)?,
1413 row.get::<_, Option<String>>(2)?,
1414 ))
1415 })?;
1416
1417 for row in rows {
1418 deps.push(row?);
1419 }
1420
1421 Ok(deps)
1422 }
1423
1424 pub fn get_dependency_count_by_type(&self) -> Result<Vec<(String, usize)>> {
1426 let conn = self.open_conn()?;
1427
1428 let mut stmt = conn.prepare(
1429 "SELECT import_type, COUNT(*) as count
1430 FROM file_dependencies
1431 GROUP BY import_type
1432 ORDER BY import_type",
1433 )?;
1434
1435 let mut counts = Vec::new();
1436
1437 let rows = stmt.query_map([], |row| {
1438 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize))
1439 })?;
1440
1441 for row in rows {
1442 counts.push(row?);
1443 }
1444
1445 Ok(counts)
1446 }
1447}
1448
1449#[derive(Clone, Copy)]
1452enum EdgeOrder {
1453 ImporterId,
1455 ImporterWalk,
1457}
1458
1459fn load_edges(conn: &Connection, order: EdgeOrder, every_edge: bool) -> Result<Vec<(i64, i64)>> {
1464 let order_by = match order {
1465 EdgeOrder::ImporterId => "e.src, e.dep_id, t.walk_seq",
1466 EdgeOrder::ImporterWalk => "s.walk_seq, e.dep_id, t.walk_seq",
1467 };
1468 let filter = if every_edge {
1469 ""
1470 } else {
1471 "WHERE e.import_type != 'mod_decl' AND (e.package IS NULL OR e.package NOT LIKE 'cs:%')"
1475 };
1476 let mut stmt = conn.prepare(&format!(
1477 "SELECT e.src, e.dst FROM import_edges e
1478 JOIN files s ON s.id = e.src
1479 JOIN files t ON t.id = e.dst
1480 {filter}
1481 ORDER BY {order_by}"
1482 ))?;
1483 let mut seen = HashSet::new();
1484 let edges = stmt
1485 .query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))?
1486 .collect::<Result<Vec<_>, _>>()?;
1487 Ok(edges.into_iter().filter(|e| seen.insert(*e)).collect())
1488}
1489
1490fn sibling_groups(conn: &Connection) -> Result<Vec<Vec<i64>>> {
1495 let mut stmt = conn.prepare(
1496 "SELECT m.package, m.file_id FROM package_members m
1497 JOIN files f ON f.id = m.file_id
1498 WHERE m.package LIKE 'go:%' AND f.vendored = 0
1499 ORDER BY m.package, f.walk_seq",
1500 )?;
1501 let mut groups: Vec<Vec<i64>> = Vec::new();
1502 let mut current: Option<String> = None;
1503 let rows = stmt.query_map([], |row| {
1504 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
1505 })?;
1506 for row in rows {
1507 let (package, id) = row?;
1508 if current.as_deref() != Some(package.as_str()) {
1509 groups.push(Vec::new());
1510 current = Some(package);
1511 }
1512 groups.last_mut().expect("pushed above").push(id);
1513 }
1514 Ok(groups)
1515}
1516
1517const CODE_FILES: &str =
1521 "language NOT IN ('Text', 'Lock', 'Generated', 'Unknown') AND vendored = 0";
1522
1523fn is_entry_point(path: &str) -> bool {
1528 let p = path.replace('\\', "/");
1529 let p = p.as_str();
1530
1531 if matches!(
1533 p,
1534 "src/lib.rs" | "src/main.rs" | "build.rs" | "lib.rs" | "main.rs"
1535 ) {
1536 return true;
1537 }
1538
1539 let (dirs, filename) = match p.rsplit_once('/') {
1542 Some((dirs, name)) => (dirs, name),
1543 None => ("", p),
1544 };
1545 if dirs.split('/').any(|d| {
1546 matches!(
1547 d,
1548 "tests" | "test" | "benches" | "examples" | "testdata" | "__tests__"
1549 ) || d.ends_with(".Tests")
1550 || d.ends_with(".UnitTests")
1551 }) {
1552 return true;
1553 }
1554
1555 if matches!(
1557 filename,
1558 "main.go" | "Program.cs" | "__main__.py" | "manage.py" | "conftest.py" | "setup.py"
1559 ) {
1560 return true;
1561 }
1562
1563 let stem = filename.rsplit_once('.').map_or(filename, |(stem, _)| stem);
1565 filename.starts_with("test_")
1566 || filename.ends_with("_test.rs")
1567 || filename.ends_with("_spec.rs")
1568 || filename.ends_with("_test.go")
1569 || filename.ends_with("_test.py")
1570 || ((filename.ends_with(".java") || filename.ends_with(".kt") || filename.ends_with(".cs"))
1571 && (stem.ends_with("Test")
1572 || stem.ends_with("Tests")
1573 || stem
1575 .strip_suffix("IT")
1576 .and_then(|s| s.chars().last())
1577 .is_some_and(char::is_lowercase)))
1578}
1579
1580fn generate_path_variants(import_path: &str) -> Vec<String> {
1592 let path = import_path.replace('\\', "/").replace("::", "/");
1594
1595 let path = path.trim_matches('"').trim_matches('\'');
1597
1598 let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1600
1601 if components.is_empty() {
1602 return vec![];
1603 }
1604
1605 let mut variants = Vec::new();
1606
1607 for start_idx in 0..components.len() {
1614 let suffix = components[start_idx..].join("/");
1615
1616 if !suffix.ends_with(".php") {
1618 variants.push(format!("{}.php", suffix));
1619 } else {
1620 variants.push(suffix.clone());
1621 }
1622
1623 if !suffix.contains('.') {
1625 variants.push(format!("{}.rs", suffix));
1627 variants.push(format!("{}.ts", suffix));
1628 variants.push(format!("{}.js", suffix));
1629 variants.push(format!("{}.py", suffix));
1630 }
1631 }
1632
1633 variants
1634}
1635
1636fn normalize_path_for_lookup(path: &str) -> String {
1647 let mut normalized = path.trim_start_matches("./").to_string();
1649 if normalized.starts_with("../") {
1650 normalized = normalized.trim_start_matches("../").to_string();
1651 }
1652
1653 if normalized.starts_with('/') || normalized.starts_with('\\') {
1657 let markers = ["services", "src", "app", "lib", "packages", "modules"];
1659
1660 let mut found_marker = false;
1661 for marker in &markers {
1662 if let Some(idx) = normalized.find(marker) {
1663 normalized = normalized[idx..].to_string();
1664 found_marker = true;
1665 break;
1666 }
1667 }
1668
1669 if !found_marker {
1671 use std::path::Path;
1672 let path_obj = Path::new(&normalized);
1673 if let Some(filename) = path_obj.file_name() {
1674 normalized = filename.to_string_lossy().to_string();
1675 }
1676 }
1677 }
1678
1679 normalized
1680}
1681
1682pub fn resolve_rust_import(
1701 import_path: &str,
1702 current_file: &str,
1703 project_root: &std::path::Path,
1704) -> Option<String> {
1705 use std::path::{Path, PathBuf};
1706
1707 if !import_path.starts_with("crate::")
1709 && !import_path.starts_with("super::")
1710 && !import_path.starts_with("self::")
1711 {
1712 return None;
1713 }
1714
1715 let current_path = Path::new(current_file);
1716 let mut resolved_path: Option<PathBuf> = None;
1717
1718 if import_path.starts_with("crate::") {
1719 let crate_root = if project_root.join("src/lib.rs").exists()
1721 || project_root.join("src/main.rs").exists()
1722 {
1723 project_root.join("src")
1724 } else {
1725 project_root.join("src")
1727 };
1728
1729 let path_parts: Vec<&str> = import_path
1730 .strip_prefix("crate::")
1731 .unwrap()
1732 .split("::")
1733 .collect();
1734
1735 resolved_path = resolve_module_path(&crate_root, &path_parts);
1736 } else if import_path.starts_with("super::") {
1737 if let Some(current_dir) = current_path.parent()
1739 && let Some(parent_dir) = current_dir.parent()
1740 {
1741 let path_parts: Vec<&str> = import_path
1742 .strip_prefix("super::")
1743 .unwrap()
1744 .split("::")
1745 .collect();
1746
1747 resolved_path = resolve_module_path(parent_dir, &path_parts);
1748 }
1749 } else if import_path.starts_with("self::") {
1750 if let Some(current_dir) = current_path.parent() {
1752 let path_parts: Vec<&str> = import_path
1753 .strip_prefix("self::")
1754 .unwrap()
1755 .split("::")
1756 .collect();
1757
1758 resolved_path = resolve_module_path(current_dir, &path_parts);
1759 }
1760 }
1761
1762 resolved_path.and_then(|p| {
1765 p.strip_prefix(project_root)
1766 .ok()
1767 .map(|rel| rel.to_string_lossy().replace('\\', "/"))
1768 })
1769}
1770
1771fn resolve_module_path(
1777 start_dir: &std::path::Path,
1778 components: &[&str],
1779) -> Option<std::path::PathBuf> {
1780 if components.is_empty() {
1781 return None;
1782 }
1783
1784 let mut current = start_dir.to_path_buf();
1785
1786 for &component in &components[..components.len() - 1] {
1788 let dir_path = current.join(component);
1790 let mod_file = dir_path.join("mod.rs");
1791
1792 if mod_file.exists() {
1793 current = dir_path;
1794 } else {
1795 return None;
1797 }
1798 }
1799
1800 let last_component = components.last().unwrap();
1802
1803 let file_path = current.join(format!("{}.rs", last_component));
1805 if file_path.exists() {
1806 return Some(file_path);
1807 }
1808
1809 let dir_path = current.join(last_component);
1811 let mod_file = dir_path.join("mod.rs");
1812 if mod_file.exists() {
1813 return Some(mod_file);
1814 }
1815
1816 None
1817}
1818
1819pub fn resolve_rust_mod_declaration(
1825 mod_name: &str,
1826 current_file: &str,
1827 _project_root: &std::path::Path,
1828) -> Option<String> {
1829 use std::path::Path;
1830
1831 let current_path = Path::new(current_file);
1832 let current_dir = current_path.parent()?;
1833
1834 let sibling = current_dir.join(format!("{}.rs", mod_name));
1836 if sibling.exists() {
1837 return Some(sibling.to_string_lossy().replace('\\', "/"));
1838 }
1839
1840 let dir_mod = current_dir.join(mod_name).join("mod.rs");
1842 if dir_mod.exists() {
1843 return Some(dir_mod.to_string_lossy().replace('\\', "/"));
1844 }
1845
1846 None
1847}
1848
1849pub fn resolve_php_import(
1872 import_path: &str,
1873 _current_file: &str,
1874 project_root: &std::path::Path,
1875) -> Option<String> {
1876 const VENDOR_NAMESPACES: &[&str] = &[
1878 "Illuminate\\",
1879 "Symfony\\",
1880 "Laravel\\",
1881 "Psr\\",
1882 "Doctrine\\",
1883 "Monolog\\",
1884 "PHPUnit\\",
1885 "Carbon\\",
1886 "GuzzleHttp\\",
1887 "Composer\\",
1888 "Predis\\",
1889 "League\\",
1890 ];
1891
1892 for vendor_ns in VENDOR_NAMESPACES {
1894 if import_path.starts_with(vendor_ns) {
1895 return None;
1896 }
1897 }
1898
1899 let file_path = import_path.replace('\\', "/");
1903
1904 let path_candidates = vec![
1908 {
1910 let parts: Vec<&str> = file_path.split('/').collect();
1911 if let Some(first) = parts.first() {
1912 let mut result = vec![first.to_lowercase()];
1913 result.extend(parts[1..].iter().map(|s| s.to_string()));
1914 result.join("/") + ".php"
1915 } else {
1916 file_path.clone() + ".php"
1917 }
1918 },
1919 file_path.clone() + ".php",
1921 file_path.to_lowercase() + ".php",
1923 ];
1924
1925 for candidate in &path_candidates {
1927 let full_path = project_root.join(candidate);
1928 if full_path.exists() {
1929 return Some(candidate.clone());
1931 }
1932 }
1933
1934 None
1936}
1937
1938#[cfg(test)]
1939mod tests {
1940 use super::*;
1941 use tempfile::TempDir;
1942
1943 fn setup_test_cache() -> (TempDir, CacheManager) {
1944 let temp = TempDir::new().unwrap();
1945 let cache = CacheManager::new(temp.path());
1946 cache.init().unwrap();
1947
1948 cache.update_file("src/main.rs", "rust", 100).unwrap();
1950 cache.update_file("src/lib.rs", "rust", 50).unwrap();
1951 cache.update_file("src/utils.rs", "rust", 30).unwrap();
1952
1953 (temp, cache)
1954 }
1955
1956 #[test]
1959 fn package_import_links_every_member() {
1960 let temp = TempDir::new().unwrap();
1961 let cache = CacheManager::new(temp.path());
1962 cache.init().unwrap();
1963 cache.update_file("cmd/a.go", "Go", 10).unwrap();
1964 cache.update_file("pkg/b/b1.go", "Go", 10).unwrap();
1965 cache.update_file("pkg/b/b2.go", "Go", 10).unwrap();
1966 let index = DependencyIndex::new(cache);
1967 let id = |p: &str| index.get_file_id_by_path(p).unwrap().unwrap();
1968 let (a, b1, b2) = (id("cmd/a.go"), id("pkg/b/b1.go"), id("pkg/b/b2.go"));
1969 {
1970 let conn = index.open_conn().unwrap();
1971 let mut writer = DependencyWriter::new(&conn);
1972 for b in [b1, b2] {
1973 writer
1974 .replace_members(b, &[("go:pkg/b".to_string(), String::new())])
1975 .unwrap();
1976 }
1977 writer
1978 .replace_dependencies(
1979 a,
1980 &[Dependency {
1981 file_id: a,
1982 imported_path: "example.com/m/pkg/b".to_string(),
1983 resolved_file_id: None,
1984 resolved_package: Some("go:pkg/b".to_string()),
1985 resolved_member: None,
1986 import_type: ImportType::Internal,
1987 line_number: 3,
1988 imported_symbols: None,
1989 }],
1990 )
1991 .unwrap();
1992 }
1993
1994 assert_eq!(index.get_dependents(b2).unwrap(), vec![a]);
1995 let mut reached: Vec<i64> = index
1996 .get_transitive_deps(a, 1)
1997 .unwrap()
1998 .into_keys()
1999 .collect();
2000 reached.sort();
2001 assert_eq!(reached, vec![a, b1, b2]);
2002 assert_eq!(index.find_islands().unwrap(), vec![vec![a, b1, b2]]);
2003 assert_eq!(
2004 index.find_hotspots(None, 1).unwrap(),
2005 vec![(b1, 1), (b2, 1)]
2006 );
2007 assert!(!index.find_unused_files().unwrap().contains(&b2));
2008 assert_eq!(
2009 index.internal_resolution_by_language().unwrap(),
2010 vec![LanguageResolution {
2011 language: "Go".to_string(),
2012 internal: 1,
2013 resolved: 1,
2014 }]
2015 );
2016 let info = index.get_dependencies_info(a).unwrap();
2017 assert_eq!(info.len(), 1, "one entry per import: {info:?}");
2018 assert_eq!(
2019 info[0].resolved_paths,
2020 Some(vec!["pkg/b/b1.go".to_string(), "pkg/b/b2.go".to_string()])
2021 );
2022 }
2023
2024 #[test]
2025 fn entry_points_cover_each_language() {
2026 for p in [
2027 "src/main.rs",
2028 "tests/a.rs",
2029 "staging/src/k8s.io/api/test/x.go",
2030 "cmd/kubelet/main.go",
2031 "pkg/a/a_test.go",
2032 "pkg/a/testdata/x.go",
2033 "module/src/test/java/org/x/FooTest.java",
2034 "module/src/main/java/org/x/FooIT.java",
2035 "app/src/main/kotlin/FooTests.kt",
2036 "src/App/Program.cs",
2037 "src/Foo.Tests/Bar.cs",
2038 "django/__main__.py",
2039 "manage.py",
2040 "pkg/conftest.py",
2041 "pkg/test_views.py",
2042 "pkg/views_test.py",
2043 ] {
2044 assert!(is_entry_point(p), "{p}");
2045 }
2046 for p in [
2047 "src/util.rs",
2048 "pkg/a/a.go",
2049 "pkg/latest/x.go",
2050 "src/main/java/org/x/EXIT.java",
2051 "src/main/java/org/x/Audit.java",
2052 "src/App/Contest.cs",
2053 "django/db/models.py",
2054 ] {
2055 assert!(!is_entry_point(p), "{p}");
2056 }
2057 }
2058
2059 #[test]
2060 fn test_insert_and_get_dependencies() {
2061 let (_temp, cache) = setup_test_cache();
2062 let deps_index = DependencyIndex::new(cache);
2063
2064 let main_id = 1i64;
2066 let lib_id = 2i64;
2067
2068 deps_index
2070 .insert_dependency(
2071 main_id,
2072 "crate::lib".to_string(),
2073 Some(lib_id),
2074 ImportType::Internal,
2075 5,
2076 None,
2077 )
2078 .unwrap();
2079
2080 let deps = deps_index.get_dependencies(main_id).unwrap();
2082 assert_eq!(deps.len(), 1);
2083 assert_eq!(deps[0].imported_path, "crate::lib");
2084 assert_eq!(deps[0].resolved_file_id, Some(lib_id));
2085 assert_eq!(deps[0].import_type, ImportType::Internal);
2086 }
2087
2088 #[test]
2089 fn test_reverse_lookup() {
2090 let (_temp, cache) = setup_test_cache();
2091 let deps_index = DependencyIndex::new(cache);
2092
2093 let main_id = 1i64;
2094 let lib_id = 2i64;
2095 let utils_id = 3i64;
2096
2097 deps_index
2099 .insert_dependency(
2100 main_id,
2101 "crate::lib".to_string(),
2102 Some(lib_id),
2103 ImportType::Internal,
2104 5,
2105 None,
2106 )
2107 .unwrap();
2108
2109 deps_index
2111 .insert_dependency(
2112 utils_id,
2113 "crate::lib".to_string(),
2114 Some(lib_id),
2115 ImportType::Internal,
2116 3,
2117 None,
2118 )
2119 .unwrap();
2120
2121 let dependents = deps_index.get_dependents(lib_id).unwrap();
2123 assert_eq!(dependents.len(), 2);
2124 assert!(dependents.contains(&main_id));
2125 assert!(dependents.contains(&utils_id));
2126 }
2127
2128 #[test]
2129 fn test_transitive_dependencies() {
2130 let (_temp, cache) = setup_test_cache();
2131 let deps_index = DependencyIndex::new(cache);
2132
2133 let file1 = 1i64;
2134 let file2 = 2i64;
2135 let file3 = 3i64;
2136
2137 deps_index
2139 .insert_dependency(
2140 file1,
2141 "file2".to_string(),
2142 Some(file2),
2143 ImportType::Internal,
2144 1,
2145 None,
2146 )
2147 .unwrap();
2148
2149 deps_index
2150 .insert_dependency(
2151 file2,
2152 "file3".to_string(),
2153 Some(file3),
2154 ImportType::Internal,
2155 1,
2156 None,
2157 )
2158 .unwrap();
2159
2160 let transitive = deps_index.get_transitive_deps(file1, 2).unwrap();
2162
2163 assert_eq!(transitive.len(), 3);
2165 assert_eq!(transitive.get(&file1), Some(&0));
2166 assert_eq!(transitive.get(&file2), Some(&1));
2167 assert_eq!(transitive.get(&file3), Some(&2));
2168 }
2169
2170 #[test]
2171 fn test_batch_insert() {
2172 let (_temp, cache) = setup_test_cache();
2173 let deps_index = DependencyIndex::new(cache);
2174
2175 let deps = vec![
2176 Dependency {
2177 file_id: 1,
2178 imported_path: "std::collections".to_string(),
2179 resolved_file_id: None,
2180 resolved_package: None,
2181 resolved_member: None,
2182 import_type: ImportType::Stdlib,
2183 line_number: 1,
2184 imported_symbols: Some(vec!["HashMap".to_string()]),
2185 },
2186 Dependency {
2187 file_id: 1,
2188 imported_path: "crate::lib".to_string(),
2189 resolved_file_id: Some(2),
2190 resolved_package: None,
2191 resolved_member: None,
2192 import_type: ImportType::Internal,
2193 line_number: 2,
2194 imported_symbols: None,
2195 },
2196 ];
2197
2198 deps_index.batch_insert_dependencies(&deps).unwrap();
2199
2200 let retrieved = deps_index.get_dependencies(1).unwrap();
2201 assert_eq!(retrieved.len(), 2);
2202 }
2203
2204 #[test]
2205 fn test_clear_dependencies() {
2206 let (_temp, cache) = setup_test_cache();
2207 let deps_index = DependencyIndex::new(cache);
2208
2209 deps_index
2211 .insert_dependency(
2212 1,
2213 "crate::lib".to_string(),
2214 Some(2),
2215 ImportType::Internal,
2216 1,
2217 None,
2218 )
2219 .unwrap();
2220
2221 assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 1);
2223
2224 deps_index.clear_dependencies(1).unwrap();
2226
2227 assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 0);
2229 }
2230
2231 #[test]
2232 fn test_resolve_rust_import_crate() {
2233 use std::fs;
2234 use tempfile::TempDir;
2235
2236 let temp = TempDir::new().unwrap();
2237 let project_root = temp.path();
2238
2239 fs::create_dir_all(project_root.join("src")).unwrap();
2241 fs::write(project_root.join("src/lib.rs"), "").unwrap();
2242 fs::write(project_root.join("src/models.rs"), "").unwrap();
2243
2244 let resolved = resolve_rust_import("crate::models", "src/query.rs", project_root);
2246
2247 assert_eq!(resolved, Some("src/models.rs".to_string()));
2248 }
2249
2250 #[test]
2251 fn test_resolve_rust_import_super() {
2252 use std::fs;
2253 use tempfile::TempDir;
2254
2255 let temp = TempDir::new().unwrap();
2256 let project_root = temp.path();
2257
2258 fs::create_dir_all(project_root.join("src/parsers")).unwrap();
2260 fs::write(project_root.join("src/models.rs"), "").unwrap();
2261 fs::write(project_root.join("src/parsers/rust.rs"), "").unwrap();
2262
2263 let current_file = project_root.join("src/parsers/rust.rs");
2266 let resolved = resolve_rust_import(
2267 "super::models",
2268 ¤t_file.to_string_lossy(),
2269 project_root,
2270 );
2271
2272 assert_eq!(resolved, Some("src/models.rs".to_string()));
2273 }
2274
2275 #[test]
2276 fn test_resolve_rust_import_external() {
2277 use tempfile::TempDir;
2278
2279 let temp = TempDir::new().unwrap();
2280 let project_root = temp.path();
2281
2282 let resolved = resolve_rust_import("serde::Serialize", "src/models.rs", project_root);
2284
2285 assert_eq!(resolved, None);
2286
2287 let resolved =
2289 resolve_rust_import("std::collections::HashMap", "src/models.rs", project_root);
2290
2291 assert_eq!(resolved, None);
2292 }
2293
2294 #[test]
2295 fn test_resolve_rust_mod_declaration() {
2296 use std::fs;
2297 use tempfile::TempDir;
2298
2299 let temp = TempDir::new().unwrap();
2300 let project_root = temp.path();
2301
2302 fs::create_dir_all(project_root.join("src")).unwrap();
2304 fs::write(project_root.join("src/lib.rs"), "").unwrap();
2305 fs::write(project_root.join("src/parser.rs"), "").unwrap();
2306
2307 let resolved = resolve_rust_mod_declaration(
2309 "parser",
2310 &project_root.join("src/lib.rs").to_string_lossy(),
2311 project_root,
2312 );
2313
2314 assert!(resolved.is_some());
2315 assert!(resolved.unwrap().ends_with("src/parser.rs"));
2316 }
2317
2318 #[test]
2319 fn test_resolve_rust_import_nested() {
2320 use std::fs;
2321 use tempfile::TempDir;
2322
2323 let temp = TempDir::new().unwrap();
2324 let project_root = temp.path();
2325
2326 fs::create_dir_all(project_root.join("src/models")).unwrap();
2328 fs::write(project_root.join("src/models/mod.rs"), "").unwrap();
2329 fs::write(project_root.join("src/models/language.rs"), "").unwrap();
2330
2331 let resolved = resolve_rust_import("crate::models::language", "src/query.rs", project_root);
2333
2334 assert_eq!(resolved, Some("src/models/language.rs".to_string()));
2335 }
2336}