use std::path::{Path, PathBuf};
use serde::Deserialize;
use crate::Error;
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Node {
#[serde(default)]
pub name: String,
#[serde(default)]
pub class_name: String,
#[serde(default)]
pub file_paths: Vec<PathBuf>,
#[serde(default)]
pub children: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instance {
pub path: String,
pub class_name: String,
pub file_paths: Vec<PathBuf>,
}
pub fn load(path: &Path) -> Result<Vec<Instance>, Error> {
let text = std::fs::read_to_string(path).map_err(|source| Error::Read {
path: path.to_path_buf(),
source,
})?;
let root: Node = serde_json::from_str(&text).map_err(|source| Error::ParseJson {
path: path.to_path_buf(),
source,
})?;
Ok(flatten(&root))
}
#[must_use]
pub fn flatten(root: &Node) -> Vec<Instance> {
let mut out = Vec::new();
visit(root, "", true, &mut out);
out
}
fn visit(node: &Node, parent: &str, is_root: bool, out: &mut Vec<Instance>) {
let is_data_model = is_root && node.class_name == "DataModel";
let path = if is_data_model {
String::new()
} else if parent.is_empty() {
node.name.clone()
} else {
format!("{parent}/{}", node.name)
};
if !is_data_model {
out.push(Instance {
path: path.clone(),
class_name: node.class_name.clone(),
file_paths: node.file_paths.clone(),
});
}
for child in &node.children {
visit(child, &path, false, out);
}
}