fob_graph/memory/
serialization.rs

1//! Serialization methods for ModuleGraph.
2
3use super::super::external_dep::ExternalDependency;
4use super::super::{Module, ModuleId};
5use super::graph::ModuleGraph;
6use crate::{Error, Result};
7
8/// Helper to escape labels for DOT format.
9fn escape_label(label: &str) -> String {
10    label.replace('"', "\\\"")
11}
12
13impl ModuleGraph {
14    /// Export the graph as DOT format for visualization.
15    pub fn to_dot_format(&self) -> Result<String> {
16        let mut output = String::from("digraph ModuleGraph {\n");
17        let all_modules = self.modules()?;
18
19        for module in &all_modules {
20            output.push_str("    \"");
21            output.push_str(&escape_label(&module.id.path_string()));
22            output.push_str("\";\n");
23        }
24
25        for module in &all_modules {
26            let deps = self.dependencies(&module.id)?;
27            for target in deps {
28                output.push_str("    \"");
29                output.push_str(&escape_label(&module.id.path_string()));
30                output.push_str("\" -> \"");
31                output.push_str(&escape_label(&target.path_string()));
32                output.push_str("\";\n");
33            }
34        }
35
36        output.push_str("}\n");
37        Ok(output)
38    }
39
40    /// Export the graph and modules to JSON.
41    pub fn to_json(&self) -> Result<String> {
42        let all_modules = self.modules()?;
43        let entry_points = self.entry_points()?;
44        let external_deps = self.external_dependencies()?;
45
46        #[derive(serde::Serialize)]
47        struct GraphJson {
48            modules: Vec<Module>,
49            entry_points: Vec<ModuleId>,
50            external_deps: Vec<ExternalDependency>,
51        }
52
53        let graph_json = GraphJson {
54            modules: all_modules,
55            entry_points,
56            external_deps,
57        };
58
59        serde_json::to_string_pretty(&graph_json)
60            .map_err(|e| Error::InvalidConfig(format!("Failed to serialize graph: {e}")))
61    }
62}