plut-core 2.10.0

Project model, run context and diagnostics for Plut
Documentation
//! A Rojo sourcemap is the project model: it states which file lands on which instance.
//! Run context is derived from that tree, not guessed from directories.

use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::Error;

/// One node of a Rojo sourcemap.
#[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>,
}

/// A flattened sourcemap node: an instance path, its class, and the files that define it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instance {
    pub path: String,
    pub class_name: String,
    pub file_paths: Vec<PathBuf>,
}

/// Load a sourcemap from disk.
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))
}

/// Flatten a sourcemap tree into instances, depth first.
#[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>) {
    // The DataModel is the container, not an instance with a path of its own.
    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);
    }
}