1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::fs::File;
use std::io::prelude::*;
use crate::error::CoreResult;
use std::ffi::{OsStr};
use crate::imp::json_to_rust::{json_root_to_rust, json_item_str_to_rust};
use crate::{HashM, HashMt};
use crate::imp::json_to_rust::construct_root::construct_root;
use crate::imp::structs::root_obj::RootObject;
use crate::imp::structs::json_file::{JsonFile, JsonFileImpl};
use crate::imp::structs::root_value::RootValue;
use std::path::Path;
pub fn json_dir_to_rust<P : AsRef<Path>>(dir_path : P, validation : bool) -> CoreResult<RootObject>{
let dirs = std::fs::read_dir(dir_path)?;
let mut vec : Vec<JsonFileImpl> = vec![];
for dir in dirs{
match dir{
Ok(de) =>{
let path = de.path();
if path.extension() == Some(&OsStr::new("json5")){
let oss: &OsStr = path.file_stem().ok_or_else(|| format!("file stem couldn't be read {:?}", &de))?;
let file_stem_ref = oss.to_str().ok_or_else(|| format!("os_string couldn't be converted to a rust string {:?}", oss))?;
let file_stem = file_stem_ref.to_string();
let mut file = match File::open(de.path()) {
Ok(f) => f,
Err(_e) => { continue; }
};
let mut buf = String::new();
match file.read_to_string(&mut buf) {
Ok(_) => vec.push(JsonFileImpl { json: buf, file_name_without_ext: file_stem }),
Err(e) => { Err(format!("{} couldn't be read", e))?; }
};
}
},
Err(_e) =>{
}
}
}
json_files_to_rust(vec.iter(), validation)
}
pub fn json_files_to_rust<T : JsonFile>(ite : impl Iterator<Item = T>, validation : bool) -> CoreResult<RootObject>{
let mut map : HashM<String, RootValue> = HashMt::new();
let mut root= None;
for file in ite{
let name = file.file_name_without_ext();
if name == "root"{
if root.is_none() {
root = Some(json_root_to_rust(file.json())?);
} else{
Err("There's two 'root.json5's in the directory")?
}
} else{
match json_item_str_to_rust(file.json(), name){
Ok(val) =>{ map.insert(name.to_string(), val.into_root_value2(name)?); }
Err(e) =>{ Err(format!("filename {}, {}", name, e.to_string()))? }
}
}
}
if root.is_none(){
Err("root.json5 is needed")?
}
return construct_root(root.unwrap(), map, validation);
}