1use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18
19use crate::dependency::PathResolver;
20use crate::models::{Dependency, ImportType};
21use crate::parsers::go::GoModule;
22use crate::parsers::java::JavaProject;
23use crate::parsers::php::Psr4Mapping;
24use crate::parsers::python::PythonPackage;
25use crate::parsers::ruby::RubyProject;
26use crate::parsers::rust::RustCrate;
27use crate::parsers::tsconfig::PathAliasMap;
28use crate::parsers::{ExportInfo, ImportInfo};
29
30pub fn find_nearest_tsconfig<'a>(
35 file_path: &str,
36 root: &Path,
37 tsconfigs: &'a HashMap<PathBuf, PathAliasMap>,
38) -> Option<&'a PathAliasMap> {
39 let abs_file_path = if Path::new(file_path).is_absolute() {
41 PathBuf::from(file_path)
42 } else {
43 root.join(file_path)
44 };
45
46 let mut current_dir = abs_file_path.parent()?;
48
49 loop {
50 if let Some(alias_map) = tsconfigs.get(current_dir) {
52 return Some(alias_map);
53 }
54
55 current_dir = current_dir.parent()?;
57
58 if current_dir == root || !current_dir.starts_with(root) {
60 break;
61 }
62 }
63
64 None
65}
66
67pub const CONFIG_LIST: &str = "resolver-configs.json";
70
71pub fn is_resolver_config_name(name: &str) -> bool {
73 matches!(
74 name,
75 "go.mod"
76 | "pom.xml"
77 | "build.gradle"
78 | "build.gradle.kts"
79 | "pyproject.toml"
80 | "setup.py"
81 | "setup.cfg"
82 | "composer.json"
83 | "tsconfig.json"
84 | "Cargo.toml"
85 | "modules.txt"
87 | "installed.json"
88 | "pyvenv.cfg"
89 | ".cargo-checksum.json"
90 | "build.zig.zon"
91 | "build.zig"
92 ) || name.ends_with(".gemspec")
93}
94
95pub fn fold_path(dir: &str, rel: &str) -> Option<String> {
103 let rel = rel.replace('\\', "/");
104 let dir = dir.replace('\\', "/");
105 let (absolute, joined) = if rel.starts_with('/') {
106 (true, rel)
107 } else {
108 (dir.starts_with('/'), format!("{dir}/{rel}"))
109 };
110 let mut parts: Vec<&str> = Vec::new();
111 for seg in joined.split('/') {
112 match seg {
113 "" | "." => {}
114 ".." => {
115 parts.pop()?;
116 }
117 s => parts.push(s),
118 }
119 }
120 if parts.is_empty() {
121 return None;
122 }
123 let body = parts.join("/");
124 Some(if absolute { format!("/{body}") } else { body })
125}
126
127pub fn parent_dir(file: &str) -> &str {
129 file.rsplit_once('/').map_or("", |(dir, _)| dir)
130}
131
132fn rel_slash(root: &Path, path: &Path) -> String {
134 path.strip_prefix(root)
135 .unwrap_or(path)
136 .to_string_lossy()
137 .replace('\\', "/")
138}
139
140#[derive(Debug, Default, serde::Serialize, serde::Deserialize, PartialEq)]
142struct ConfigList {
143 go_mods: Vec<String>,
144 java: Vec<String>,
145 python: Vec<String>,
146 gemspecs: Vec<String>,
147 cargo_tomls: Vec<String>,
148 composer: Vec<String>,
149 tsconfigs: Vec<String>,
150 #[serde(default)]
151 vendor_markers: Vec<String>,
152 #[serde(default)]
153 zig_zons: Vec<String>,
154 #[serde(default)]
155 zig_builds: Vec<String>,
156 walk_error: Option<String>,
157}
158
159#[derive(Debug, Default, Clone)]
161struct ConfigFiles {
162 go_mods: Vec<PathBuf>,
163 java: Vec<PathBuf>,
164 python: Vec<PathBuf>,
165 gemspecs: Vec<PathBuf>,
166 cargo_tomls: Vec<PathBuf>,
167 composer: Vec<PathBuf>,
168 tsconfigs: Vec<PathBuf>,
169 vendor_markers: Vec<PathBuf>,
171 zig_zons: Vec<PathBuf>,
173 zig_builds: Vec<PathBuf>,
175 walk_error: Option<String>,
178}
179
180impl ConfigFiles {
181 fn walk(root: &Path) -> Self {
185 let mut out = Self::default();
186 let walker = ignore::WalkBuilder::new(root)
187 .follow_links(false)
188 .git_ignore(true)
189 .build();
190 for entry in walker {
191 let entry = match entry {
192 Ok(entry) => entry,
193 Err(e) => {
194 if out.walk_error.is_none() {
195 out.walk_error = Some(e.to_string());
196 }
197 continue;
198 }
199 };
200 let path = entry.path();
201 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
202 let is_gemspec = path.extension().and_then(|s| s.to_str()) == Some("gemspec");
203 match filename {
204 "go.mod" | "pom.xml" | "build.gradle" | "build.gradle.kts" | "pyproject.toml"
205 | "setup.py" | "setup.cfg" | "composer.json" | "tsconfig.json" | "Cargo.toml" => {}
206 _ if is_gemspec => {}
207 "modules.txt" | "installed.json" | "pyvenv.cfg" => {
208 let rel = rel_slash(root, path);
209 if crate::vendor::marker_root(&rel).is_some() {
210 out.vendor_markers.push(path.to_path_buf());
211 }
212 continue;
213 }
214 "build.zig.zon" => {
215 out.zig_zons.push(path.to_path_buf());
216 continue;
217 }
218 "build.zig" => {
219 out.zig_builds.push(path.to_path_buf());
220 continue;
221 }
222 _ => continue,
223 }
224
225 if filename == "Cargo.toml" {
227 out.cargo_tomls.push(path.to_path_buf());
228 let checksum = path.with_file_name(".cargo-checksum.json");
230 if checksum.is_file() {
231 out.vendor_markers.push(checksum);
232 }
233 }
234 if filename == "tsconfig.json" {
235 out.tsconfigs.push(path.to_path_buf());
236 }
237 if !path.is_file() {
238 continue;
239 }
240 let path_str = path.to_string_lossy().replace('\\', "/");
242 match filename {
243 "go.mod" => {
244 if !path_str.contains("/vendor/") {
245 out.go_mods.push(path.to_path_buf());
246 }
247 }
248 "pom.xml" | "build.gradle" | "build.gradle.kts" => {
249 out.java.push(path.to_path_buf())
250 }
251 "pyproject.toml" | "setup.py" | "setup.cfg" => {
252 let skipped = path_str.contains("/venv/")
253 || path_str.contains("/.venv/")
254 || path_str.contains("/site-packages/")
255 || path_str.contains("/dist/")
256 || path_str.contains("/build/")
257 || path_str.contains("/__pycache__/");
258 if !skipped {
259 out.python.push(path.to_path_buf());
260 }
261 }
262 "composer.json" if !path.components().any(|c| c.as_os_str() == "vendor") => {
263 out.composer.push(path.to_path_buf());
264 }
265 _ => {}
266 }
267 if is_gemspec {
268 out.gemspecs.push(path.to_path_buf());
269 }
270 }
271 out.drop_vendored_configs(root);
272 out
273 }
274
275 fn vendor_roots(&self, root: &Path) -> Vec<String> {
278 let mut roots: Vec<String> = self
279 .vendor_markers
280 .iter()
281 .filter_map(|p| crate::vendor::marker_root(&rel_slash(root, p)))
282 .collect();
283 for zon in &self.zig_zons {
284 if let Ok(source) = std::fs::read_to_string(zon) {
285 roots.extend(crate::vendor::zig_path_dependencies(
286 &rel_slash(root, zon),
287 &source,
288 ));
289 }
290 }
291 roots
292 }
293
294 fn drop_vendored_configs(&mut self, root: &Path) {
297 let rules = crate::vendor::VendorRules::new(root, self.vendor_roots(root), &[]);
298 let keep = |p: &PathBuf| !rules.in_vendored_dir(&rel_slash(root, p));
299 for list in [
300 &mut self.go_mods,
301 &mut self.java,
302 &mut self.python,
303 &mut self.gemspecs,
304 &mut self.cargo_tomls,
305 &mut self.composer,
306 &mut self.tsconfigs,
307 &mut self.zig_builds,
308 ] {
309 list.retain(keep);
310 }
311 let dirs: Vec<String> = self
313 .vendor_markers
314 .iter()
315 .filter_map(|p| crate::vendor::marker_root(&rel_slash(root, p)))
316 .collect();
317 self.zig_zons.retain(|p| {
318 let rel = rel_slash(root, p);
319 !dirs.iter().any(|d| rel.starts_with(d.as_str())) && !rules.in_vendored_dir(&rel)
320 });
321 }
322
323 fn digest(&self, root: &Path) -> String {
327 let mut h = blake3::Hasher::new();
328 let mut file = |tag: &str, path: &Path| {
329 h.update(tag.as_bytes());
331 h.update(rel_slash(root, path).as_bytes());
332 h.update(b"\0");
333 match std::fs::read(path) {
334 Ok(bytes) => {
335 h.update(blake3::hash(&bytes).as_bytes());
336 }
337 Err(_) => {
338 h.update(b"<absent>");
339 }
340 }
341 };
342 let kinds: [(&str, &Vec<PathBuf>); 7] = [
343 ("go", &self.go_mods),
344 ("java", &self.java),
345 ("python", &self.python),
346 ("gem", &self.gemspecs),
347 ("cargo", &self.cargo_tomls),
348 ("composer", &self.composer),
349 ("tsconfig", &self.tsconfigs),
350 ];
351 for (tag, paths) in kinds {
352 for path in paths {
353 file(tag, path);
354 }
355 }
356 for path in &self.zig_zons {
357 file("zig", path);
358 }
359 for path in &self.zig_builds {
360 file("zig-build", path);
361 }
362 for path in &self.python {
364 if let Some(dir) = path.parent() {
365 for name in ["pyproject.toml", "setup.py", "setup.cfg"] {
366 file("python-sibling", &dir.join(name));
367 }
368 }
369 }
370 for path in &self.vendor_markers {
372 h.update(b"vendor-marker");
373 h.update(rel_slash(root, path).as_bytes());
374 h.update(b"\0");
375 }
376 h.update(if root.join("Cargo.toml").exists() {
377 b"cargo-gate:1"
378 } else {
379 b"cargo-gate:0"
380 });
381 h.update(self.walk_error.as_deref().unwrap_or("").as_bytes());
382 h.finalize().to_hex().to_string()
383 }
384
385 fn to_list(&self, root: &Path) -> ConfigList {
386 let rel = |paths: &Vec<PathBuf>| -> Vec<String> {
387 paths
388 .iter()
389 .map(|p| {
390 p.strip_prefix(root)
391 .unwrap_or(p)
392 .to_string_lossy()
393 .replace('\\', "/")
394 })
395 .collect()
396 };
397 ConfigList {
398 go_mods: rel(&self.go_mods),
399 java: rel(&self.java),
400 python: rel(&self.python),
401 gemspecs: rel(&self.gemspecs),
402 cargo_tomls: rel(&self.cargo_tomls),
403 composer: rel(&self.composer),
404 tsconfigs: rel(&self.tsconfigs),
405 vendor_markers: rel(&self.vendor_markers),
406 zig_zons: rel(&self.zig_zons),
407 zig_builds: rel(&self.zig_builds),
408 walk_error: self.walk_error.clone(),
409 }
410 }
411
412 fn from_list(root: &Path, list: &ConfigList) -> Self {
413 let abs =
414 |paths: &Vec<String>| -> Vec<PathBuf> { paths.iter().map(|p| root.join(p)).collect() };
415 Self {
416 go_mods: abs(&list.go_mods),
417 java: abs(&list.java),
418 python: abs(&list.python),
419 gemspecs: abs(&list.gemspecs),
420 cargo_tomls: abs(&list.cargo_tomls),
421 composer: abs(&list.composer),
422 tsconfigs: abs(&list.tsconfigs),
423 vendor_markers: abs(&list.vendor_markers),
424 zig_zons: abs(&list.zig_zons),
425 zig_builds: abs(&list.zig_builds),
426 walk_error: list.walk_error.clone(),
427 }
428 }
429
430 fn check_walk(&self) -> anyhow::Result<()> {
431 match &self.walk_error {
432 Some(e) => Err(anyhow::anyhow!("{}", e)),
433 None => Ok(()),
434 }
435 }
436}
437
438#[derive(Debug, Default)]
440pub struct ResolverConfigs {
441 pub tsconfigs: HashMap<PathBuf, PathAliasMap>,
442 pub go_modules: Vec<GoModule>,
443 pub java_projects: Vec<JavaProject>,
444 pub python_packages: Vec<PythonPackage>,
445 pub ruby_projects: Vec<RubyProject>,
446 pub rust_crates: Vec<RustCrate>,
447 pub php_psr4: Vec<Psr4Mapping>,
448 pub zig_modules: Vec<crate::parsers::zig::ZigModule>,
450 pub vendor: crate::vendor::VendorRules,
452 pub digest: String,
456 files: ConfigFiles,
458}
459
460impl ResolverConfigs {
461 pub fn discover(root: &Path, vendored: &[String]) -> Self {
465 Self::parse(root, ConfigFiles::walk(root), vendored)
466 }
467
468 pub fn from_saved_list(root: &Path, cache_dir: &Path, vendored: &[String]) -> Option<Self> {
472 let bytes = std::fs::read(cache_dir.join(CONFIG_LIST)).ok()?;
473 let list: ConfigList = serde_json::from_slice(&bytes).ok()?;
474 Some(Self::parse(
475 root,
476 ConfigFiles::from_list(root, &list),
477 vendored,
478 ))
479 }
480
481 pub fn save_list(&self, root: &Path, cache_dir: &Path) -> anyhow::Result<()> {
483 let list = self.files.to_list(root);
484 let path = cache_dir.join(CONFIG_LIST);
485 if let Ok(bytes) = std::fs::read(&path)
486 && serde_json::from_slice::<ConfigList>(&bytes).ok().as_ref() == Some(&list)
487 {
488 return Ok(());
489 }
490 let tmp = crate::atomic_write::tmp_path_for(&path);
491 std::fs::write(&tmp, serde_json::to_vec_pretty(&list)?)?;
492 crate::atomic_write::atomic_replace(&tmp, &path)?;
493 Ok(())
494 }
495
496 pub fn lists_any_under(&self, root: &Path, rels: &[String]) -> bool {
499 let list = self.files.to_list(root);
500 [
501 &list.go_mods,
502 &list.java,
503 &list.python,
504 &list.gemspecs,
505 &list.cargo_tomls,
506 &list.composer,
507 &list.tsconfigs,
508 &list.vendor_markers,
509 &list.zig_zons,
510 &list.zig_builds,
511 ]
512 .into_iter()
513 .flatten()
514 .any(|p| {
515 rels.iter().any(|rel| {
516 p == rel
517 || p.strip_prefix(rel.as_str())
518 .is_some_and(|r| r.starts_with('/'))
519 })
520 })
521 }
522
523 fn parse(root: &Path, files: ConfigFiles, vendored: &[String]) -> Self {
524 let digest = {
525 let mut h = blake3::Hasher::new();
526 h.update(files.digest(root).as_bytes());
527 for pattern in vendored {
528 h.update(b"vendored-pattern");
529 h.update(pattern.as_bytes());
530 h.update(b"\0");
531 }
532 h.finalize().to_hex().to_string()
533 };
534 let vendor = crate::vendor::VendorRules::new(root, files.vendor_roots(root), vendored);
535 let mut digest = digest;
536 let zig_modules: Vec<crate::parsers::zig::ZigModule> = files
537 .zig_builds
538 .iter()
539 .filter_map(|p| {
540 let source = std::fs::read_to_string(p).ok()?;
541 Some(crate::parsers::zig::parse_build_zig_modules(
542 &rel_slash(root, p),
543 &source,
544 ))
545 })
546 .flatten()
547 .collect();
548
549 let tsconfigs = crate::parsers::tsconfig::parse_tsconfigs_from(&files.tsconfigs)
550 .unwrap_or_else(|e| {
551 log::warn!("Failed to parse tsconfig.json files: {}", e);
552 HashMap::new()
553 });
554 if !tsconfigs.is_empty() {
555 log::info!("Found {} tsconfig.json files", tsconfigs.len());
556 for (config_dir, alias_map) in &tsconfigs {
557 log::debug!(
558 " {} (base_url: {:?}, {} aliases)",
559 config_dir.display(),
560 alias_map.base_url,
561 alias_map.aliases.len()
562 );
563 }
564 }
565
566 let go_modules = files
567 .check_walk()
568 .and_then(|_| crate::parsers::go::parse_go_modules_from(root, &files.go_mods))
569 .unwrap_or_else(|e| {
570 log::warn!("Failed to parse go.mod files: {}", e);
571 Vec::new()
572 });
573 if !go_modules.is_empty() {
574 log::info!("Found {} Go modules", go_modules.len());
575 for module in &go_modules {
576 log::debug!(" {} (project: {})", module.name, module.project_root);
577 }
578 }
579
580 let java_projects = files
581 .check_walk()
582 .and_then(|_| crate::parsers::java::parse_java_projects_from(root, &files.java))
583 .unwrap_or_else(|e| {
584 log::warn!("Failed to parse Java project configs: {}", e);
585 Vec::new()
586 });
587 if !java_projects.is_empty() {
588 log::info!("Found {} Java projects", java_projects.len());
589 for project in &java_projects {
590 log::debug!(
591 " {} (project: {})",
592 project.package_name,
593 project.project_root
594 );
595 }
596 }
597
598 let python_packages = files
599 .check_walk()
600 .and_then(|_| crate::parsers::python::parse_python_packages_from(root, &files.python))
601 .unwrap_or_else(|e| {
602 log::warn!("Failed to parse Python package configs: {}", e);
603 Vec::new()
604 });
605 if !python_packages.is_empty() {
606 log::info!("Found {} Python packages", python_packages.len());
607 for package in &python_packages {
608 log::debug!(" {} (project: {})", package.name, package.project_root);
609 }
610 }
611
612 let ruby_projects = files
613 .check_walk()
614 .and_then(|_| crate::parsers::ruby::parse_ruby_projects_from(root, &files.gemspecs))
615 .unwrap_or_else(|e| {
616 log::warn!("Failed to parse Ruby project configs: {}", e);
617 Vec::new()
618 });
619 if !ruby_projects.is_empty() {
622 let mut h = blake3::Hasher::new();
623 h.update(digest.as_bytes());
624 for project in &ruby_projects {
625 h.update(project.project_root.as_bytes());
626 for name in &project.provides {
627 h.update(b"\0");
628 h.update(name.as_bytes());
629 }
630 h.update(b"\n");
631 }
632 digest = h.finalize().to_hex().to_string();
633 }
634 if !ruby_projects.is_empty() {
635 log::info!("Found {} Ruby projects", ruby_projects.len());
636 for project in &ruby_projects {
637 log::debug!(" {} (project: {})", project.gem_name, project.project_root);
638 }
639 }
640
641 let rust_crates = if root.join("Cargo.toml").exists() {
643 files
644 .check_walk()
645 .and_then(|_| crate::parsers::rust::parse_rust_crates_from(&files.cargo_tomls))
646 .unwrap_or_else(|e| {
647 log::warn!("Failed to parse Cargo.toml files: {}", e);
648 Vec::new()
649 })
650 } else {
651 Vec::new()
652 };
653 if !rust_crates.is_empty() {
654 log::info!("Found {} Rust workspace crates", rust_crates.len());
655 for krate in &rust_crates {
656 log::debug!(" {} (root: {})", krate.name, krate.root_path.display());
657 }
658 }
659
660 let php_psr4 = files
663 .check_walk()
664 .and_then(|_| {
665 crate::parsers::php::parse_composer_psr4_from(root, files.composer.clone())
666 })
667 .unwrap_or_else(|e| {
668 log::warn!("Failed to parse composer.json files: {}", e);
669 Vec::new()
670 });
671 if !php_psr4.is_empty() {
672 log::info!(
673 "Found {} PSR-4 mappings from composer.json files",
674 php_psr4.len()
675 );
676 for mapping in &php_psr4 {
677 log::debug!(
678 " {} => {} (project: {})",
679 mapping.namespace_prefix,
680 mapping.directory,
681 mapping.project_root
682 );
683 }
684 }
685
686 Self {
687 tsconfigs,
688 go_modules,
689 java_projects,
690 python_packages,
691 ruby_projects,
692 rust_crates,
693 php_psr4,
694 zig_modules,
695 vendor,
696 digest,
697 files,
698 }
699 }
700}
701
702#[derive(Debug, Clone, PartialEq, Eq)]
704pub enum Resolution {
705 File(i64),
707 Package {
710 key: String,
711 member: Option<String>,
712 },
713 Unresolved,
714}
715
716pub fn package_members(rel_path: &str, declared: &[(String, String)]) -> Vec<(String, String)> {
722 let mut members = declared.to_vec();
723 if rel_path.ends_with(".go")
724 && let Some(key) = crate::parsers::go::go_package_member(rel_path)
725 {
726 members.push((key, String::new()));
727 }
728 members
729}
730
731pub struct ResolverContext<'a> {
733 pub root: &'a Path,
734 pub configs: &'a ResolverConfigs,
735}
736
737impl<'a> ResolverContext<'a> {
738 pub fn new(root: &'a Path, configs: &'a ResolverConfigs) -> Self {
739 Self { root, configs }
740 }
741
742 pub fn alias_map_for(&self, file_path: &str) -> Option<&'a PathAliasMap> {
744 find_nearest_tsconfig(file_path, self.root, &self.configs.tsconfigs)
745 }
746
747 pub fn resolve_file_imports(
750 &self,
751 file_id: i64,
752 file_path: &str,
753 import_infos: Vec<ImportInfo>,
754 resolver: &PathResolver,
755 ) -> Vec<Dependency> {
756 let mut resolved_deps = Vec::with_capacity(import_infos.len());
757 for mut import_info in import_infos {
758 self.reclassify(file_path, &mut import_info);
759
760 if matches!(
764 import_info.import_type,
765 ImportType::External | ImportType::Stdlib
766 ) {
767 resolved_deps.push(Dependency {
768 file_id,
769 imported_path: import_info.imported_path.clone(),
770 resolved_file_id: None,
771 resolved_package: None,
772 resolved_member: None,
773 import_type: import_info.import_type.clone(),
774 line_number: import_info.line_number,
775 imported_symbols: import_info.imported_symbols.clone(),
776 });
777 continue;
778 }
779
780 let (resolved_file_id, resolved_package, resolved_member) =
781 match self.resolve(file_path, &import_info, resolver) {
782 Resolution::File(id) => (Some(id), None, None),
783 Resolution::Package { key, member } => (None, Some(key), member),
784 Resolution::Unresolved => (None, None, None),
785 };
786 resolved_deps.push(Dependency {
787 file_id,
788 imported_path: import_info.imported_path.clone(),
789 resolved_file_id,
790 resolved_package,
791 resolved_member,
792 import_type: import_info.import_type,
793 line_number: import_info.line_number,
794 imported_symbols: import_info.imported_symbols.clone(),
795 });
796 }
797 resolved_deps
798 }
799
800 pub fn reclassify(&self, file_path: &str, import_info: &mut ImportInfo) {
803 let go_modules = &self.configs.go_modules;
804 let java_projects = &self.configs.java_projects;
805 let python_packages = &self.configs.python_packages;
806 let ruby_projects = &self.configs.ruby_projects;
807 let rust_crates = &self.configs.rust_crates;
808
809 if file_path.ends_with(".go") {
811 let mut reclassified = false;
813 for module in go_modules {
814 import_info.import_type = crate::parsers::go::reclassify_go_import(
815 &import_info.imported_path,
816 Some(&module.name),
817 );
818 if matches!(import_info.import_type, ImportType::Internal) {
820 reclassified = true;
821 break;
822 }
823 }
824 if !reclassified {
826 import_info.import_type =
827 crate::parsers::go::reclassify_go_import(&import_info.imported_path, None);
828 }
829 }
830
831 if file_path.ends_with(".java") {
833 let mut reclassified = false;
835 for project in java_projects {
836 import_info.import_type = crate::parsers::java::reclassify_java_import(
837 &import_info.imported_path,
838 Some(&project.package_name),
839 );
840 if matches!(import_info.import_type, ImportType::Internal) {
842 reclassified = true;
843 break;
844 }
845 }
846 if !reclassified {
848 import_info.import_type =
849 crate::parsers::java::reclassify_java_import(&import_info.imported_path, None);
850 }
851 }
852
853 if file_path.ends_with(".py") {
855 let mut reclassified = false;
857 for package in python_packages {
858 import_info.import_type = crate::parsers::python::reclassify_python_import(
859 &import_info.imported_path,
860 Some(&package.name),
861 );
862 if matches!(import_info.import_type, ImportType::Internal) {
864 reclassified = true;
865 break;
866 }
867 }
868 if !reclassified {
870 import_info.import_type = crate::parsers::python::reclassify_python_import(
871 &import_info.imported_path,
872 None,
873 );
874 }
875 }
876
877 if file_path.ends_with(".rb")
879 || file_path.ends_with(".rake")
880 || file_path.ends_with(".gemspec")
881 {
882 let mut reclassified = false;
884 for project in ruby_projects {
885 let gem_names = vec![project.gem_name.clone()];
886 import_info.import_type = crate::parsers::ruby::reclassify_ruby_import(
887 &import_info.imported_path,
888 &gem_names,
889 );
890 if matches!(import_info.import_type, ImportType::Internal) {
892 reclassified = true;
893 break;
894 }
895 }
896 if !reclassified {
899 let first = import_info
900 .imported_path
901 .split('/')
902 .next()
903 .unwrap_or_default();
904 reclassified = ruby_projects.iter().any(|p| p.serves(first));
905 if reclassified {
906 import_info.import_type = ImportType::Internal;
907 }
908 }
909 if !reclassified {
911 import_info.import_type =
912 crate::parsers::ruby::reclassify_ruby_import(&import_info.imported_path, &[]);
913 }
914 }
915
916 if file_path.ends_with(".kt") || file_path.ends_with(".kts") {
918 let mut reclassified = false;
920 for project in java_projects {
921 import_info.import_type = crate::parsers::kotlin::reclassify_kotlin_import(
922 &import_info.imported_path,
923 Some(&project.package_name),
924 );
925 if matches!(import_info.import_type, ImportType::Internal) {
927 reclassified = true;
928 break;
929 }
930 }
931 if !reclassified {
933 import_info.import_type = crate::parsers::kotlin::reclassify_kotlin_import(
934 &import_info.imported_path,
935 None,
936 );
937 }
938 }
939
940 if file_path.ends_with(".php")
943 && !self.configs.php_psr4.is_empty()
944 && !import_info.imported_path.contains('/')
945 && !import_info.imported_path.ends_with(".php")
946 && !matches!(import_info.import_type, ImportType::Stdlib)
947 {
948 let internal = self.configs.php_psr4.iter().any(|m| {
949 crate::parsers::php::php_prefix_matches(
950 &import_info.imported_path,
951 &m.namespace_prefix,
952 )
953 });
954 import_info.import_type = if internal {
955 ImportType::Internal
956 } else {
957 ImportType::External
958 };
959 }
960
961 if file_path.ends_with(".zig")
963 && matches!(import_info.import_type, ImportType::External)
964 && crate::parsers::zig::find_zig_module(
965 &import_info.imported_path,
966 file_path,
967 &self.configs.zig_modules,
968 )
969 .is_some()
970 {
971 import_info.import_type = ImportType::Internal;
972 }
973
974 if file_path.ends_with(".rs") && !rust_crates.is_empty() {
976 let new_type = crate::parsers::rust::reclassify_rust_import(
977 &import_info.imported_path,
978 rust_crates,
979 );
980 if matches!(new_type, ImportType::Internal) {
981 import_info.import_type = new_type;
982 }
983 }
984 }
985
986 pub fn resolve(
989 &self,
990 file_path: &str,
991 import_info: &ImportInfo,
992 resolver: &PathResolver,
993 ) -> Resolution {
994 if file_path.ends_with(".go") {
995 return crate::parsers::go::go_package_key(
997 &import_info.imported_path,
998 &self.configs.go_modules,
999 )
1000 .map_or(Resolution::Unresolved, |key| Resolution::Package {
1001 key,
1002 member: None,
1003 });
1004 }
1005 if file_path.ends_with(".cs") {
1006 let path = &import_info.imported_path;
1010 if let Some([member]) = import_info.imported_symbols.as_deref()
1011 && let Some((namespace, last)) = path.rsplit_once('.')
1012 && last == member
1013 {
1014 return Resolution::Package {
1015 key: format!("cs:{namespace}"),
1016 member: Some(member.clone()),
1017 };
1018 }
1019 return Resolution::Package {
1020 key: format!("cs:{path}"),
1021 member: None,
1022 };
1023 }
1024 if [".java", ".kt", ".kts"]
1025 .iter()
1026 .any(|ext| file_path.ends_with(ext))
1027 {
1028 let (key, member) = crate::parsers::java::jvm_import_key(&import_info.imported_path);
1031 return Resolution::Package { key, member };
1032 }
1033 self.resolve_import(file_path, import_info, resolver)
1034 .map_or(Resolution::Unresolved, Resolution::File)
1035 }
1036
1037 pub fn resolve_import(
1041 &self,
1042 file_path: &str,
1043 import_info: &ImportInfo,
1044 resolver: &PathResolver,
1045 ) -> Option<i64> {
1046 let candidates = self.import_candidates(file_path, &import_info.imported_path);
1047 let suffix_ok = matches!(
1051 file_path.rsplit_once('.').map_or("", |(_, e)| e),
1052 "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "h++" | "C" | "H"
1053 );
1054 let found = candidates
1055 .iter()
1056 .find_map(|path| self.lookup(resolver, path, false))
1057 .or_else(|| {
1058 suffix_ok
1059 .then(|| {
1060 candidates
1061 .iter()
1062 .find_map(|p| self.lookup(resolver, p, true))
1063 })
1064 .flatten()
1065 });
1066 if found.is_none() {
1067 log::trace!(
1068 "Could not resolve import '{}' of {}",
1069 import_info.imported_path,
1070 file_path
1071 );
1072 }
1073 found
1074 }
1075
1076 fn import_candidates(&self, file_path: &str, import: &str) -> Vec<String> {
1079 let ext = file_path.rsplit_once('.').map_or("", |(_, e)| e);
1080 match ext {
1081 "php" if import.contains('/') || import.ends_with(".php") => {
1084 fold_path(parent_dir(file_path), import)
1085 .into_iter()
1086 .chain(fold_path("", import))
1087 .collect()
1088 }
1089 "php" => crate::parsers::php::php_namespace_candidates(import, &self.configs.php_psr4),
1090 "py" if !self.configs.python_packages.is_empty() || import.starts_with('.') => {
1091 crate::parsers::python::python_import_candidates(
1092 import,
1093 &self.configs.python_packages,
1094 Some(file_path),
1095 )
1096 }
1097 "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" | "mjs" | "cjs" | "vue" | "svelte" => {
1098 let alias_map =
1099 find_nearest_tsconfig(file_path, self.root, &self.configs.tsconfigs);
1100 crate::parsers::typescript::resolve_ts_import_to_path(
1101 import,
1102 Some(file_path),
1103 alias_map,
1104 )
1105 .map(|c| c.split('|').map(str::to_string).collect())
1106 .unwrap_or_default()
1107 }
1108 "rs" => crate::parsers::rust::resolve_rust_use_to_path(
1111 import,
1112 Some(file_path),
1113 Some(self.root.to_str().unwrap_or("")),
1114 )
1115 .into_iter()
1116 .chain(crate::parsers::rust::resolve_rust_workspace_path(
1117 import,
1118 &self.configs.rust_crates,
1119 ))
1120 .collect(),
1121 "rb" | "rake" | "gemspec" if !self.configs.ruby_projects.is_empty() => {
1122 crate::parsers::ruby::ruby_require_candidates(
1123 import,
1124 &self.configs.ruby_projects,
1125 Some(file_path),
1126 )
1127 }
1128 "c" | "h" => crate::parsers::c::resolve_c_include_to_path(import, Some(file_path))
1129 .into_iter()
1130 .collect(),
1131 "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "h++" | "C" | "H" => {
1132 crate::parsers::cpp::resolve_cpp_include_to_path(import, Some(file_path))
1133 .into_iter()
1134 .collect()
1135 }
1136 "zig" => {
1137 crate::parsers::zig::find_zig_module(import, file_path, &self.configs.zig_modules)
1138 .map(|m| m.root.clone())
1139 .or_else(|| {
1140 crate::parsers::zig::resolve_zig_import_to_path(import, Some(file_path))
1141 })
1142 .into_iter()
1143 .collect()
1144 }
1145 _ => Vec::new(),
1146 }
1147 }
1148
1149 fn lookup(&self, resolver: &PathResolver, path: &str, suffix: bool) -> Option<i64> {
1153 let path = path.replace('\\', "/");
1154 let rel = if Path::new(&path).is_absolute() {
1156 let rel = Path::new(&path).strip_prefix(self.root).ok()?;
1157 rel.to_string_lossy().replace('\\', "/")
1158 } else {
1159 path
1160 };
1161 let rel = fold_path("", &rel)?;
1162 if !suffix {
1163 return resolver.get_exact(&rel);
1164 }
1165 match resolver.get_file_id_by_path(&rel) {
1166 Ok(id) => id,
1167 Err(e) => {
1168 log::debug!("Skipping dependency resolution for '{}': {}", rel, e);
1169 None
1170 }
1171 }
1172 }
1173
1174 pub fn resolve_export(
1176 &self,
1177 file_path: &str,
1178 export_info: &ExportInfo,
1179 resolver: &PathResolver,
1180 ) -> Option<i64> {
1181 let root = self.root;
1182 let tsconfigs = &self.configs.tsconfigs;
1183
1184 if file_path.ends_with(".ts")
1185 || file_path.ends_with(".tsx")
1186 || file_path.ends_with(".js")
1187 || file_path.ends_with(".jsx")
1188 || file_path.ends_with(".mts")
1189 || file_path.ends_with(".cts")
1190 || file_path.ends_with(".mjs")
1191 || file_path.ends_with(".cjs")
1192 || file_path.ends_with(".vue")
1193 {
1194 let alias_map = find_nearest_tsconfig(file_path, root, tsconfigs);
1196 if let Some(candidates_str) = crate::parsers::typescript::resolve_ts_import_to_path(
1197 &export_info.source_path,
1198 Some(file_path),
1199 alias_map,
1200 ) {
1201 let candidates: Vec<&str> = candidates_str.split('|').collect();
1203
1204 let mut resolved_id = None;
1206 for candidate_path in candidates {
1207 let normalized_candidate = if let Ok(rel_path) =
1209 std::path::Path::new(candidate_path).strip_prefix(root)
1210 {
1211 rel_path.to_string_lossy().to_string()
1212 } else {
1213 candidate_path.to_string()
1214 };
1215
1216 match resolver.get_file_id_by_path(&normalized_candidate) {
1217 Ok(Some(id)) => {
1218 log::trace!(
1219 "Resolved export source: {} -> {} (file_id={})",
1220 export_info.source_path,
1221 normalized_candidate,
1222 id
1223 );
1224 resolved_id = Some(id);
1225 break; }
1227 Ok(None) => {
1228 log::trace!("Export source candidate not in index: {}", candidate_path);
1229 }
1230 Err(e) => {
1231 log::debug!(
1232 "Skipping export source resolution for '{}': {}",
1233 normalized_candidate,
1234 e
1235 );
1236 }
1237 }
1238 }
1239
1240 if resolved_id.is_none() {
1241 log::trace!(
1242 "Export source: no matching file found in database for any candidate: {}",
1243 candidates_str
1244 );
1245 }
1246
1247 resolved_id
1248 } else {
1249 log::trace!(
1250 "Could not resolve export source (non-relative or external): {}",
1251 export_info.source_path
1252 );
1253 None
1254 }
1255 } else {
1256 None
1257 }
1258 }
1259}
1260
1261#[cfg(test)]
1262mod tests {
1263 use super::*;
1264 use std::fs;
1265 use tempfile::TempDir;
1266
1267 fn write(root: &Path, rel: &str, body: &str) {
1268 let p = root.join(rel);
1269 fs::create_dir_all(p.parent().unwrap()).unwrap();
1270 fs::write(p, body).unwrap();
1271 }
1272
1273 fn workspace() -> TempDir {
1275 let temp = TempDir::new().unwrap();
1276 let r = temp.path();
1277 write(r, "Cargo.toml", "[package]\nname = \"root_crate\"\n");
1278 write(r, "crates/a/Cargo.toml", "[package]\nname = \"crate_a\"\n");
1279 write(r, "svc/go.mod", "module example.com/svc\n");
1280 write(r, "svc/vendor/x/go.mod", "module example.com/vendored\n");
1281 write(
1282 r,
1283 "java/pom.xml",
1284 "<project>\n<groupId>com.example</groupId>\n</project>\n",
1285 );
1286 write(r, "kt/build.gradle.kts", "group = \"com.kt\"\n");
1287 write(r, "py/pyproject.toml", "[project]\nname = \"pkg\"\n");
1288 write(r, "py/venv/lib/setup.py", "setup(name=\"skipped\")\n");
1289 write(
1290 r,
1291 "rb/thing.gemspec",
1292 "Gem::Specification.new do |s|\n s.name = \"thing\"\nend\n",
1293 );
1294 write(
1295 r,
1296 "php/composer.json",
1297 r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
1298 );
1299 write(
1300 r,
1301 "php/vendor/lib/composer.json",
1302 r#"{"autoload":{"psr-4":{"Lib\\":"src/"}}}"#,
1303 );
1304 write(
1305 r,
1306 "web/tsconfig.json",
1307 r#"{"compilerOptions":{"baseUrl":".","paths":{"@/*":["src/*"]}}}"#,
1308 );
1309 fs::create_dir_all(r.join(".git")).unwrap();
1311 write(r, ".gitignore", "ignored/\n");
1312 write(r, "ignored/go.mod", "module example.com/ignored\n");
1313 temp
1314 }
1315
1316 #[test]
1317 fn one_walk_finds_what_the_seven_finders_found() {
1318 let temp = workspace();
1319 let root = temp.path();
1320 let one = ResolverConfigs::discover(root, &[]);
1321
1322 let mut tsconfigs: Vec<_> = crate::parsers::tsconfig::parse_all_tsconfigs(root)
1323 .unwrap()
1324 .into_iter()
1325 .map(|(k, v)| format!("{:?} {:?}", k, v))
1326 .collect();
1327 tsconfigs.sort();
1328 let mut got: Vec<_> = one
1329 .tsconfigs
1330 .iter()
1331 .map(|(k, v)| format!("{:?} {:?}", k, v))
1332 .collect();
1333 got.sort();
1334 assert_eq!(got, tsconfigs);
1335
1336 let dbg = |v: &dyn std::fmt::Debug| format!("{:?}", v);
1337 assert_eq!(
1338 dbg(&one.go_modules),
1339 dbg(&crate::parsers::go::parse_all_go_modules(root).unwrap())
1340 );
1341 assert_eq!(
1342 dbg(&one.java_projects),
1343 dbg(&crate::parsers::java::parse_all_java_projects(root).unwrap())
1344 );
1345 assert_eq!(
1346 dbg(&one.python_packages),
1347 dbg(&crate::parsers::python::parse_all_python_packages(root).unwrap())
1348 );
1349 assert_eq!(
1350 dbg(&one.ruby_projects),
1351 dbg(&crate::parsers::ruby::parse_all_ruby_projects(root).unwrap())
1352 );
1353 assert_eq!(
1354 dbg(&one.rust_crates),
1355 dbg(&crate::parsers::rust::parse_all_rust_crates(root).unwrap())
1356 );
1357 assert_eq!(
1358 dbg(&one.php_psr4),
1359 dbg(&crate::parsers::php::parse_all_composer_psr4(root).unwrap())
1360 );
1361
1362 assert_eq!(one.go_modules.len(), 1);
1364 assert_eq!(one.python_packages.len(), 1);
1365 assert_eq!(one.rust_crates.len(), 2);
1366 }
1367
1368 #[test]
1369 fn rust_crates_need_a_root_cargo_toml() {
1370 let temp = TempDir::new().unwrap();
1371 write(
1372 temp.path(),
1373 "crates/a/Cargo.toml",
1374 "[package]\nname = \"crate_a\"\n",
1375 );
1376 let one = ResolverConfigs::discover(temp.path(), &[]);
1377 assert!(one.rust_crates.is_empty());
1378 }
1379}