Skip to content

Commit

Permalink
Swap from YAML Clap CLI to derived struct Clap CLI (#161)
Browse files Browse the repository at this point in the history
* Update list of authors in Cargo.toml

* Switch from clap yaml to clap derive, and use PathBufs instead of &str for paths (its safer)

* Cargo fmt

* Cargo fmt

* Removed unnecessary func-call

* Added tests and did some formatting

---------

Co-authored-by: Thomas Lohse <thomas.k.lohse@gmail.com>
  • Loading branch information
seblund and t-lohse authored Aug 23, 2023
1 parent f2b6b70 commit 4b41c9d
Show file tree
Hide file tree
Showing 13 changed files with 284 additions and 160 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "reveaal"
version = "0.1.0"
build = "src/build.rs"
authors = ["Peter Greve <Pgreve16@student.aau.dk>"]
authors = ["Thomas Lohse", "Sebastian Lund", "Thorulf Neustrup", "Peter Greve"]
edition = "2018"

[lib]
Expand All @@ -20,14 +20,14 @@ logging = ["dep:env_logger", "dep:chrono"]
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
clap = { version = "~2.34.0", features = ["yaml"] }
clap = { version = "4.2.1", features = [ "derive" ] }
pest = "2.5.6"
pest_derive = "2.5.6"
xml-rs = "0.8.3"
serde-xml-rs = "0.6.0"
elementtree = "1.2.2"
dyn-clone = "1.0"
tonic = "0.8.2"
tonic = "0.8.3"
prost = "0.11.0"
tokio = { version = "1.0", features = ["macros", "rt"] }
colored = "2.0.0"
Expand Down
3 changes: 1 addition & 2 deletions benches/bench_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use reveaal::{ComponentLoader, JsonProjectLoader};
const UNI_PATH: &str = "samples/json/EcdarUniversity";

pub fn get_uni_loader() -> Box<dyn ComponentLoader + 'static> {
let mut loader =
JsonProjectLoader::new_loader(UNI_PATH.to_string(), TEST_SETTINGS).to_comp_loader();
let mut loader = JsonProjectLoader::new_loader(UNI_PATH, TEST_SETTINGS).to_comp_loader();
let _ = loader.get_component("Adm2");
let _ = loader.get_component("Administration");
let _ = loader.get_component("HalfAdm1");
Expand Down
27 changes: 18 additions & 9 deletions src/DataReader/component_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::ProtobufServer::services::query_request::Settings;
use crate::System::input_enabler;
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

pub type ComponentsMap = HashMap<String, Component>;
Expand Down Expand Up @@ -198,12 +199,12 @@ fn parse_xml_components(xml: &str) -> Vec<Component> {
pub trait ProjectLoader: ComponentLoader {
fn get_declarations(&self) -> &SystemDeclarations;
fn get_queries(&self) -> &Vec<Query>;
fn get_project_path(&self) -> &str;
fn get_project_path(&self) -> &PathBuf;
fn to_comp_loader(self: Box<Self>) -> Box<dyn ComponentLoader>;
}

pub struct JsonProjectLoader {
project_path: String,
project_path: PathBuf,
loaded_components: ComponentsMap,
system_declarations: SystemDeclarations,
queries: Vec<Query>,
Expand Down Expand Up @@ -247,7 +248,7 @@ impl ProjectLoader for JsonProjectLoader {
&self.queries
}

fn get_project_path(&self) -> &str {
fn get_project_path(&self) -> &PathBuf {
&self.project_path
}

Expand All @@ -257,12 +258,16 @@ impl ProjectLoader for JsonProjectLoader {
}

impl JsonProjectLoader {
pub fn new_loader(project_path: String, settings: Settings) -> Box<dyn ProjectLoader> {
#[allow(clippy::new_ret_no_self)]
pub fn new_loader<P: AsRef<Path>>(
project_path: P,
settings: Settings,
) -> Box<dyn ProjectLoader> {
let system_declarations = json_reader::read_system_declarations(&project_path).unwrap();
let queries = json_reader::read_queries(&project_path).unwrap();

Box::new(JsonProjectLoader {
project_path,
project_path: project_path.as_ref().to_path_buf(),
loaded_components: HashMap::new(),
system_declarations,
queries,
Expand Down Expand Up @@ -290,7 +295,7 @@ impl JsonProjectLoader {
}

pub struct XmlProjectLoader {
project_path: String,
project_path: PathBuf,
loaded_components: ComponentsMap,
system_declarations: SystemDeclarations,
queries: Vec<Query>,
Expand Down Expand Up @@ -328,7 +333,7 @@ impl ProjectLoader for XmlProjectLoader {
&self.queries
}

fn get_project_path(&self) -> &str {
fn get_project_path(&self) -> &PathBuf {
&self.project_path
}

Expand All @@ -338,7 +343,11 @@ impl ProjectLoader for XmlProjectLoader {
}

impl XmlProjectLoader {
pub fn new_loader(project_path: String, settings: Settings) -> Box<dyn ProjectLoader> {
#[allow(clippy::new_ret_no_self)]
pub fn new_loader<P: AsRef<Path>>(
project_path: P,
settings: Settings,
) -> Box<dyn ProjectLoader> {
let (comps, system_declarations, queries) = parse_xml_from_file(&project_path);

let mut map = HashMap::<String, Component>::new();
Expand All @@ -353,7 +362,7 @@ impl XmlProjectLoader {
}

Box::new(XmlProjectLoader {
project_path,
project_path: project_path.as_ref().to_path_buf(),
loaded_components: map,
system_declarations,
queries,
Expand Down
49 changes: 25 additions & 24 deletions src/DataReader/json_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,35 @@ use std::fs::File;
use std::io::Read;
use std::path::Path;

pub fn read_system_declarations(project_path: &str) -> Option<SystemDeclarations> {
let sysdecl_path = format!(
"{}{}SystemDeclarations.json",
project_path,
std::path::MAIN_SEPARATOR
);
pub fn read_system_declarations<P: AsRef<Path>>(project_path: P) -> Option<SystemDeclarations> {
let sysdecl_path = project_path.as_ref().join("SystemDeclarations.json");

if !Path::new(&sysdecl_path).exists() {
return None;
}

match read_json::<SystemDeclarations>(&sysdecl_path) {
match read_json::<SystemDeclarations, _>(&sysdecl_path) {
Ok(sys_decls) => Some(sys_decls),
Err(error) => panic!(
"We got error {}, and could not parse json file {} to component",
error, &sysdecl_path
error,
sysdecl_path.display()
),
}
}

pub fn read_json_component(project_path: &str, component_name: &str) -> Component {
let component_path = format!(
"{0}{1}Components{1}{2}.json",
project_path,
std::path::MAIN_SEPARATOR,
component_name
);
pub fn read_json_component<P: AsRef<Path>>(project_path: P, component_name: &str) -> Component {
let component_path = project_path
.as_ref()
.join("Components")
.join(format!("{}.json", component_name));

let component: Component = match read_json(&component_path) {
Ok(json) => json,
Err(error) => panic!(
"We got error {}, and could not parse json file {} to component",
error, component_path
error,
component_path.display()
),
};

Expand All @@ -46,14 +42,18 @@ pub fn read_json_component(project_path: &str, component_name: &str) -> Componen
//Input:File name
//Description:uses the filename to open the file and then reads the file.
//Output: Result type, if more info about this type is need please go to: https://doc.rust-lang.org/std/result/
pub fn read_json<T: DeserializeOwned>(filename: &str) -> serde_json::Result<T> {
let mut file =
File::open(filename).unwrap_or_else(|_| panic!("Could not find file {}", filename));
pub fn read_json<T: DeserializeOwned, P: AsRef<Path>>(filename: P) -> serde_json::Result<T> {
let mut file = File::open(&filename)
.unwrap_or_else(|_| panic!("Could not find file {}", filename.as_ref().display()));
let mut data = String::new();
file.read_to_string(&mut data).unwrap();

let json_file = serde_json::from_str(&data)
.unwrap_or_else(|_| panic!("{}: Json format is not as expected", filename));
let json_file = serde_json::from_str(&data).unwrap_or_else(|_| {
panic!(
"{}: Json format is not as expected",
filename.as_ref().display()
)
});

Ok(json_file)
}
Expand All @@ -65,8 +65,8 @@ pub fn json_to_component(json_str: &str) -> Result<Component, serde_json::Error>
//Input:Filename
//Description: transforms json into query type
//Output:Result
pub fn read_queries(project_path: &str) -> Option<Vec<Query>> {
let queries_path = format!("{}{}Queries.json", project_path, std::path::MAIN_SEPARATOR);
pub fn read_queries<P: AsRef<Path>>(project_path: P) -> Option<Vec<Query>> {
let queries_path = project_path.as_ref().join("Queries.json");

if !Path::new(&queries_path).exists() {
return None;
Expand All @@ -76,7 +76,8 @@ pub fn read_queries(project_path: &str) -> Option<Vec<Query>> {
Ok(json) => Some(json),
Err(error) => panic!(
"We got error {}, and could not parse json file {} to query",
error, &queries_path
error,
queries_path.display()
),
}
}
15 changes: 7 additions & 8 deletions src/DataReader/json_writer.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use crate::ModelObjects::Component;
use std::fs::File;
use std::{fs::File, path::Path};

pub fn component_to_json_file<P: AsRef<Path>>(project_path: P, component: &Component) {
let path = project_path
.as_ref()
.join("Components")
.join(format!("{}.json", component.name));

pub fn component_to_json_file(project_path: &str, component: &Component) {
let path = format!(
"{0}{1}Components{1}{2}.json",
project_path,
std::path::MAIN_SEPARATOR,
component.name
);
let file = File::create(path).expect("Couldnt open file");

serde_json::to_writer_pretty(&file, component).expect("Failed to serialize component");
Expand Down
4 changes: 2 additions & 2 deletions src/DataReader/parse_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ pub fn test_parse() {
}

pub fn parse_to_query(input: &str) -> Vec<Query> {
let queries = parse_to_expression_tree(input).unwrap();
queries
parse_to_expression_tree(input)
.expect("Parsing failed")
.into_iter()
.map(|q| Query {
query: Option::from(q),
Expand Down
9 changes: 5 additions & 4 deletions src/DataReader/xml_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use std::path::Path;

pub fn is_xml_project(project_path: &str) -> bool {
project_path.ends_with(".xml")
pub fn is_xml_project<P: AsRef<Path>>(project_path: P) -> bool {
project_path.as_ref().ends_with(".xml")
}

///Used to parse systems described in xml
pub(crate) fn parse_xml_from_file(
fileName: &str,
pub(crate) fn parse_xml_from_file<P: AsRef<Path>>(
fileName: P,
) -> (Vec<Component>, SystemDeclarations, Vec<Query>) {
//Open file and read xml
let file = File::open(fileName).unwrap();
Expand Down
Loading

0 comments on commit 4b41c9d

Please sign in to comment.