use crate::{LibraryLayout, ModulePath, Placement, Segments, Tree};
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum BundleError {
Shape(String),
NotLocal(String),
Segment(String),
Twice(String),
NoEntryModule(String),
}
impl std::fmt::Display for BundleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BundleError::Shape(what) => write!(f, "the bundle is malformed: {what}"),
BundleError::NotLocal(path) => {
write!(f, "the module {path} is not in the bundle's own tree")
}
BundleError::Segment(segment) => {
write!(f, "`{segment}` is not a segment of a module path")
}
BundleError::Twice(file) => write!(f, "two modules of the bundle are the file {file}"),
BundleError::NoEntryModule(path) => {
write!(f, "the entry's module {path} is not in the bundle")
}
}
}
}
impl std::error::Error for BundleError {}
pub fn bundled_file(
library: Option<&str>,
segments: &[String],
) -> Result<(String, Option<String>), BundleError> {
let inside =
Segments::from_names(segments).ok_or_else(|| BundleError::Segment(segments.join("/")))?;
if let Some(segment) = inside.names().find(|segment| unsafe_name(segment)) {
return Err(BundleError::Segment(segment.to_owned()));
}
let library = match library {
None if inside.is_root() => {
return Err(BundleError::Shape(
"a module outside every library has no segments".to_owned(),
));
}
None => None,
Some(".") => Some(Segments::root()),
Some(other) => {
let root: Segments = other
.parse()
.map_err(|_| BundleError::Segment(other.to_owned()))?;
if root.names().any(unsafe_name) {
return Err(BundleError::Segment(other.to_owned()));
}
Some(root)
}
};
let module = ModulePath::new(Tree::Local, library, inside);
let file = LibraryLayout::file(module.file(Placement::Contract).as_str());
Ok((file, module.library().map(ToString::to_string)))
}
fn unsafe_name(name: &str) -> bool {
matches!(name, "." | "..") || name.contains('\\')
}