1use anyhow::Context;
2use glob::glob;
3use std::{fs::File, io::Read, path::PathBuf};
4
5use orion_error::{ContextRecord, ErrorOwe, ErrorWith, OperationContext};
6use wp_log::info_ctrl;
7
8use crate::{WplCode, parser::error::WplCodeResult, types::AnyResult};
9
10pub fn fetch_wpl_data(path: &str, target: &str) -> WplCodeResult<Vec<WplCode>> {
11 let mut wpl_vec = Vec::new();
12 let mut ctx = OperationContext::want("load wpl");
13 ctx.record("path", path);
14 let files = find_conf_files(path, target).owe_conf().with(&ctx)?;
15
16 for f_name in &files {
17 info_ctrl!("load conf file: {:?}", f_name);
18 let mut f = File::open(f_name).owe_conf().with(&ctx)?;
19 let mut buffer = Vec::with_capacity(10240);
20 f.read_to_end(&mut buffer).owe_conf().with(&ctx)?;
21 let file_data = String::from_utf8(buffer).owe_conf().with(&ctx)?;
22 wpl_vec.push(WplCode::try_from((PathBuf::from(f_name), file_data))?)
23 }
24 Ok(wpl_vec)
25}
26fn find_conf_files(path: &str, target: &str) -> AnyResult<Vec<PathBuf>> {
27 let mut found = Vec::new();
28 info_ctrl!("find conf files in: {}", path);
29 let glob_path = format!("{}/**/{}", path, target);
30 for entry in glob(glob_path.as_str()).with_context(|| format!("read_dir fail: {}", path))? {
31 match entry {
32 Ok(path) => {
33 found.push(path);
34 }
35 Err(e) => {
36 error!("find_conf files fail: {}", e);
37 }
38 }
39 }
40 Ok(found)
41}