use sephera_core::path_utils as paths;
#[must_use]
pub fn module_path(source_file: &str) -> String {
if let Some(stripped) = source_file.strip_suffix("/mod.rs") {
return stripped.to_owned();
}
paths::strip_suffix_owned(source_file, ".rs")
}
#[must_use]
pub fn crate_root(source_file: &str) -> String {
paths::through_last_segment(source_file, "src")
}
#[must_use]
pub fn module_children_dir(source_file: &str) -> String {
if is_target_crate_root(source_file) {
paths::parent(source_file)
} else {
module_path(source_file)
}
}
#[must_use]
pub fn is_target_crate_root(source_file: &str) -> bool {
let stem = paths::file_stem(source_file);
let parent = paths::parent(source_file);
let directory = paths::file_name(&parent);
if matches!(stem, "main" | "lib" | "mod") && directory == "src" {
return true;
}
matches!(
directory,
"tests" | "benches" | "examples" | "src/bin" | "bin"
)
}
#[must_use]
pub fn qualify(base: &str, rest: &str) -> String {
paths::join(base, &[&paths::replace_separator(rest, ':')])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_module_spellings_map_to_one_path() {
assert_eq!(module_path("src/core/graph.rs"), "src/core/graph");
assert_eq!(module_path("src/core/graph/mod.rs"), "src/core/graph");
}
#[test]
fn a_crate_root_is_a_directory() {
assert_eq!(crate_root("src/core/graph.rs"), "src");
assert_eq!(crate_root("tests/helper.rs"), "");
}
#[test]
fn submodules_sit_beside_a_crate_root_and_in_a_directory_otherwise() {
assert_eq!(module_children_dir("src/main.rs"), "src");
assert_eq!(module_children_dir("src/core/graph.rs"), "src/core/graph");
assert_eq!(module_children_dir("tests/support_a.rs"), "tests");
}
#[test]
fn a_mod_deeper_in_the_tree_is_not_a_crate_root() {
assert!(!is_target_crate_root("src/core/graph/mod.rs"));
assert!(is_target_crate_root("src/lib.rs"));
}
}