1use std::{
3 fs::{self, File},
4 io::{BufReader, Read},
5};
6
7use super::{
8 api::NetworkConfigList,
9 types::{NetConf, NetworkConfig},
10};
11
12pub struct ConfigFile {}
13
14impl ConfigFile {
15 pub fn config_files(dir: String, extensions: Vec<String>) -> Result<Vec<String>, String> {
16 let mut conf_files = Vec::default();
17 let dir = fs::read_dir(dir).unwrap();
18
19 for entry in dir {
20 match entry {
21 Ok(file) => {
22 let file_path = file.path();
23 let file_ext = file_path.extension().unwrap();
24 if extensions.contains(&file_ext.to_string_lossy().to_string()) {
25 conf_files.push(file.path().to_string_lossy().to_string());
26 }
27 }
28 Err(e) => {
29 println!("{:?}", e);
30 }
31 }
32 }
33 Ok(conf_files)
34 }
35
36 pub fn config_from_bytes(datas: &[u8]) -> Result<NetworkConfigList, String> {
37 let ncmaps: serde_json::Value = serde_json::from_slice(datas).unwrap();
38 let name = ncmaps.get("name").unwrap().as_str().unwrap().to_string();
39 let version = ncmaps
40 .get("cniVersion")
41 .unwrap()
42 .as_str()
43 .unwrap()
44 .to_string();
45 let mut disabel_check = false;
46 if let Some(check) = ncmaps.get("disableCheck") {
47 disabel_check = check.as_bool().unwrap();
48 }
49
50 let mut ncflist = NetworkConfigList::default();
51 let mut all_plugins = Vec::new();
52 if let Some(plugins) = ncmaps.get("plugins") {
53 let plugins_arr = plugins.as_array().unwrap();
54 for plugin in plugins_arr {
55 let string_plugin = plugin.to_string();
56 let plg_bytes = string_plugin.as_bytes().to_vec();
57 let tmp: NetConf = serde_json::from_str(&string_plugin).unwrap();
58 all_plugins.push(NetworkConfig {
59 network: tmp,
60 bytes: plg_bytes,
61 })
62 }
63 }
64
65 ncflist.name = name;
66 ncflist.cni_version = version;
67 ncflist.bytes = datas.to_vec();
68 ncflist.disable_check = disabel_check;
69 ncflist.plugins = all_plugins;
70 Ok(ncflist)
71 }
72
73 pub fn read_configlist_file(file_path: String) -> Option<NetworkConfigList> {
74 let file = File::open(file_path).unwrap();
75 let mut file_bytes = Vec::default();
76 let mut reader = BufReader::new(file);
77 let _ = reader.read_to_end(&mut file_bytes);
78
79 let ncflist = Self::config_from_bytes(&file_bytes).unwrap();
80 Some(ncflist)
81 }
82}