use std::path::{Path, PathBuf};
use super::walk::SOURCE_EXTENSIONS;
const RUNNABLE_EXTENSIONS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
pub fn probe_source_file(resolved: &Path) -> Option<PathBuf> {
if resolved.is_file() {
return Some(resolved.to_path_buf());
}
SOURCE_EXTENSIONS
.iter()
.map(|ext| resolved.with_extension(ext))
.find(|candidate| candidate.is_file())
}
pub fn probe_runnable_file(resolved: &Path) -> Option<PathBuf> {
if resolved.is_file() {
return Some(resolved.to_path_buf());
}
let has_runnable_extension = resolved
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| RUNNABLE_EXTENSIONS.contains(&ext));
RUNNABLE_EXTENSIONS
.iter()
.map(|ext| {
if has_runnable_extension {
return resolved.with_extension(ext);
}
let mut name = resolved.as_os_str().to_os_string();
name.push(".");
name.push(ext);
PathBuf::from(name)
})
.find(|candidate| candidate.is_file())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn package_entries_replace_any_extension_and_commands_only_runnable_ones() {
let dir = tempfile::tempdir().expect("create temp dir");
let lib = dir.path().join("lib");
std::fs::create_dir_all(&lib).expect("lib");
for file in ["index.ts", "theme.css"] {
std::fs::write(lib.join(file), "").expect("write");
}
assert_eq!(
probe_source_file(&lib.join("index.json")),
Some(lib.join("index.ts"))
);
assert_eq!(probe_runnable_file(&lib.join("index.json")), None);
assert_eq!(probe_runnable_file(&lib.join("theme")), None);
assert_eq!(
probe_runnable_file(&lib.join("index")),
Some(lib.join("index.ts"))
);
}
}