Skip to main content

wpl/
util.rs

1use glob::glob;
2use std::{fs::File, io::Read, path::PathBuf};
3
4use orion_error::OperationContext;
5use orion_error::conversion::{ErrorWith, SourceErr, SourceRawErr};
6use wp_log::info_ctrl;
7
8use crate::WplCode;
9use crate::parser::error::WplCodeResult;
10use crate::parser::error::{WplCodeError, WplCodeReason};
11
12pub fn fetch_wpl_data(path: &str, target: &str) -> WplCodeResult<Vec<WplCode>> {
13    let mut wpl_vec = Vec::new();
14    let mut ctx = OperationContext::doing("load wpl");
15    ctx.record("path", path);
16    let files = find_conf_files(path, target).with_context(&ctx)?;
17
18    for f_name in &files {
19        info_ctrl!("load conf file: {:?}", f_name);
20        let mut f = File::open(f_name)
21            .source_err(WplCodeReason::core_conf(), "open file")
22            .with_context(&ctx)?;
23        let mut buffer = Vec::with_capacity(10240);
24        f.read_to_end(&mut buffer)
25            .source_err(WplCodeReason::core_conf(), "read file")
26            .with_context(&ctx)?;
27        let file_data = String::from_utf8(buffer)
28            .source_raw_err(WplCodeReason::core_conf(), "utf8 decode")
29            .with_context(&ctx)?;
30        wpl_vec.push(WplCode::try_from((PathBuf::from(f_name), file_data))?)
31    }
32    Ok(wpl_vec)
33}
34fn find_conf_files(path: &str, target: &str) -> WplCodeResult<Vec<PathBuf>> {
35    let mut found = Vec::new();
36    info_ctrl!("find conf files in: {}", path);
37    let glob_path = format!("{}/**/{}", path, target);
38    for entry in glob(glob_path.as_str()).map_err(|e| {
39        let msg = format!("read_dir fail: {}, {}", path, e);
40        WplCodeError::builder(WplCodeReason::Syntax)
41            .detail(msg)
42            .finish()
43    })? {
44        match entry {
45            Ok(path) => {
46                found.push(path);
47            }
48            Err(e) => {
49                error!("find_conf files fail: {}", e);
50            }
51        }
52    }
53    Ok(found)
54}