Skip to content

Commit

Permalink
Move generation code into lib.rs
Browse files Browse the repository at this point in the history
This allows the libary to have a single point of entry without having all the logic for generating hypothesis in the cli crate
  • Loading branch information
LukasPrediger committed Sep 14, 2022
1 parent 48b6720 commit c7bc513
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 13 deletions.
17 changes: 4 additions & 13 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clap::Parser;
use schema2000::{render_schema, SchemaHypothesis};
use schema2000::{generate_hypothesis_from_iterator, render_schema, SchemaHypothesis};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let _args = Args::parse();
Expand All @@ -10,19 +10,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let deserializer = serde_json::Deserializer::from_reader(stdin);
let iterator = deserializer.into_iter::<serde_json::Value>();

let mut current_hypothesis: Option<SchemaHypothesis> = None;
let hypothesis: SchemaHypothesis =
generate_hypothesis_from_iterator(iterator.map(|value| value.unwrap()));

for json_document in iterator {
let new_hypo = schema2000::generate_hypothesis(&json_document?);
if current_hypothesis.is_none() {
current_hypothesis = Some(new_hypo);
} else {
current_hypothesis =
current_hypothesis.map(|cur| schema2000::merge_hypothesis(cur, new_hypo));
}
}

let result = render_schema(&current_hypothesis.unwrap());
let result = render_schema(&hypothesis);

println!("{}", result);

Expand Down
19 changes: 19 additions & 0 deletions core/src/generate.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::{BTreeMap, BTreeSet};

use crate::merge_hypothesis;
use serde_json::{Map, Value};

use crate::model::{
Expand Down Expand Up @@ -88,6 +89,24 @@ pub fn generate_hypothesis(dom: &Value) -> SchemaHypothesis {
}
}

pub fn generate_hypothesis_from_iterator<I>(values: I) -> SchemaHypothesis
where
I: Iterator<Item = Value>,
{
let mut current_hypothesis: Option<SchemaHypothesis> = None;

for json_document in values {
let new_hypo = generate_hypothesis(&json_document);
if current_hypothesis.is_none() {
current_hypothesis = Some(new_hypo);
} else {
current_hypothesis = current_hypothesis.map(|cur| merge_hypothesis(cur, new_hypo));
}
}

current_hypothesis.unwrap()
}

#[cfg(test)]
mod test {
use maplit::{btreemap, btreeset};
Expand Down
1 change: 1 addition & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(clippy::module_name_repetitions)]

pub use generate::generate_hypothesis;
pub use generate::generate_hypothesis_from_iterator;
pub use merge::merge_hypothesis;
pub use model::SchemaHypothesis;
pub use renderer::render_schema;
Expand Down

0 comments on commit c7bc513

Please sign in to comment.