From 61b3a3d3a035b6bf44c36061507fa6c927aa45ed Mon Sep 17 00:00:00 2001 From: THE-SIMPLE-MARK <57036815+THE-SIMPLE-MARK@users.noreply.github.com> Date: Sun, 10 Sep 2023 09:54:09 +0200 Subject: [PATCH] Add rustfmt.toml fix inheritance issues, fix indentation issues --- Cargo.lock | 23 +++ Cargo.toml | 2 +- rustfmt.toml | 3 + src/convert_section.rs | 260 ++++++++++++++------------- src/convert_section/search_folder.rs | 26 +-- src/main.rs | 70 ++++---- 6 files changed, 213 insertions(+), 171 deletions(-) create mode 100644 rustfmt.toml diff --git a/Cargo.lock b/Cargo.lock index 97aef87..d290214 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9,6 +9,28 @@ dependencies = [ "serde_json", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" + +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "itoa" version = "1.0.9" @@ -65,6 +87,7 @@ version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360" dependencies = [ + "indexmap", "itoa", "ryu", "serde", diff --git a/Cargo.toml b/Cargo.toml index 59fb5de..6bc399e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -serde_json = "1.0.1" +serde_json = { version = "1.0.1", features = ["preserve_order"] } diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..18e12f6 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +hard_tabs=true +tab_spaces=2 +wrap_comments=true \ No newline at end of file diff --git a/src/convert_section.rs b/src/convert_section.rs index 1409a44..82b073f 100644 --- a/src/convert_section.rs +++ b/src/convert_section.rs @@ -8,133 +8,149 @@ use std::path::Path; mod search_folder; use search_folder::search_folder; +#[derive(Debug)] pub enum SectionDataValue { - Single(Value), - Array(Vec), + Single(Value), + Array(Vec), } type SectionDataMap = HashMap; pub fn convert_section<'a>( - obj: Map, - start_dir: &Path, - is_recursive: bool, - upstream_section_data: &mut SectionDataMap, + obj: Map, + start_dir: &Path, + is_recursive: bool, + upstream_section_data: &mut SectionDataMap, ) -> Result { - let mut section_data: HashMap = HashMap::new(); - let mut section_title = String::new(); - - // check if the section inherits from any other files - if obj.contains_key("inherits") { - let inherits = &Value::to_string(obj.get("inherits").unwrap()); - - // search for that file - let inherits_file = search_folder( - start_dir, - format!("{:?}.json", inherits) - .replace("\\", "") - .replace("\"", "") - .as_str(), - ); - println!("File inherited: {:?}", inherits_file); - - // read JSON file - let mut json_file = File::open(inherits_file.unwrap())?; - let mut json_content = String::new(); - json_file - .read_to_string(&mut json_content) - .expect("TODO: panic message"); - - // parse JSON - let json_value: Value = serde_json::from_str(&json_content)?; - let Value::Object(json_obj) = json_value else { todo!() }; - - // convert JSON object to INI-like content - let Ok(_) = convert_section(json_obj, start_dir, true, &mut section_data) else { todo!() }; - } - - // iterate through the JSON object and add the section data to section_data - for (key, value) in &obj { - if key == "type" { - section_title = value.to_string(); - } - - match value { - // handle arrays - Value::Array(child_array) => { - // if we are in recursive mode we want to merge the data to the parent function - if is_recursive { - upstream_section_data - .entry(key.clone()) - .or_insert(SectionDataValue::Array(child_array.clone())) - } else { - section_data - .entry(key.clone()) - .or_insert(SectionDataValue::Array(child_array.clone())) - } - } - - // handle other types (numbers, strings, etc.) - _ => { - if is_recursive { - upstream_section_data - .entry(key.clone()) - .or_insert(SectionDataValue::Single(value.clone())) - } else { - section_data - .entry(key.clone()) - .or_insert(SectionDataValue::Single(value.clone())) - } - } - }; - } - - let mut ini = String::new(); - if !is_recursive { - if !section_title.is_empty() { - ini.push_str(format!("[{}]\n", section_title).replace("\"", "").as_str()); - } - - for (key, value) in section_data { - match value { - // handle arrays - SectionDataValue::Single(Value::Array(child_array)) => { - ini.push_str(&format!("{} = ", key)); // sdd space after = - for (i, item) in child_array.iter().enumerate() { - let item_str = match item { - Value::Number(num) => num.to_string(), - Value::String(str_val) => { - if str_val.contains(";") { - format!("\"{}\"", str_val) - } else { - str_val.clone() - } - } - _ => item.to_string(), - }; - ini.push_str(&item_str); - if i < child_array.len() - 1 { - ini.push(','); - } - } - ini.push('\n'); - } - - // handle other types (numbers, strings, etc.) - SectionDataValue::Single(value) => { - let value_str = &Value::to_string(&value); - let value_str = value_str.trim_matches('"'); // remove double quotes from numbers - if value_str.contains(";") { - ini.push_str(&format!("{} = \"{}\"\n", key, value_str)); // add space after = and enclose in double quotes - } else { - ini.push_str(&format!("{} = {}\n", key, value_str)); // add space after = - } - } - - _ => (), - } - } - } - - Ok(ini) + let mut section_data: HashMap = HashMap::new(); + let mut section_title = String::new(); + + // check if the section inherits from any other files + if obj.contains_key("inherits") { + let inherits = &Value::to_string(obj.get("inherits").unwrap()); + + // search for that file + let inherits_file = search_folder( + start_dir, + format!("{:?}.json", inherits) + .replace("\\", "") + .replace("\"", "") + .as_str(), + ); + + if inherits_file != None { + println!("File inherited: {:?}", inherits_file); + + // add to section_data so it doesn't get overwritten + section_data + .entry("inherits".parse().unwrap()) + .or_insert_with(|| SectionDataValue::Single(inherits.parse().unwrap())); + + // read JSON file + let mut json_file = File::open(inherits_file.unwrap())?; + let mut json_content = String::new(); + json_file + .read_to_string(&mut json_content) + .expect("TODO: panic message"); + + // parse JSON + let json_value: Value = serde_json::from_str(&json_content)?; + let Value::Object(json_obj) = json_value else { todo!() }; + + // convert JSON object to INI-like content + let Ok(_) = convert_section(json_obj, start_dir, true, if is_recursive { upstream_section_data } else { &mut section_data }) else { todo!() }; + + println!("Successfully converted recursive data!"); + } else { + eprintln!("ERROR: Could not find file to be inherited: {:?}", inherits); + } + } + + // iterate through the JSON object and add the section data to section_data + for (key, value) in &obj { + if key == "type" { + section_title = value.to_string(); + } + + match value { + // handle arrays + Value::Array(child_array) => { + // if we are in recursive mode we want to merge the data to the parent function + if is_recursive { + upstream_section_data + .entry(key.clone()) + .or_insert_with(|| SectionDataValue::Array(child_array.clone())) + } else { + section_data + .entry(key.clone()) + .or_insert_with(|| SectionDataValue::Array(child_array.clone())) + } + } + + // handle other types (numbers, strings, etc.) + _ => { + if is_recursive { + upstream_section_data + .entry(key.clone()) + .or_insert_with(|| SectionDataValue::Single(value.clone())) + } else { + section_data + .entry(key.clone()) + .or_insert_with(|| SectionDataValue::Single(value.clone())) + } + } + }; + } + + let mut ini = String::new(); + if !is_recursive { + if !section_title.is_empty() { + ini.push_str(format!("[{}]\n", section_title).replace("\"", "").as_str()); + } + + for (key, value) in §ion_data { + println!("Key: {:?} Value: {:?}", key, value) + } + + for (key, value) in section_data { + match value { + // handle arrays + SectionDataValue::Array(child_array) => { + ini.push_str(&format!("{} = ", key)); // sdd space after = + for (i, item) in child_array.iter().enumerate() { + let item_str = match item { + Value::Number(num) => num.to_string(), + Value::String(str_val) => { + if str_val.contains(";") { + format!("\"{}\"", str_val) + } else { + str_val.clone() + } + } + _ => item.to_string(), + }; + ini.push_str(&item_str); + if i < child_array.len() - 1 { + ini.push(','); + } + } + ini.push('\n'); + } + + // handle other types (numbers, strings, etc.) + SectionDataValue::Single(value) => { + let value_str = &Value::to_string(&value); + let value_str = value_str.trim_matches('"'); // remove double quotes from numbers + if value_str.contains(";") { + ini.push_str(&format!("{} = \"{}\"\n", key, value_str)); + // add space after = and enclose in double quotes + } else { + ini.push_str(&format!("{} = {}\n", key, value_str)); // add space after = + } + } + } + } + } + + Ok(ini) } diff --git a/src/convert_section/search_folder.rs b/src/convert_section/search_folder.rs index 133cc3d..bcef931 100644 --- a/src/convert_section/search_folder.rs +++ b/src/convert_section/search_folder.rs @@ -3,19 +3,19 @@ use std::fs; use std::path::Path; pub fn search_folder<'a>(start_dir: &Path, target_file_name: &str) -> Option { - if let Ok(entries) = fs::read_dir(start_dir) { - for entry in entries.flatten() { - let entry_path = entry.path(); + if let Ok(entries) = fs::read_dir(start_dir) { + for entry in entries.flatten() { + let entry_path = entry.path(); - if entry_path.is_dir() { - if let Some(result) = search_folder(&entry_path, target_file_name) { - return Some(result); - } - } else if entry_path.file_name() == Option::from(OsStr::new(target_file_name)) { - return Some(entry_path.into_os_string()); - } - } - } + if entry_path.is_dir() { + if let Some(result) = search_folder(&entry_path, target_file_name) { + return Some(result); + } + } else if entry_path.file_name() == Option::from(OsStr::new(target_file_name)) { + return Some(entry_path.into_os_string()); + } + } + } - None + None } diff --git a/src/main.rs b/src/main.rs index 714638d..dd15f2e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,39 +10,39 @@ use std::io::{Read, Write}; use std::path::Path; fn main() -> Result<(), Box> { - // check for arguments - let args: Vec = env::args().collect(); - if args.len() != 3 { - eprintln!( - "Usage: {} ", - args[0] - ); - std::process::exit(1); - } - - // extract the input JSON file path from the command-line arguments - let input_json_path = &args[1]; - let inheritance_files_path = Path::new(&args[2]); - - // read JSON file - let mut json_file = File::open(input_json_path)?; - let mut json_content = String::new(); - json_file.read_to_string(&mut json_content)?; - - // parse JSON - let json_value: Value = serde_json::from_str(&json_content)?; - let Value::Object(json_obj) = json_value else { todo!() }; - let mut unused_data = HashMap::new(); - - // convert JSON object to INI-like content - let Ok(ini_content) = convert_section(json_obj, inheritance_files_path, false, &mut unused_data) else { todo!() }; - - let mut file = File::create("output.ini")?; - file - .write_all(ini_content.as_bytes()) - .expect("TODO: panic message"); - - println!("Conversion successful!"); - - Ok(()) + // check for arguments + let args: Vec = env::args().collect(); + if args.len() != 3 { + eprintln!( + "Usage: {} ", + args[0] + ); + std::process::exit(1); + } + + // extract the input JSON file path from the command-line arguments + let input_json_path = &args[1]; + let inheritance_files_path = Path::new(&args[2]); + + // read JSON file + let mut json_file = File::open(input_json_path)?; + let mut json_content = String::new(); + json_file.read_to_string(&mut json_content)?; + + // parse JSON + let json_value: Value = serde_json::from_str(&json_content)?; + let Value::Object(json_obj) = json_value else { todo!() }; + let mut unused_data = HashMap::new(); + + // convert JSON object to INI-like content + let Ok(ini_content) = convert_section(json_obj, inheritance_files_path, false, &mut unused_data) else { todo!() }; + + let mut file = File::create("output.ini")?; + file + .write_all(ini_content.as_bytes()) + .expect("TODO: panic message"); + + println!("Conversion successful!"); + + Ok(()) }