Skip to main content

graphify_export/
json.rs

1//! NetworkX node_link_data compatible JSON export.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6use graphify_core::graph::KnowledgeGraph;
7use tracing::info;
8
9/// Export graph to `graph.json` in NetworkX `node_link_data` format.
10pub fn export_json(graph: &KnowledgeGraph, output_dir: &Path) -> anyhow::Result<PathBuf> {
11    let json = graph.to_node_link_json();
12    fs::create_dir_all(output_dir)?;
13    let path = output_dir.join("graph.json");
14    fs::write(&path, serde_json::to_string_pretty(&json)?)?;
15    info!(path = %path.display(), "exported graph JSON");
16    Ok(path)
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22    use graphify_core::confidence::Confidence;
23    use graphify_core::model::{GraphEdge, GraphNode, NodeType};
24    use std::collections::HashMap;
25
26    fn sample_graph() -> KnowledgeGraph {
27        let mut kg = KnowledgeGraph::new();
28        kg.add_node(GraphNode {
29            id: "a".into(),
30            label: "A".into(),
31            source_file: "test.rs".into(),
32            source_location: None,
33            node_type: NodeType::Class,
34            community: None,
35            extra: HashMap::new(),
36        })
37        .unwrap();
38        kg.add_node(GraphNode {
39            id: "b".into(),
40            label: "B".into(),
41            source_file: "test.rs".into(),
42            source_location: None,
43            node_type: NodeType::Function,
44            community: None,
45            extra: HashMap::new(),
46        })
47        .unwrap();
48        kg.add_edge(GraphEdge {
49            source: "a".into(),
50            target: "b".into(),
51            relation: "calls".into(),
52            confidence: Confidence::Extracted,
53            confidence_score: 1.0,
54            source_file: "test.rs".into(),
55            source_location: None,
56            weight: 1.0,
57            extra: HashMap::new(),
58        })
59        .unwrap();
60        kg
61    }
62
63    #[test]
64    fn export_json_creates_file() {
65        let dir = tempfile::tempdir().unwrap();
66        let kg = sample_graph();
67        let path = export_json(&kg, dir.path()).unwrap();
68        assert!(path.exists());
69
70        let content: serde_json::Value =
71            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
72        assert_eq!(content["nodes"].as_array().unwrap().len(), 2);
73        assert_eq!(content["links"].as_array().unwrap().len(), 1);
74    }
75}