1use 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#[allow(clippy::missing_errors_doc)] pub 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
57fn 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
87fn 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#[allow(clippy::manual_let_else)] fn 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 if is_sbt_log_line(trimmed) {
133 continue;
134 }
135
136 if trimmed.starts_with("List(") || trimmed.contains("Attributed(") {
138 jars.extend(parse_attributed_format(trimmed));
139 continue;
140 }
141
142 if trimmed.contains(':') && trimmed.contains(".jar") {
144 jars.extend(parse_colon_separated(trimmed));
145 continue;
146 }
147
148 if is_jar_path(trimmed) {
150 jars.push(PathBuf::from(trimmed));
151 }
152 }
153
154 jars
155}
156
157fn 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
181fn 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
192fn is_jar_path(s: &str) -> bool {
194 !s.is_empty() && s.to_ascii_lowercase().ends_with(".jar")
195}
196
197fn 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
206fn parse_coursier_coordinates(jar_path: &Path) -> Option<String> {
215 let path_str = jar_path.to_str()?;
216
217 let maven2_idx = path_str.find("/maven2/")?;
219 let after_maven2 = &path_str[maven2_idx + "/maven2/".len()..];
220
221 let components: Vec<&str> = after_maven2.split('/').collect();
223 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 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
247fn 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, source_jar,
263 }
264 })
265 .collect()
266}
267
268fn 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 let sources_jar = parent.join(format!("{stem}-sources.jar"));
277 if sources_jar.exists() {
278 return Some(sources_jar);
279 }
280
281 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#[allow(clippy::case_sensitive_file_extension_comparisons)] fn 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
303fn 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
343fn 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
357fn 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
396fn 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#[cfg(test)]
406mod tests {
407 use super::*;
408 use tempfile::TempDir;
409
410 #[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]
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]
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]
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]
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]
557 fn test_missing_sbt_binary_error() {
558 let tmp = TempDir::new().unwrap();
559 let original_path = std::env::var_os("PATH");
560
561 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]
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]
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]
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]
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]
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]
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}