arc_isle/parser/
imports.rs

1use crate::parser::utils::{as_str_or, read_yaml, YamlHash};
2use crate::schema::ImportError;
3use std::fmt::{Debug, Display, Formatter};
4use yaml_rust::Yaml;
5
6#[derive(Debug)]
7pub struct SourceImport {
8    pub key: String,
9    pub imported_source: Yaml,
10}
11
12pub fn detect(
13    source: &YamlHash,
14    parent_path: &str,
15) -> Vec<Result<Yaml, ImportError>> {
16    let import_key = Yaml::String("_import".to_string());
17    let is_import = source.contains_key(&import_key);
18    if !is_import {
19        return Vec::new();
20    }
21    let mut found_imports = Vec::new();
22    match &source[&import_key] {
23        Yaml::String(file_path) => {
24            let file_path = parent_path.to_string() + "/" + &file_path;
25            match read_yaml(&file_path) {
26                Ok(imported_yaml) => {
27                    for e in imported_yaml {
28                        found_imports.push(Ok(e));
29                    }
30                }
31                Err(err) => found_imports.push(Err(ImportError::IOError(err))),
32            }
33        }
34        Yaml::Array(file_paths) => {
35            for file_path in file_paths {
36                match as_str_or(&file_path, ImportError::InvalidImportValue) {
37                    Ok(file_path) => {
38                        let file_path = parent_path.to_string() + "/" + &file_path;
39                        match read_yaml(&file_path) {
40                            Ok(imported_yaml) => {
41                                for e in imported_yaml {
42                                    found_imports.push(Ok(e));
43                                }
44                            }
45                            Err(err) => found_imports.push(Err(ImportError::IOError(err))),
46                        }
47                    }
48                    Err(err) => found_imports.push(Err(err)),
49                }
50            }
51        }
52        _ => found_imports.push(Err(ImportError::InvalidImportValue)),
53    }
54    found_imports
55}
56
57impl ImportError {
58    fn default_fmt(&self, f: &mut Formatter) -> std::fmt::Result {
59        match self {
60            ImportError::IOError(err) => {
61                write!(f, "I/O error while loading imports: {}", err.to_string())
62            }
63            ImportError::InvalidInputSource => write!(f, "Input source should be a hashmap"),
64            ImportError::InvalidImportValue => write!(f, "Import statement should be string"),
65        }
66    }
67}
68
69impl std::error::Error for ImportError {}
70
71impl Display for ImportError {
72    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
73        self.default_fmt(f)
74    }
75}
76
77impl Debug for ImportError {
78    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79        self.default_fmt(f)
80    }
81}