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