1use crate::{LibraryLayout, ModulePath, Placement, Segments, Tree};
6
7#[derive(Clone, PartialEq, Eq, Debug)]
9pub enum BundleError {
10 Shape(String),
12 NotLocal(String),
14 Segment(String),
16 Twice(String),
18 NoEntryModule(String),
20}
21
22impl std::fmt::Display for BundleError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 match self {
25 BundleError::Shape(what) => write!(f, "the bundle is malformed: {what}"),
26 BundleError::NotLocal(path) => {
27 write!(f, "the module {path} is not in the bundle's own tree")
28 }
29 BundleError::Segment(segment) => {
30 write!(f, "`{segment}` is not a segment of a module path")
31 }
32 BundleError::Twice(file) => write!(f, "two modules of the bundle are the file {file}"),
33 BundleError::NoEntryModule(path) => {
34 write!(f, "the entry's module {path} is not in the bundle")
35 }
36 }
37 }
38}
39
40impl std::error::Error for BundleError {}
41
42pub fn bundled_file(
55 library: Option<&str>,
56 segments: &[String],
57) -> Result<(String, Option<String>), BundleError> {
58 let inside =
59 Segments::from_names(segments).ok_or_else(|| BundleError::Segment(segments.join("/")))?;
60 if let Some(segment) = inside.names().find(|segment| unsafe_name(segment)) {
61 return Err(BundleError::Segment(segment.to_owned()));
62 }
63 let library = match library {
64 None if inside.is_root() => {
65 return Err(BundleError::Shape(
66 "a module outside every library has no segments".to_owned(),
67 ));
68 }
69 None => None,
70 Some(".") => Some(Segments::root()),
71 Some(other) => {
72 let root: Segments = other
73 .parse()
74 .map_err(|_| BundleError::Segment(other.to_owned()))?;
75 if root.names().any(unsafe_name) {
76 return Err(BundleError::Segment(other.to_owned()));
77 }
78 Some(root)
79 }
80 };
81 let module = ModulePath::new(Tree::Local, library, inside);
82 let file = LibraryLayout::file(module.file(Placement::Contract).as_str());
83 Ok((file, module.library().map(ToString::to_string)))
84}
85
86fn unsafe_name(name: &str) -> bool {
89 matches!(name, "." | "..") || name.contains('\\')
90}