use super::super::path_vocab::canonical_segment;
use std::path::Path;
pub(super) fn module_path_of(relative: &Path, root_relative: Option<&Path>) -> String {
if root_relative == Some(relative) {
return "crate".to_string();
}
let custom_root = root_relative.is_some_and(|r| !is_conventional_root(r));
file_module_path(relative, custom_root)
}
fn is_conventional_root(relative: &Path) -> bool {
relative
.file_name()
.is_some_and(|n| matches!(n.to_string_lossy().as_ref(), "lib.rs" | "main.rs"))
&& relative.components().count() == 1
}
fn file_module_path(relative: &Path, custom_root: bool) -> String {
let components: Vec<String> = relative
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect();
let mut segments = vec![String::from("crate")];
let last = components.len().saturating_sub(1);
for (index, component) in components.iter().enumerate() {
if index == last {
let stem = component.strip_suffix(".rs").unwrap_or(component);
let segmentless = stem == "mod"
|| (!custom_root && components.len() == 1 && matches!(stem, "lib" | "main"));
if !segmentless {
segments.push(canonical_segment(stem).to_string());
}
} else {
segments.push(canonical_segment(component).to_string());
}
}
segments.join("::")
}