Refactor path handling in sourcemap processing

- Canonicalized project directory once for consistent comparison, improving the logic for generating relative paths.
- Enhanced fallback mechanism for absolute paths when files are outside the project directory, increasing robustness in path management.
This commit is contained in:
Joe 2026-01-23 04:36:30 -06:00
parent 4a6fdaa02d
commit 7c6c4a0e85

View file

@ -20,7 +20,6 @@ use crate::{
use super::resolve_path; use super::resolve_path;
const PATH_STRIP_FAILED_ERR: &str = "Failed to create relative paths for project file!";
const ABSOLUTE_PATH_FAILED_ERR: &str = "Failed to turn relative path into absolute path!"; const ABSOLUTE_PATH_FAILED_ERR: &str = "Failed to turn relative path into absolute path!";
/// Representation of a node in the generated sourcemap tree. /// Representation of a node in the generated sourcemap tree.
@ -198,24 +197,29 @@ fn recurse_create_node<'a>(
let mut output_file_paths: Vec<Cow<'a, Path>> = let mut output_file_paths: Vec<Cow<'a, Path>> =
Vec::with_capacity(instance.metadata().relevant_paths.len()); Vec::with_capacity(instance.metadata().relevant_paths.len());
if use_absolute_paths { // Canonicalize project_dir once for consistent comparison
// It's somewhat important to note here that `path::absolute` takes in a Path and returns a PathBuf let canonical_project_dir = std::fs::canonicalize(project_dir).ok();
for val in file_paths {
output_file_paths.push(Cow::Owned( for val in file_paths {
path::absolute(val).expect(ABSOLUTE_PATH_FAILED_ERR), if use_absolute_paths {
)); let abs_path = path::absolute(val).expect(ABSOLUTE_PATH_FAILED_ERR);
} output_file_paths.push(Cow::Owned(abs_path));
} else { } else if let Some(ref proj_dir) = canonical_project_dir {
for val in file_paths { // Canonicalize file path and strip project dir prefix to get relative path
// Try to create relative path, fall back to absolute if path is outside project dir if let Ok(canonical_file) = std::fs::canonicalize(val) {
match val.strip_prefix(project_dir) { if let Ok(relative) = canonical_file.strip_prefix(proj_dir) {
Ok(relative) => output_file_paths.push(Cow::from(relative)), output_file_paths.push(Cow::Owned(relative.to_path_buf()));
Err(_) => output_file_paths.push(Cow::Owned( continue;
path::absolute(val).expect(ABSOLUTE_PATH_FAILED_ERR), }
)),
} }
// Fallback: file is outside project dir
let abs_path = path::absolute(val).expect(ABSOLUTE_PATH_FAILED_ERR);
output_file_paths.push(Cow::Owned(abs_path));
} else {
let abs_path = path::absolute(val).expect(ABSOLUTE_PATH_FAILED_ERR);
output_file_paths.push(Cow::Owned(abs_path));
} }
}; }
Some(SourcemapNode { Some(SourcemapNode {
name: instance.name(), name: instance.name(),