Skip to main content

flow_types/
bundle.rs

1//! A `code.Bundle`'s files (`code.md`, *Checked bundles*): the file each
2//! of its modules is at in the tree the bundle holds, which forming the
3//! bundle reads and every diagnostic about it names.
4
5use crate::{LibraryLayout, ModulePath, Placement, Segments, Tree};
6
7/// Why a `code.Bundle` is no bundle of files.
8#[derive(Clone, PartialEq, Eq, Debug)]
9pub enum BundleError {
10    /// The JSON is not a `code.Bundle`'s form: what was wrong.
11    Shape(String),
12    /// A module is not in the local tree, which is all a bundle holds.
13    NotLocal(String),
14    /// A segment of a module path would leave its directory.
15    Segment(String),
16    /// Two modules of the bundle are one file.
17    Twice(String),
18    /// The entry's module is not one of the bundle's files.
19    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
42/// The file, from a bundle's root, of the module of its local tree whose
43/// library is `library`, `"."` for the root, and whose path inside it is
44/// `segments`, and the directory of its library, `""` for the root, when it
45/// is in one. A module outside every library is `<segments>.flow` from the
46/// root; a library's module is its contract module
47/// `<library>/contract/<segments>.flow`, `contract/lib.flow` for its root
48/// module.
49///
50/// # Errors
51///
52/// [`BundleError`] when a segment would leave its directory, or a module
53/// outside every library has no segments.
54pub 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
86/// Whether `name`, a name of a path, steps out of its directory or holds a
87/// separator some host reads.
88fn unsafe_name(name: &str) -> bool {
89    matches!(name, "." | "..") || name.contains('\\')
90}