next_web_dev/util/
file_util.rs

1use std::{
2    error::Error,
3    fmt::Debug,
4    fs::File,
5    io::{BufReader, Read},
6    path::Path,
7};
8
9use hashbrown::HashMap;
10use regex::Regex;
11use serde::de::DeserializeOwned;
12
13/**
14*struct:    FileUtil
15*desc:      文件操作工具类
16*author:    Listening
17*email:     yuenxillar@163.com
18*date:      2024/10/02
19*/
20
21pub struct FileUtil;
22
23impl FileUtil {
24    pub fn read_file(path: &str) -> Result<Vec<u8>, Box<dyn Error>> {
25        let file = File::open(Path::new(path))?;
26        let mut reader = BufReader::new(file);
27        let mut buf = Vec::new();
28        reader.read_to_end(&mut buf).unwrap();
29        Ok(buf)
30    }
31
32    // 判断文件是否存在
33    pub fn is_file_exist(path: &str) -> bool {
34        Path::new(path).exists()
35    }
36
37    #[inline]
38    pub fn read_file_to_string(path: &str) -> Result<String, Box<dyn Error>> {
39        let file = File::open(Path::new(path))?;
40        let mut reader = BufReader::new(file);
41        let mut buf = String::new();
42        reader.read_to_string(&mut buf).unwrap();
43        Ok(buf)
44    }
45
46    pub fn read_file_into_application<T: DeserializeOwned + Debug>(
47        file_path: &str,
48    ) -> (T, HashMap<String, serde_yaml::Value>) {
49        use serde_yaml::Value;
50
51        println!("read application file: {}", file_path);
52        match std::fs::metadata(file_path) {
53            Ok(_) => (),
54            Err(_error) => panic!("The application config file is not exits!!"),
55        }
56        let mut file = File::open(file_path).expect("application file open is _error!!");
57        let mut str = String::new();
58        let _ = file.read_to_string(&mut str).unwrap();
59
60        // replace var
61        let replace_var = |content: &str| -> String {
62            let re = Regex::new(r"\$\{server_ip\}").unwrap();
63
64            // 替换 ${server_ip} 为新的 IP 地址
65            let updated_content = re.replace_all(&content, "192.168.1.130");
66            updated_content.to_string()
67        };
68
69        let buf = replace_var(str.as_str());
70
71        // mapping value
72        let docs = serde_yaml::from_str::<Value>(&buf).unwrap();
73        let mut data_map: HashMap<String, Value> = HashMap::new();
74
75        // Prepare a recursive function to fill in
76        fn populate_map(prefix: String, value: &Value, map: &mut HashMap<String, Value>) {
77            match value {
78                Value::Mapping(mapping) => {
79                    for (k, v) in mapping {
80                        if let Some(key) = k.as_str() {
81                            populate_map(
82                                format!(
83                                    "{}{}",
84                                    if prefix.is_empty() {
85                                        String::new()
86                                    } else {
87                                        format!("{}.", prefix)
88                                    },
89                                    key
90                                ),
91                                v,
92                                map,
93                            );
94                        }
95                    }
96                }
97                _ => {
98                    map.insert(prefix, value.clone());
99                }
100            }
101        }
102
103        // Fill in the map
104        populate_map(String::new(), &docs, &mut data_map);
105
106        // into application
107        let application: T = serde_yaml::from_str(buf.as_str()).unwrap();
108
109        // return
110        return (application, data_map);
111    }
112}