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