Skip to main content

reflex/
dependency_resolve.rs

1//! Import resolution for the dependency pass.
2//!
3//! Two parts, both taken out of `Indexer::index_with_callback` unchanged:
4//!
5//! - [`ResolverConfigs`]: the project files that change how imports are classified
6//!   and resolved (`go.mod`, Maven/Gradle builds, Python package configs, gemspecs,
7//!   `Cargo.toml`, `composer.json`, `tsconfig.json`). They are found by ONE walk
8//!   that applies each finder's own rules; the seven finders used to walk the tree
9//!   once each.
10//! - [`ResolverContext`]: the per-language rules that reclassify an extracted import
11//!   and resolve it (or a re-export's source) to a `files.id`.
12//!
13//! Resolution depends on the whole set of indexed paths (through [`PathResolver`]'s
14//! suffix matching) and on these configs, not only on the importing file.
15
16use 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
31/// Find the nearest tsconfig.json for a given source file
32///
33/// Walks up the directory tree from the source file to find the nearest tsconfig directory.
34/// Returns a reference to the PathAliasMap if found.
35pub fn find_nearest_tsconfig<'a>(
36    file_path: &str,
37    root: &Path,
38    tsconfigs: &'a HashMap<PathBuf, PathAliasMap>,
39) -> Option<&'a PathAliasMap> {
40    // Convert file_path to absolute path (relative to root)
41    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    // Start from the file's directory and walk up
48    let mut current_dir = abs_file_path.parent()?;
49
50    loop {
51        // Check if we have a tsconfig for this directory
52        if let Some(alias_map) = tsconfigs.get(current_dir) {
53            return Some(alias_map);
54        }
55
56        // Move up one directory
57        current_dir = current_dir.parent()?;
58
59        // Stop if we've reached the root
60        if current_dir == root || !current_dir.starts_with(root) {
61            break;
62        }
63    }
64
65    None
66}
67
68/// The file under `.reflex/` that lists the config files the last walk found, so
69/// an update that does not walk can parse the same configs.
70pub const CONFIG_LIST: &str = "resolver-configs.json";
71
72/// Whether a file with this name is a resolver config (one the config walk keeps).
73pub 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            // Vendoring markers (`crate::vendor`)
87            | "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
97/// `dir/rel` with `.` and `..` folded without touching the disk, `/`-separated.
98/// An absolute `dir` (or `rel`) stays absolute. `None` when `..` climbs above the
99/// start or nothing is left.
100///
101/// Resolvers used `canonicalize()`, which reads the disk relative to the process's
102/// working directory: a root-relative path resolved only when the process ran in
103/// the root.
104pub 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
129/// The directory part of a `/`-separated file path (`""` for a bare name).
130pub fn parent_dir(file: &str) -> &str {
131    file.rsplit_once('/').map_or("", |(dir, _)| dir)
132}
133
134/// `path` relative to `root`, `/`-separated.
135fn 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/// [`ConfigFiles`] on disk: paths relative to the root, `/`-separated.
143#[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/// The config files one walk found, per kind, in walk order.
164#[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    /// Vendoring markers (`crate::vendor::marker_root`): only their paths matter.
174    vendor_markers: Vec<PathBuf>,
175    /// `build.zig.zon` files, whose path dependencies are vendored roots.
176    zig_zons: Vec<PathBuf>,
177    /// `build.zig` files, whose named modules `@import("name")` reaches.
178    zig_builds: Vec<PathBuf>,
179    /// `Package.swift` files, whose targets are the modules `import Name` reaches.
180    swift_packages: Vec<PathBuf>,
181    /// The first walk error. Every finder except tsconfig's stopped on its first
182    /// error (`entry?`) and returned it, so their kinds fail with it here too.
183    walk_error: Option<String>,
184}
185
186impl ConfigFiles {
187    /// One walk with the settings all seven finders shared (a default `WalkBuilder`
188    /// with `follow_links(false)`, `git_ignore(true)`), keeping each finder's own
189    /// filter.
190    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            // Rust's finder matched the name alone; tsconfig's likewise.
236            if filename == "Cargo.toml" {
237                out.cargo_tomls.push(path.to_path_buf());
238                // A `cargo vendor` crate: the walk skips the dotfile itself
239                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            // Normalize separators so the directory filters work on Windows too.
251            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    /// The vendored roots the markers and `build.zig.zon` path dependencies name,
286    /// relative and `/`-terminated.
287    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    /// Drop the configs of vendored code: a vendored crate's `Cargo.toml` would make
305    /// its crate Internal, a vendored gemspec its gem.
306    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        // A vendored module's own markers and path dependencies are not ours
322        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        // A package checked out under `Pods/` or `Carthage/` is a dependency
332        self.swift_packages
333            .retain(|p| !rules.is_vendored(&rel_slash(root, p), crate::models::Language::Swift));
334    }
335
336    /// A digest of everything the config parsers read: each kind's files in walk
337    /// order with their bytes, the Python parser's sibling files, the root
338    /// `Cargo.toml` gate and the walk error. Equal digests mean equal configs.
339    fn digest(&self, root: &Path) -> String {
340        let mut h = blake3::Hasher::new();
341        let mut file = |tag: &str, path: &Path| {
342            // `/`-separated: a walk and the saved list spell a path alike on Windows
343            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        // `find_python_package_name` reads all three names in each project root.
379        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        // A marker's bytes change on every `go mod vendor`; its root does not.
387        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/// Every resolver config of a workspace, parsed.
457#[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    /// Named modules the workspace's `build.zig` files define.
467    pub zig_modules: Vec<crate::parsers::zig::ZigModule>,
468    /// Targets the workspace's `Package.swift` files define, in walk order.
469    pub swift_modules: Vec<SwiftModule>,
470    /// Which files are vendored: the markers found, plus `[index.vendored] patterns`.
471    pub vendor: crate::vendor::VendorRules,
472    /// Digest of every input above (see `ConfigFiles::digest`) and the vendored
473    /// patterns. An index run whose digest differs from the stored one re-resolves
474    /// and re-flags every file.
475    pub digest: String,
476    /// The config files these were parsed from.
477    files: ConfigFiles,
478}
479
480impl ResolverConfigs {
481    /// Find and parse every resolver config under `root`. A kind that fails to parse
482    /// is logged and left empty, as before.
483    /// `vendored` is `[index.vendored] patterns`.
484    pub fn discover(root: &Path, vendored: &[String]) -> Self {
485        Self::parse(root, ConfigFiles::walk(root), vendored)
486    }
487
488    /// Parse the config files listed in `cache_dir` by [`Self::save_list`], without
489    /// walking. `None` when there is no list. The caller compares the digest with
490    /// the stored one: a listed file that changed shows there.
491    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    /// Write the list of config files (atomically) unless it is already there.
502    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    /// Whether any of `rels` (relative, `/`-separated) is a listed config file or
517    /// a directory above one.
518    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        // What each gem's lib/ provides decides which requires are Internal: a new
653        // top-level name there must re-resolve every file
654        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        // Gate: only a workspace with a root `Cargo.toml` is scanned for crates.
675        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        // Note: Kotlin projects use the same java_projects above (same build systems: Maven/Gradle)
694
695        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/// What an import resolved to (see [`ResolverContext::resolve`]).
737#[derive(Debug, Clone, PartialEq, Eq)]
738pub enum Resolution {
739    /// One indexed file (`file_dependencies.resolved_file_id`).
740    File(i64),
741    /// A package key (`resolved_package`) and optionally one member of it
742    /// (`resolved_member`); the graph reaches every file in `package_members`.
743    Package {
744        key: String,
745        member: Option<String>,
746    },
747    Unresolved,
748}
749
750/// The resolution rules for one workspace, over its parsed configs.
751pub 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    /// The `(package key, member)` rows that make the file at `rel_path` reachable
762    /// by package imports (`package_members`): a Go file's directory, a Swift
763    /// file's SwiftPM target, plus what its content declares (`declared`: a JVM
764    /// package and top-level names, C# namespaces, types and sub-namespaces).
765    /// Member `""` stands for the whole package: an import with no member reaches
766    /// exactly the `""` rows. A target comes from `Package.swift`, a resolver
767    /// config: a change to one rewrites every file's rows (`full_deps`).
768    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    /// The alias map a TS/JS/Vue file is extracted and resolved with.
797    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    /// Every extracted import of one file, reclassified and resolved, as the rows
802    /// `replace_dependencies` writes.
803    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            // External and Stdlib imports: store with resolved_file_id = None.
815            // Graph-analysis queries all filter WHERE resolved_file_id IS NOT NULL,
816            // so storing these here only affects the `rfx deps` display path (REF-78).
817            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    /// Reclassify an extracted import with the workspace's module, package and
855    /// crate names.
856    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        // Reclassify Go imports using module names (if Go project)
864        if file_path.ends_with(".go") {
865            // Check if the import matches any Go module
866            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 it's internal, we've found the right module
873                if matches!(import_info.import_type, ImportType::Internal) {
874                    reclassified = true;
875                    break;
876                }
877            }
878            // If no module matched, use base classification
879            if !reclassified {
880                import_info.import_type =
881                    crate::parsers::go::reclassify_go_import(&import_info.imported_path, None);
882            }
883        }
884
885        // Reclassify Java imports using package names (if Java project)
886        if file_path.ends_with(".java") {
887            // Check if the import matches any Java project
888            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 it's internal, we've found the right project
895                if matches!(import_info.import_type, ImportType::Internal) {
896                    reclassified = true;
897                    break;
898                }
899            }
900            // If no project matched, use base classification
901            if !reclassified {
902                import_info.import_type =
903                    crate::parsers::java::reclassify_java_import(&import_info.imported_path, None);
904            }
905        }
906
907        // Reclassify Python imports using package names (if Python project)
908        if file_path.ends_with(".py") {
909            // Check if the import matches any Python package
910            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 it's internal, we've found the right package
917                if matches!(import_info.import_type, ImportType::Internal) {
918                    reclassified = true;
919                    break;
920                }
921            }
922            // If no package matched, use base classification
923            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        // Reclassify Ruby imports using gem names (if Ruby project)
932        if file_path.ends_with(".rb")
933            || file_path.ends_with(".rake")
934            || file_path.ends_with(".gemspec")
935        {
936            // Check if the import matches any Ruby project
937            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 it's internal, we've found the right project
945                if matches!(import_info.import_type, ImportType::Internal) {
946                    reclassified = true;
947                    break;
948                }
949            }
950            // A name some workspace gem's lib/ provides (`active_support` is in the
951            // gem `activesupport`)
952            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 no project matched, use base classification (will be External or Stdlib)
964            if !reclassified {
965                import_info.import_type =
966                    crate::parsers::ruby::reclassify_ruby_import(&import_info.imported_path, &[]);
967            }
968        }
969
970        // Reclassify Kotlin imports using package names (if Kotlin project)
971        if file_path.ends_with(".kt") || file_path.ends_with(".kts") {
972            // Check if the import matches any Java/Kotlin project (same build systems)
973            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 it's internal, we've found the right project
980                if matches!(import_info.import_type, ImportType::Internal) {
981                    reclassified = true;
982                    break;
983                }
984            }
985            // If no project matched, use base classification
986            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        // With composer.json, a PHP `use` is Internal exactly when a project
995        // autoload prefix holds it (Illuminate\... in vendor/ is External)
996        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        // A target of the workspace's Package.swift files, even one named like an
1016        // SDK framework
1017        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        // A Zig module name the workspace's build.zig defines
1029        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        // Reclassify Rust imports using workspace crates
1042        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    /// Where an import that is neither External nor Stdlib leads: one file, or a
1054    /// package the graph expands to its member files ([`Self::package_members`]).
1055    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            // A Go import names a package (a directory), never one file
1063            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            // `using A.B` names a namespace: every file that declares it.
1074            // `using static A.B.C` / `using X = A.B.C` name member `C` of `A.B`:
1075            // the files declaring type `C` there, or namespace `A.B.C`
1076            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            // `import Core` names a SwiftPM target: every file of its directory
1093            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            // A JVM import names a package and a class or top-level name in it,
1108            // wherever (in whichever module) the file declaring it lives
1109            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    /// The `files.id` an import that is neither External nor Stdlib resolves to,
1117    /// for the languages whose imports name one file (see [`Self::resolve`]): the
1118    /// first of the language's candidate paths that is indexed.
1119    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        // Candidates are exact paths. Only C/C++ falls back to a suffix match, in
1127        // place of the include-path search a compiler does; elsewhere a suffix
1128        // finds the wrong file (`django.py` for `from django import forms`).
1129        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    /// The paths an import of `file_path` may name, most likely first. They may be
1156    /// absolute (under the root) or relative to it; [`Self::lookup`] takes either.
1157    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            // A `require 'x.php'` names a file: beside the requiring file, else
1161            // from the root; a `use` names a class the autoload mappings place
1162            "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            // A module of this crate, else another workspace crate (`use b::x`
1188            // also reads as a local module `b`)
1189            "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    /// The `files.id` of `path`: absolute under the root, or relative to it, with
1229    /// `.` and `..` folded. A path outside the root is not indexed. With `suffix`,
1230    /// a unique file ending in the path's whole segments also counts.
1231    fn lookup(&self, resolver: &PathResolver, path: &str, suffix: bool) -> Option<i64> {
1232        let path = path.replace('\\', "/");
1233        // `/x` on Unix, `C:/x` on Windows
1234        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    /// The `files.id` a re-export's source resolves to (TS/JS/Vue only).
1254    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            // Resolve TypeScript/JavaScript/Vue export paths (relative imports and path aliases)
1274            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                // Parse pipe-delimited candidates (e.g., "path.tsx|path.ts|path.jsx|path.js|path.vue")
1281                let candidates: Vec<&str> = candidates_str.split('|').collect();
1282
1283                // Try each candidate in order until we find one in the database
1284                let mut resolved_id = None;
1285                for candidate_path in candidates {
1286                    // Normalize path to be relative to project root
1287                    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; // Found a match, stop trying
1305                        }
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    /// A tree with every config kind, plus each finder's skip rule.
1353    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        // `.gitignore` applies only inside a repository.
1389        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        // The skip rules held: vendored and ignored configs are not there.
1442        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}