Skip to main content

plut_core/
sourcemap.rs

1//! A Rojo sourcemap is the project model: it states which file lands on which instance.
2//! Run context is derived from that tree, not guessed from directories.
3
4use std::path::{Path, PathBuf};
5
6use serde::Deserialize;
7
8use crate::Error;
9
10/// One node of a Rojo sourcemap.
11#[derive(Debug, Clone, Deserialize)]
12#[serde(rename_all = "camelCase")]
13pub struct Node {
14    #[serde(default)]
15    pub name: String,
16    #[serde(default)]
17    pub class_name: String,
18    #[serde(default)]
19    pub file_paths: Vec<PathBuf>,
20    #[serde(default)]
21    pub children: Vec<Node>,
22}
23
24/// A flattened sourcemap node: an instance path, its class, and the files that define it.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Instance {
27    pub path: String,
28    pub class_name: String,
29    pub file_paths: Vec<PathBuf>,
30}
31
32/// Load a sourcemap from disk.
33pub fn load(path: &Path) -> Result<Vec<Instance>, Error> {
34    let text = std::fs::read_to_string(path).map_err(|source| Error::Read {
35        path: path.to_path_buf(),
36        source,
37    })?;
38    let root: Node = serde_json::from_str(&text).map_err(|source| Error::ParseJson {
39        path: path.to_path_buf(),
40        source,
41    })?;
42    Ok(flatten(&root))
43}
44
45/// Flatten a sourcemap tree into instances, depth first.
46#[must_use]
47pub fn flatten(root: &Node) -> Vec<Instance> {
48    let mut out = Vec::new();
49    visit(root, "", true, &mut out);
50    out
51}
52
53fn visit(node: &Node, parent: &str, is_root: bool, out: &mut Vec<Instance>) {
54    // The DataModel is the container, not an instance with a path of its own.
55    let is_data_model = is_root && node.class_name == "DataModel";
56    let path = if is_data_model {
57        String::new()
58    } else if parent.is_empty() {
59        node.name.clone()
60    } else {
61        format!("{parent}/{}", node.name)
62    };
63
64    if !is_data_model {
65        out.push(Instance {
66            path: path.clone(),
67            class_name: node.class_name.clone(),
68            file_paths: node.file_paths.clone(),
69        });
70    }
71
72    for child in &node.children {
73        visit(child, &path, false, out);
74    }
75}