pipeline_script/preprocessor/
mod.rs1use regex::Regex;
2use std::fs::read_to_string;
3
4pub trait Preprocessor {
5 fn process(&mut self, script: &str) -> String;
6}
7#[derive(Default)]
8pub struct FormatStringPreprocessor;
9impl Preprocessor for FormatStringPreprocessor {
10 fn process(&mut self, script: &str) -> String {
11 let re = Regex::new(r#"f"(.*?)""#).unwrap();
12 let replace = re.replace_all(script, |cap: ®ex::Captures| {
13 let mat = cap.get(1).unwrap();
14 let s = mat.as_str();
15 let replace = s.replace("{", r#"","#).replace("}", r#",""#);
16 format!(r#"string("{replace}")"#)
17 });
18 replace.to_string()
19 }
20}
21#[derive(Default)]
22pub struct ImportPreprocessor;
23
24impl ImportPreprocessor {
25 fn helper(imports: &mut Vec<String>, script: impl AsRef<str>) -> (String, bool) {
26 let origin = script.as_ref();
27 let re = Regex::new(r"\bimport\b\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+").unwrap();
28 let replace = re.replace_all(origin, |cap: ®ex::Captures| {
29 let mat = cap.get(1).unwrap();
30 let s = mat.as_str().into();
31 if imports.contains(&s) {
32 return String::new();
33 }
34 imports.push(s.clone());
35 let s = read_to_string(format!("{s}.ppl")).unwrap();
36 format!("{s}\n")
37 });
38 (replace.to_string(), re.is_match(origin))
39 }
40}
41impl Preprocessor for ImportPreprocessor {
42 fn process(&mut self, script: &str) -> String {
43 let mut s = script.into();
44 let mut imports = vec![];
45 loop {
46 let (str, b) = Self::helper(&mut imports, s);
47 s = str;
48 if !b {
49 break;
50 }
51 }
52 s
57 }
58}