Skip to main content

sqry_classpath/resolve/
sbt.rs

1//! sbt classpath resolver.
2//!
3//! Resolves JVM classpath entries from sbt projects by:
4//! 1. Executing `sbt -no-colors "print dependencyClasspath"` to get runtime classpath
5//! 2. Parsing the output for JAR file paths (supports both `Attributed(...)` and
6//!    colon-separated formats)
7//! 3. Extracting Maven coordinates from Coursier cache paths
8//! 4. Looking up source JARs in the Coursier cache
9//! 5. Falling back to cached classpath on failure
10
11use std::io::BufRead;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::time::Duration;
15
16use log::{debug, info, warn};
17
18use crate::{ClasspathError, ClasspathResult};
19
20use super::{ClasspathEntry, ResolveConfig, ResolvedClasspath};
21
22const SBT_CACHE_FILE: &str = "sbt-resolved-classpath.json";
23
24// ── Public API ──────────────────────────────────────────────────────────────
25
26/// Resolve classpath for an sbt project.
27///
28/// Strategy:
29/// 1. Execute `sbt -no-colors "print dependencyClasspath"`
30/// 2. Parse output for JAR paths
31/// 3. On failure, fall back to Coursier cache scanning
32#[allow(clippy::missing_errors_doc)] // Internal helper
33pub fn resolve_sbt_classpath(config: &ResolveConfig) -> ClasspathResult<Vec<ResolvedClasspath>> {
34    info!(
35        "Resolving sbt classpath in {}",
36        config.project_root.display()
37    );
38
39    match run_sbt_dependency_classpath(config) {
40        Ok(jar_paths) => {
41            info!("sbt returned {} JAR paths", jar_paths.len());
42            let entries = build_entries(&jar_paths);
43            let resolved = ResolvedClasspath {
44                module_name: infer_module_name(&config.project_root),
45                module_root: config.project_root.clone(),
46                entries,
47            };
48            Ok(vec![resolved])
49        }
50        Err(e) => {
51            warn!("sbt resolution failed: {e}. Attempting cache fallback.");
52            try_cache_fallback(config, &e)
53        }
54    }
55}
56
57// ── sbt execution ───────────────────────────────────────────────────────────
58
59/// Run `sbt -no-colors "print dependencyClasspath"` and parse JAR paths from output.
60fn run_sbt_dependency_classpath(config: &ResolveConfig) -> ClasspathResult<Vec<PathBuf>> {
61    let sbt_bin = find_sbt_binary()?;
62
63    let mut cmd = Command::new(&sbt_bin);
64    cmd.arg("-no-colors")
65        .arg("print dependencyClasspath")
66        .current_dir(&config.project_root)
67        .stderr(std::process::Stdio::null());
68
69    debug!(
70        "Running: {} -no-colors \"print dependencyClasspath\"",
71        sbt_bin.display()
72    );
73
74    let output = run_command_with_timeout(&mut cmd, config.timeout_secs)?;
75
76    if !output.status.success() {
77        return Err(ClasspathError::ResolutionFailed(format!(
78            "sbt exited with status {}",
79            output.status
80        )));
81    }
82
83    let jars = parse_sbt_output(&output.stdout);
84    Ok(jars)
85}
86
87/// Locate the `sbt` binary on `$PATH`.
88fn find_sbt_binary() -> ClasspathResult<PathBuf> {
89    which_binary("sbt").ok_or_else(|| {
90        ClasspathError::ResolutionFailed(
91            "sbt binary not found on PATH. Install sbt to resolve classpath.".to_string(),
92        )
93    })
94}
95
96/// Parse sbt `print dependencyClasspath` output.
97///
98/// sbt outputs classpath entries in one of these formats:
99///
100/// **Attributed format** (older sbt versions):
101/// ```text
102/// List(Attributed(/path/to/jar1.jar), Attributed(/path/to/jar2.jar))
103/// ```
104///
105/// **Colon-separated format** (newer sbt versions):
106/// ```text
107/// /path/to/jar1.jar:/path/to/jar2.jar
108/// ```
109///
110/// **One-per-line format** (some sbt plugins):
111/// ```text
112/// /path/to/jar1.jar
113/// /path/to/jar2.jar
114/// ```
115///
116/// We handle all three formats, filtering to `.jar` files only.
117#[allow(clippy::manual_let_else)] // Match for error handling clarity
118fn parse_sbt_output(stdout: &[u8]) -> Vec<PathBuf> {
119    let mut jars = Vec::new();
120
121    for line in stdout.lines() {
122        let line = match line {
123            Ok(l) => l,
124            Err(_) => continue,
125        };
126        let trimmed = line.trim();
127        if trimmed.is_empty() {
128            continue;
129        }
130
131        // Skip sbt log/info lines (e.g., "[info] ...", "[success] ...").
132        if is_sbt_log_line(trimmed) {
133            continue;
134        }
135
136        // Try Attributed format first.
137        if trimmed.starts_with("List(") || trimmed.contains("Attributed(") {
138            jars.extend(parse_attributed_format(trimmed));
139            continue;
140        }
141
142        // Try colon-separated format (only if line contains ':' and paths).
143        if trimmed.contains(':') && trimmed.contains(".jar") {
144            jars.extend(parse_colon_separated(trimmed));
145            continue;
146        }
147
148        // One-per-line format: single path per line.
149        if is_jar_path(trimmed) {
150            jars.push(PathBuf::from(trimmed));
151        }
152    }
153
154    jars
155}
156
157/// Parse `Attributed(...)` entries from a line.
158///
159/// Input: `List(Attributed(/path/to/a.jar), Attributed(/path/to/b.jar))`
160/// Output: `["/path/to/a.jar", "/path/to/b.jar"]`
161fn parse_attributed_format(line: &str) -> Vec<PathBuf> {
162    let mut results = Vec::new();
163    let mut search_from = 0;
164
165    while let Some(start) = line[search_from..].find("Attributed(") {
166        let abs_start = search_from + start + "Attributed(".len();
167        if let Some(end) = line[abs_start..].find(')') {
168            let path_str = line[abs_start..abs_start + end].trim();
169            if is_jar_path(path_str) {
170                results.push(PathBuf::from(path_str));
171            }
172            search_from = abs_start + end + 1;
173        } else {
174            break;
175        }
176    }
177
178    results
179}
180
181/// Parse colon-separated classpath entries.
182///
183/// Input: `/path/to/a.jar:/path/to/b.jar:/path/to/c.jar`
184fn parse_colon_separated(line: &str) -> Vec<PathBuf> {
185    line.split(':')
186        .map(str::trim)
187        .filter(|s| is_jar_path(s))
188        .map(PathBuf::from)
189        .collect()
190}
191
192/// Check whether a string looks like a JAR file path.
193fn is_jar_path(s: &str) -> bool {
194    !s.is_empty() && s.to_ascii_lowercase().ends_with(".jar")
195}
196
197/// Check whether a line is an sbt log/info/warning line that should be skipped.
198fn is_sbt_log_line(line: &str) -> bool {
199    line.starts_with("[info]")
200        || line.starts_with("[warn]")
201        || line.starts_with("[error]")
202        || line.starts_with("[success]")
203        || line.starts_with("[debug]")
204}
205
206// ── Coordinate extraction ───────────────────────────────────────────────────
207
208/// Parse Maven coordinates from a Coursier cache path.
209///
210/// Coursier cache paths follow the pattern:
211/// `~/.cache/coursier/v1/https/repo1.maven.org/maven2/<group-path>/<artifact>/<version>/<artifact>-<version>.jar`
212///
213/// We extract `group:artifact:version` from this structure.
214fn parse_coursier_coordinates(jar_path: &Path) -> Option<String> {
215    let path_str = jar_path.to_str()?;
216
217    // Look for the `/maven2/` segment that precedes the Maven layout.
218    let maven2_idx = path_str.find("/maven2/")?;
219    let after_maven2 = &path_str[maven2_idx + "/maven2/".len()..];
220
221    // Split into path components.
222    let components: Vec<&str> = after_maven2.split('/').collect();
223    // Need at least: group-parts... / artifact / version / filename
224    if components.len() < 3 {
225        return None;
226    }
227
228    let filename = *components.last()?;
229    let version = components[components.len() - 2];
230    let artifact = components[components.len() - 3];
231    let group_parts = &components[..components.len() - 3];
232
233    if group_parts.is_empty() {
234        return None;
235    }
236
237    // Verify filename matches expected pattern.
238    let expected_prefix = format!("{artifact}-{version}");
239    if !filename.starts_with(&expected_prefix) {
240        return None;
241    }
242
243    let group = group_parts.join(".");
244    Some(format!("{group}:{artifact}:{version}"))
245}
246
247// ── Entry construction ──────────────────────────────────────────────────────
248
249/// Build `ClasspathEntry` records from JAR paths, enriching with coordinates
250/// and source JAR locations where possible.
251fn build_entries(jar_paths: &[PathBuf]) -> Vec<ClasspathEntry> {
252    jar_paths
253        .iter()
254        .map(|jar_path| {
255            let coordinates = parse_coursier_coordinates(jar_path);
256            let source_jar = find_source_jar(jar_path);
257
258            ClasspathEntry {
259                jar_path: jar_path.clone(),
260                coordinates,
261                is_direct: false, // sbt dependencyClasspath returns the full transitive closure.
262                source_jar,
263            }
264        })
265        .collect()
266}
267
268/// Find a source JAR alongside a main JAR.
269///
270/// Looks for `<stem>-sources.jar` in the same directory.
271fn find_source_jar(jar_path: &Path) -> Option<PathBuf> {
272    let stem = jar_path.file_stem()?.to_string_lossy();
273    let parent = jar_path.parent()?;
274
275    // Try `<stem>-sources.jar` in the same directory.
276    let sources_jar = parent.join(format!("{stem}-sources.jar"));
277    if sources_jar.exists() {
278        return Some(sources_jar);
279    }
280
281    // Try Coursier-style: derive `-sources.jar` path.
282    if let Some(coursier_sources) = derive_coursier_source_jar(jar_path)
283        && coursier_sources.exists()
284    {
285        return Some(coursier_sources);
286    }
287
288    None
289}
290
291/// Derive the Coursier cache path for a source JAR given the main JAR path.
292#[allow(clippy::case_sensitive_file_extension_comparisons)] // Known file extensions
293fn derive_coursier_source_jar(jar_path: &Path) -> Option<PathBuf> {
294    let path_str = jar_path.to_str()?;
295    if path_str.ends_with(".jar") && !path_str.ends_with("-sources.jar") {
296        let sources_path = format!("{}-sources.jar", &path_str[..path_str.len() - 4]);
297        Some(PathBuf::from(sources_path))
298    } else {
299        None
300    }
301}
302
303// ── Cache fallback ──────────────────────────────────────────────────────────
304
305/// Attempt to load a previously cached classpath when live resolution fails.
306fn try_cache_fallback(
307    config: &ResolveConfig,
308    original_error: &ClasspathError,
309) -> ClasspathResult<Vec<ResolvedClasspath>> {
310    if let Some(ref cache_path) = config.cache_path {
311        let cache_path = if cache_path.is_dir() {
312            cache_path.join(SBT_CACHE_FILE)
313        } else {
314            cache_path.clone()
315        };
316        if cache_path.exists() {
317            info!("Loading cached classpath from {}", cache_path.display());
318            let content = std::fs::read_to_string(&cache_path).map_err(|e| {
319                ClasspathError::CacheError(format!(
320                    "Failed to read cache file {}: {e}",
321                    cache_path.display()
322                ))
323            })?;
324            let cached: Vec<ResolvedClasspath> = serde_json::from_str(&content).map_err(|e| {
325                ClasspathError::CacheError(format!(
326                    "Failed to parse cache file {}: {e}",
327                    cache_path.display()
328                ))
329            })?;
330            return Ok(cached);
331        }
332        warn!(
333            "Cache file {} does not exist; cannot fall back",
334            cache_path.display()
335        );
336    }
337
338    Err(ClasspathError::ResolutionFailed(format!(
339        "sbt resolution failed and no cache available. Original error: {original_error}"
340    )))
341}
342
343// ── Utility functions ───────────────────────────────────────────────────────
344
345/// Find a binary on `$PATH` using `which`-style lookup.
346fn which_binary(name: &str) -> Option<PathBuf> {
347    let path_var = std::env::var_os("PATH")?;
348    for dir in std::env::split_paths(&path_var) {
349        let candidate = dir.join(name);
350        if candidate.is_file() {
351            return Some(candidate);
352        }
353    }
354    None
355}
356
357/// Run a command with a timeout, returning its output.
358fn run_command_with_timeout(
359    cmd: &mut Command,
360    timeout_secs: u64,
361) -> ClasspathResult<std::process::Output> {
362    let mut child = cmd
363        .stdout(std::process::Stdio::piped())
364        .spawn()
365        .map_err(|e| ClasspathError::ResolutionFailed(format!("Failed to spawn command: {e}")))?;
366
367    let timeout = Duration::from_secs(timeout_secs);
368
369    let start = std::time::Instant::now();
370    loop {
371        match child.try_wait() {
372            Ok(Some(_status)) => {
373                return child.wait_with_output().map_err(|e| {
374                    ClasspathError::ResolutionFailed(format!("Failed to collect output: {e}"))
375                });
376            }
377            Ok(None) => {
378                if start.elapsed() >= timeout {
379                    let _ = child.kill();
380                    let _ = child.wait();
381                    return Err(ClasspathError::ResolutionFailed(format!(
382                        "Command timed out after {timeout_secs}s"
383                    )));
384                }
385                std::thread::sleep(Duration::from_millis(100));
386            }
387            Err(e) => {
388                return Err(ClasspathError::ResolutionFailed(format!(
389                    "Failed to check process status: {e}"
390                )));
391            }
392        }
393    }
394}
395
396/// Infer a module name from the project root directory name.
397fn infer_module_name(project_root: &Path) -> String {
398    project_root
399        .file_name()
400        .map_or_else(|| "root".to_string(), |n| n.to_string_lossy().to_string())
401}
402
403// ── Tests ───────────────────────────────────────────────────────────────────
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use tempfile::TempDir;
409
410    // ── Test: parse sbt Attributed output ───────────────────────────────
411
412    #[test]
413    fn test_parse_attributed_format() {
414        let line =
415            "List(Attributed(/path/to/guava-33.0.0.jar), Attributed(/path/to/slf4j-api-2.0.9.jar))";
416        let result = parse_attributed_format(line);
417        assert_eq!(result.len(), 2);
418        assert_eq!(result[0], PathBuf::from("/path/to/guava-33.0.0.jar"));
419        assert_eq!(result[1], PathBuf::from("/path/to/slf4j-api-2.0.9.jar"));
420    }
421
422    #[test]
423    fn test_parse_attributed_format_single() {
424        let line = "List(Attributed(/only/one.jar))";
425        let result = parse_attributed_format(line);
426        assert_eq!(result.len(), 1);
427        assert_eq!(result[0], PathBuf::from("/only/one.jar"));
428    }
429
430    #[test]
431    fn test_parse_attributed_format_filters_non_jar() {
432        let line = "List(Attributed(/path/to/classes), Attributed(/path/to/real.jar))";
433        let result = parse_attributed_format(line);
434        assert_eq!(result.len(), 1);
435        assert_eq!(result[0], PathBuf::from("/path/to/real.jar"));
436    }
437
438    // ── Test: parse sbt colon-separated output ──────────────────────────
439
440    #[test]
441    fn test_parse_colon_separated() {
442        let line = "/path/to/a.jar:/path/to/b.jar:/path/to/c.jar";
443        let result = parse_colon_separated(line);
444        assert_eq!(result.len(), 3);
445        assert_eq!(result[0], PathBuf::from("/path/to/a.jar"));
446        assert_eq!(result[1], PathBuf::from("/path/to/b.jar"));
447        assert_eq!(result[2], PathBuf::from("/path/to/c.jar"));
448    }
449
450    #[test]
451    fn test_parse_colon_separated_filters_non_jar() {
452        let line = "/path/to/a.jar:/path/to/classes:/path/to/b.jar";
453        let result = parse_colon_separated(line);
454        assert_eq!(result.len(), 2);
455    }
456
457    // ── Test: parse full sbt output ─────────────────────────────────────
458
459    #[test]
460    fn test_parse_sbt_output_attributed() {
461        let output = b"\
462[info] Loading settings for project root from build.sbt ...
463[info] Set current project to myproject
464List(Attributed(/home/user/.cache/coursier/v1/https/repo1.maven.org/maven2/com/google/guava/guava/33.0.0/guava-33.0.0.jar), Attributed(/home/user/.cache/coursier/v1/https/repo1.maven.org/maven2/org/slf4j/slf4j-api/2.0.9/slf4j-api-2.0.9.jar))
465[success] Total time: 1 s
466";
467        let result = parse_sbt_output(output);
468        assert_eq!(result.len(), 2);
469        assert!(result[0].to_str().unwrap().contains("guava-33.0.0.jar"));
470        assert!(result[1].to_str().unwrap().contains("slf4j-api-2.0.9.jar"));
471    }
472
473    #[test]
474    fn test_parse_sbt_output_colon_separated() {
475        let output = b"\
476[info] Loading project definition
477/path/to/a.jar:/path/to/b.jar
478[success] Done
479";
480        let result = parse_sbt_output(output);
481        assert_eq!(result.len(), 2);
482    }
483
484    #[test]
485    fn test_parse_sbt_output_one_per_line() {
486        let output = b"\
487/path/to/a.jar
488/path/to/b.jar
489/path/to/c.jar
490";
491        let result = parse_sbt_output(output);
492        assert_eq!(result.len(), 3);
493    }
494
495    #[test]
496    fn test_parse_sbt_output_empty() {
497        let result = parse_sbt_output(b"");
498        assert!(result.is_empty());
499    }
500
501    #[test]
502    fn test_parse_sbt_output_only_log_lines() {
503        let output = b"\
504[info] Loading settings
505[info] Set current project
506[success] Total time: 0 s
507";
508        let result = parse_sbt_output(output);
509        assert!(result.is_empty());
510    }
511
512    // ── Test: sbt log line detection ────────────────────────────────────
513
514    #[test]
515    fn test_is_sbt_log_line() {
516        assert!(is_sbt_log_line("[info] Loading settings"));
517        assert!(is_sbt_log_line("[warn] Deprecated API"));
518        assert!(is_sbt_log_line("[error] Compilation failed"));
519        assert!(is_sbt_log_line("[success] Total time: 1 s"));
520        assert!(is_sbt_log_line("[debug] Resolving dependencies"));
521        assert!(!is_sbt_log_line("/path/to/jar.jar"));
522        assert!(!is_sbt_log_line("List(Attributed(/path.jar))"));
523    }
524
525    // ── Test: Coursier coordinate extraction ────────────────────────────
526
527    #[test]
528    fn test_parse_coursier_coordinates() {
529        let path = PathBuf::from(
530            "/home/user/.cache/coursier/v1/https/repo1.maven.org/maven2/com/google/guava/guava/33.0.0/guava-33.0.0.jar",
531        );
532        let coords = parse_coursier_coordinates(&path);
533        assert_eq!(coords, Some("com.google.guava:guava:33.0.0".to_string()));
534    }
535
536    #[test]
537    fn test_parse_coursier_coordinates_scala_library() {
538        let path = PathBuf::from(
539            "/home/user/.cache/coursier/v1/https/repo1.maven.org/maven2/org/scala-lang/scala-library/2.13.12/scala-library-2.13.12.jar",
540        );
541        let coords = parse_coursier_coordinates(&path);
542        assert_eq!(
543            coords,
544            Some("org.scala-lang:scala-library:2.13.12".to_string())
545        );
546    }
547
548    #[test]
549    fn test_parse_coursier_coordinates_not_coursier() {
550        let path = PathBuf::from("/usr/local/lib/some.jar");
551        assert_eq!(parse_coursier_coordinates(&path), None);
552    }
553
554    // ── Test: missing sbt binary ────────────────────────────────────────
555
556    #[test]
557    fn test_missing_sbt_binary_error() {
558        let tmp = TempDir::new().unwrap();
559        let original_path = std::env::var_os("PATH");
560
561        // SAFETY: This test is not run in parallel with other tests that depend
562        // on PATH. We restore the original value immediately after the check.
563        unsafe { std::env::set_var("PATH", tmp.path()) };
564        let result = find_sbt_binary();
565        if let Some(p) = original_path {
566            unsafe { std::env::set_var("PATH", p) };
567        }
568
569        assert!(result.is_err());
570        let err_msg = result.unwrap_err().to_string();
571        assert!(
572            err_msg.contains("not found"),
573            "Error should mention 'not found': {err_msg}"
574        );
575    }
576
577    // ── Test: resolve with no sbt and no cache ──────────────────────────
578
579    #[test]
580    fn test_resolve_no_sbt_no_cache_returns_error() {
581        let tmp = TempDir::new().unwrap();
582        let config = ResolveConfig {
583            project_root: tmp.path().to_path_buf(),
584            timeout_secs: 5,
585            cache_path: None,
586        };
587
588        let result = resolve_sbt_classpath(&config);
589        assert!(result.is_err());
590    }
591
592    // ── Test: cache fallback ────────────────────────────────────────────
593
594    #[test]
595    fn test_cache_fallback_loads_cached_classpath() {
596        let tmp = TempDir::new().unwrap();
597        let cache_path = tmp.path().join("classpath_cache.json");
598
599        let cached = vec![ResolvedClasspath {
600            module_name: "cached-scala-project".to_string(),
601            module_root: tmp.path().to_path_buf(),
602            entries: vec![ClasspathEntry {
603                jar_path: PathBuf::from("/cached/scala-library.jar"),
604                coordinates: Some("org.scala-lang:scala-library:2.13.12".to_string()),
605                is_direct: false,
606                source_jar: None,
607            }],
608        }];
609        std::fs::write(&cache_path, serde_json::to_string(&cached).unwrap()).unwrap();
610
611        let original_error = ClasspathError::ResolutionFailed("sbt not found".to_string());
612        let config = ResolveConfig {
613            project_root: tmp.path().to_path_buf(),
614            timeout_secs: 5,
615            cache_path: Some(cache_path),
616        };
617
618        let result = try_cache_fallback(&config, &original_error);
619        assert!(result.is_ok());
620        let resolved = result.unwrap();
621        assert_eq!(resolved.len(), 1);
622        assert_eq!(resolved[0].module_name, "cached-scala-project");
623        assert_eq!(resolved[0].entries.len(), 1);
624    }
625
626    #[test]
627    fn test_cache_fallback_missing_cache_file() {
628        let tmp = TempDir::new().unwrap();
629        let cache_path = tmp.path().join("nonexistent.json");
630        let original_error = ClasspathError::ResolutionFailed("sbt not found".to_string());
631        let config = ResolveConfig {
632            project_root: tmp.path().to_path_buf(),
633            timeout_secs: 5,
634            cache_path: Some(cache_path),
635        };
636
637        let result = try_cache_fallback(&config, &original_error);
638        assert!(result.is_err());
639    }
640
641    #[test]
642    fn test_cache_fallback_no_cache_configured() {
643        let original_error = ClasspathError::ResolutionFailed("sbt not found".to_string());
644        let config = ResolveConfig {
645            project_root: PathBuf::from("/tmp"),
646            timeout_secs: 5,
647            cache_path: None,
648        };
649
650        let result = try_cache_fallback(&config, &original_error);
651        assert!(result.is_err());
652        let err_msg = result.unwrap_err().to_string();
653        assert!(err_msg.contains("no cache available"));
654    }
655
656    // ── Test: source JAR discovery ──────────────────────────────────────
657
658    #[test]
659    fn test_find_source_jar_same_directory() {
660        let tmp = TempDir::new().unwrap();
661        let main_jar = tmp.path().join("scala-library-2.13.12.jar");
662        let sources_jar = tmp.path().join("scala-library-2.13.12-sources.jar");
663        std::fs::write(&main_jar, b"").unwrap();
664        std::fs::write(&sources_jar, b"").unwrap();
665
666        let result = find_source_jar(&main_jar);
667        assert_eq!(result, Some(sources_jar));
668    }
669
670    #[test]
671    fn test_find_source_jar_not_present() {
672        let tmp = TempDir::new().unwrap();
673        let main_jar = tmp.path().join("scala-library-2.13.12.jar");
674        std::fs::write(&main_jar, b"").unwrap();
675
676        let result = find_source_jar(&main_jar);
677        assert_eq!(result, None);
678    }
679
680    // ── Test: build_entries enrichment ───────────────────────────────────
681
682    #[test]
683    fn test_build_entries_with_coursier_path() {
684        let jar_paths = vec![
685            PathBuf::from(
686                "/home/user/.cache/coursier/v1/https/repo1.maven.org/maven2/com/google/guava/guava/33.0.0/guava-33.0.0.jar",
687            ),
688            PathBuf::from("/some/local/path/unknown.jar"),
689        ];
690
691        let entries = build_entries(&jar_paths);
692        assert_eq!(entries.len(), 2);
693        assert_eq!(
694            entries[0].coordinates,
695            Some("com.google.guava:guava:33.0.0".to_string())
696        );
697        assert_eq!(entries[1].coordinates, None);
698        assert!(!entries[0].is_direct);
699        assert!(!entries[1].is_direct);
700    }
701
702    // ── Test: infer_module_name ─────────────────────────────────────────
703
704    #[test]
705    fn test_infer_module_name() {
706        assert_eq!(
707            infer_module_name(Path::new("/home/user/my-scala-project")),
708            "my-scala-project"
709        );
710        assert_eq!(infer_module_name(Path::new("/")), "root");
711    }
712
713    // ── Test: derive_coursier_source_jar ────────────────────────────────
714
715    #[test]
716    fn test_derive_coursier_source_jar() {
717        let jar = PathBuf::from("/cache/v1/scala-library-2.13.12.jar");
718        let result = derive_coursier_source_jar(&jar);
719        assert_eq!(
720            result,
721            Some(PathBuf::from("/cache/v1/scala-library-2.13.12-sources.jar"))
722        );
723    }
724
725    #[test]
726    fn test_derive_coursier_source_jar_already_sources() {
727        let jar = PathBuf::from("/cache/v1/scala-library-2.13.12-sources.jar");
728        let result = derive_coursier_source_jar(&jar);
729        assert_eq!(result, None);
730    }
731}