new_home_core/util/
script_preprocessor.rs

1use regex::{Captures, Regex};
2
3pub struct ScriptVariables {
4    pub app: String,
5    pub framework: String,
6}
7
8pub struct ScriptPreprocessor {
9    script: String
10}
11
12impl ScriptPreprocessor {
13    pub fn new(script: String) -> Self {
14        Self { script }
15    }
16
17    pub fn process(&self, variables: ScriptVariables) -> String {
18        let script_copy = self.script.clone();
19        let regex = Regex::new(r#"import (.* from)? ?['"]@(framework|app)(.*)['"];"#).unwrap();
20
21        String::from(regex.replace_all(script_copy.as_str(), |captures: &Captures| {
22            let variable_name = captures.get(2).unwrap().as_str();
23            let root_url = match variable_name {
24                "framework" => variables.framework.clone(),
25                "app" => variables.app.clone(),
26                _ => String::new()
27            };
28
29            let script_url = String::from(captures.get(3).unwrap().as_str().clone());
30            let from = match captures.get(1) {
31                None => String::new(),
32                Some(from) => String::from(from.as_str())
33            };
34
35            return format!("import {}'{}/{}'",
36                           &from,
37                           &root_url.trim_end_matches('/'),
38                           &script_url.trim_start_matches('/')
39            );
40        }))
41    }
42}