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