rush_ecs_parser/
loader.rs

1use super::adapter::Parser;
2use crate::utils::{dir_to_string, file_to_string};
3use anyhow::Result;
4use rush_ecs_core::blueprint::Blueprint;
5use std::{
6    fs::{canonicalize, metadata},
7    path::Path,
8};
9
10/// [`Blueprint`] Loader
11///
12/// Load [`Blueprint`] from file or directory
13///
14pub struct Loader {
15    parser: Box<dyn Parser>,
16}
17
18impl Loader {
19    /// Create a new [`Blueprint`] [`Loader`]
20    pub fn new(parser: impl Parser) -> Self {
21        Self {
22            parser: Box::new(parser),
23        }
24    }
25
26    /// Load Blueprint
27    ///
28    /// Loads [`Blueprint`] from a specific [`Path`]
29    ///
30    /// [`Path`] can be a **file** or **directory**;
31    pub fn load_blueprint(&self, path: &Path) -> Result<Blueprint> {
32        // expecting a valid path
33        let abs_path = canonicalize(path)?;
34        let md = metadata(abs_path).expect("invalid path");
35
36        // get blueprint string from file or directory
37        let blueprint_string = match md.is_dir() {
38            true => dir_to_string(path),
39            false => file_to_string(path),
40        };
41
42        self.parser.parse_string(blueprint_string)
43    }
44}