Skip to main content

cgx_engine/
export.rs

1use std::collections::{HashMap, HashSet};
2use std::io::Write;
3use std::process::Command;
4
5use crate::graph::{Edge, GraphDb, Node};
6
7pub fn export_json(db: &GraphDb) -> anyhow::Result<String> {
8    let nodes = db.get_all_nodes()?;
9    let edges = db.get_all_edges()?;
10    let communities = db.get_communities()?;
11    let breakdown = db.get_language_breakdown()?;
12    let indexed_at = chrono::Utc::now().to_rfc3339();
13
14    let community_list: Vec<serde_json::Value> = communities
15        .into_iter()
16        .map(|(id, label, node_count, top_nodes)| {
17            serde_json::json!({
18                "id": id,
19                "label": label,
20                "node_count": node_count,
21                "top_nodes": top_nodes,
22            })
23        })
24        .collect();
25
26    let output = serde_json::json!({
27        "meta": {
28            "repo_id": db.repo_id,
29            "indexed_at": indexed_at,
30            "node_count": nodes.len(),
31            "edge_count": edges.len(),
32            "language_breakdown": breakdown,
33            "community_count": community_list.len(),
34        },
35        "nodes": nodes,
36        "edges": edges,
37        "communities": community_list,
38    });
39
40    Ok(serde_json::to_string_pretty(&output)?)
41}
42
43pub fn export_mermaid(db: &GraphDb, max_nodes: usize) -> anyhow::Result<String> {
44    let max = max_nodes.clamp(1, 500);
45    let nodes = db.get_all_nodes()?;
46    let edges = db.get_all_edges()?;
47
48    if nodes.is_empty() {
49        return Ok("graph TD\n  A[\"No data\"]\n".to_string());
50    }
51
52    let node_ids: HashSet<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
53
54    let mut node_degree: HashMap<String, usize> = HashMap::new();
55    for edge in &edges {
56        if node_ids.contains(edge.src.as_str()) && node_ids.contains(edge.dst.as_str()) {
57            *node_degree.entry(edge.src.clone()).or_default() += 1;
58            *node_degree.entry(edge.dst.clone()).or_default() += 1;
59        }
60    }
61
62    let mut ranked: Vec<&Node> = nodes.iter().collect();
63    ranked.sort_by_key(|n| -(node_degree.get(&n.id).copied().unwrap_or(0) as i64));
64    ranked.truncate(max);
65
66    let selected: HashSet<&str> = ranked.iter().map(|n| n.id.as_str()).collect();
67
68    let mut included_edges: Vec<&Edge> = edges
69        .iter()
70        .filter(|e| selected.contains(e.src.as_str()) && selected.contains(e.dst.as_str()))
71        .collect();
72    included_edges.truncate(max);
73
74    let mut output = String::from("graph TD\n");
75
76    let mut safe_ids: HashMap<&str, String> = HashMap::new();
77    for node in &ranked {
78        let safe = sanitize_mermaid_id(&node.id);
79        safe_ids.insert(&node.id, safe.clone());
80        let label = sanitize_mermaid_label(&node.name);
81        output.push_str(&format!("  {}[\"{}\"]\n", safe, label));
82    }
83
84    for edge in &included_edges {
85        if let (Some(src_safe), Some(dst_safe)) = (
86            safe_ids.get(edge.src.as_str()),
87            safe_ids.get(edge.dst.as_str()),
88        ) {
89            let style = match edge.kind.as_str() {
90                "CALLS" => "-->",
91                "IMPORTS" => "-.->",
92                "CO_CHANGES" => "==>",
93                _ => "-->",
94            };
95            output.push_str(&format!("  {} {} {}\n", src_safe, style, dst_safe));
96        }
97    }
98
99    if ranked.len() < nodes.len() {
100        output.push_str(&format!(
101            "  %% Showing {}/{} nodes ({} edges filtered)\n",
102            ranked.len(),
103            nodes.len(),
104            edges.len() - included_edges.len()
105        ));
106    }
107
108    Ok(output)
109}
110
111pub fn export_dot(db: &GraphDb) -> anyhow::Result<String> {
112    let nodes = db.get_all_nodes()?;
113    let edges = db.get_all_edges()?;
114
115    if nodes.is_empty() {
116        return Ok("digraph G {\n  label=\"No data\";\n}\n".to_string());
117    }
118
119    let mut output = String::from("digraph G {\n");
120    output.push_str("  rankdir=LR;\n");
121    output.push_str("  bgcolor=\"#0a0a0f\";\n");
122    output.push_str("  node [fontname=\"JetBrains Mono\", fontsize=10];\n");
123    output.push_str("  edge [fontname=\"JetBrains Mono\", fontsize=8];\n\n");
124
125    let kind_colors: HashMap<&str, &str> = [
126        ("Function", "#00ff88"),
127        ("Class", "#3b82f6"),
128        ("File", "#f59e0b"),
129        ("Module", "#8b5cf6"),
130        ("Author", "#ec4899"),
131        ("Variable", "#06b6d4"),
132        ("Type", "#f97316"),
133    ]
134    .into_iter()
135    .collect();
136
137    let max_churn = nodes
138        .iter()
139        .map(|n| n.churn)
140        .fold(0.0f64, f64::max)
141        .max(0.01);
142
143    for node in &nodes {
144        let safe_id = sanitize_dot_id(&node.id);
145        let label = node.name.replace('"', "\\\"");
146        let color = kind_colors
147            .get(node.kind.as_str())
148            .copied()
149            .unwrap_or("#888888");
150        let size = 0.3 + (node.churn / max_churn) * 0.7;
151
152        output.push_str(&format!(
153            "  \"{}\" [label=\"{}\", color=\"{}\", fontcolor=\"{}\", width={:.2}, height={:.2}];\n",
154            safe_id,
155            label,
156            color,
157            color,
158            size,
159            size * 0.6
160        ));
161    }
162
163    output.push('\n');
164
165    let edge_colors: HashMap<&str, &str> = [
166        ("CALLS", "#ffffff33"),
167        ("IMPORTS", "#3b82f644"),
168        ("CO_CHANGES", "#ef444466"),
169        ("OWNS", "#ec489944"),
170        ("INHERITS", "#8b5cf644"),
171    ]
172    .into_iter()
173    .collect();
174
175    for edge in &edges {
176        let safe_src = sanitize_dot_id(&edge.src);
177        let safe_dst = sanitize_dot_id(&edge.dst);
178        let color = edge_colors
179            .get(edge.kind.as_str())
180            .copied()
181            .unwrap_or("#ffffff22");
182
183        output.push_str(&format!(
184            "  \"{}\" -> \"{}\" [color=\"{}\", penwidth={:.1}];\n",
185            safe_src,
186            safe_dst,
187            color,
188            (edge.weight * 1.5).clamp(0.5, 5.0)
189        ));
190    }
191
192    output.push_str("}\n");
193    Ok(output)
194}
195
196pub fn export_svg(db: &GraphDb) -> anyhow::Result<String> {
197    let dot_output = export_dot(db)?;
198
199    if let Ok(svg) = dot_to_svg(&dot_output) {
200        return Ok(svg);
201    }
202
203    fallback_svg_with_data(db)
204}
205
206fn fallback_svg_with_data(db: &GraphDb) -> anyhow::Result<String> {
207    let nodes = db.get_all_nodes()?;
208    let edges = db.get_all_edges()?;
209    render_svg_circle(&nodes, &edges)
210}
211
212fn dot_to_svg(dot: &str) -> anyhow::Result<String> {
213    let mut child = Command::new("dot")
214        .arg("-Tsvg")
215        .stdin(std::process::Stdio::piped())
216        .stdout(std::process::Stdio::piped())
217        .stderr(std::process::Stdio::null())
218        .spawn()?;
219
220    if let Some(mut stdin) = child.stdin.take() {
221        stdin.write_all(dot.as_bytes())?;
222    }
223
224    let output = child.wait_with_output()?;
225    if output.status.success() {
226        Ok(String::from_utf8_lossy(&output.stdout).to_string())
227    } else {
228        anyhow::bail!("dot command failed")
229    }
230}
231
232fn render_svg_circle(nodes: &[Node], edges: &[Edge]) -> anyhow::Result<String> {
233    if nodes.is_empty() {
234        return Ok(r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200">
235  <rect width="400" height="200" fill="#0a0a0f"/>
236  <text x="200" y="100" text-anchor="middle" fill="#888" font-family="JetBrains Mono, monospace" font-size="14">No data</text>
237</svg>"##.to_string());
238    }
239
240    let display_nodes: Vec<&Node> = nodes.iter().collect();
241    let max_display = display_nodes.len().min(200);
242    let display_nodes = &display_nodes[..max_display];
243
244    let node_ids: HashSet<&str> = display_nodes.iter().map(|n| n.id.as_str()).collect();
245    let display_edges: Vec<&Edge> = edges
246        .iter()
247        .filter(|e| node_ids.contains(e.src.as_str()) && node_ids.contains(e.dst.as_str()))
248        .take(max_display * 2)
249        .collect();
250
251    let center_x = 400.0;
252    let center_y = 400.0;
253    let radius = 320.0;
254    let total = display_nodes.len() as f64;
255
256    let mut positions: HashMap<&str, (f64, f64)> = HashMap::new();
257    for (i, node) in display_nodes.iter().enumerate() {
258        let angle = 2.0 * std::f64::consts::PI * (i as f64) / total - std::f64::consts::PI / 2.0;
259        let x = center_x + radius * angle.cos();
260        let y = center_y + radius * angle.sin();
261        positions.insert(&node.id, (x, y));
262    }
263
264    let kind_colors: HashMap<&str, &str> = [
265        ("Function", "#00ff88"),
266        ("Class", "#3b82f6"),
267        ("File", "#f59e0b"),
268        ("Module", "#8b5cf6"),
269        ("Author", "#ec4899"),
270        ("Variable", "#06b6d4"),
271        ("Type", "#f97316"),
272    ]
273    .into_iter()
274    .collect();
275
276    let edge_colors: HashMap<&str, &str> = [
277        ("CALLS", "#ffffff22"),
278        ("IMPORTS", "#3b82f644"),
279        ("CO_CHANGES", "#ef444466"),
280        ("OWNS", "#ec489944"),
281        ("INHERITS", "#8b5cf644"),
282    ]
283    .into_iter()
284    .collect();
285
286    let mut svg = format!(
287        r##"<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800" viewBox="0 0 800 800">
288  <rect width="800" height="800" fill="#0a0a0f"/>
289  <text x="10" y="20" fill="#555" font-family="JetBrains Mono, monospace" font-size="10">cgx graph - {} nodes, {} edges</text>
290"##,
291        nodes.len(),
292        edges.len()
293    );
294
295    for edge in &display_edges {
296        if let (Some(&(x1, y1)), Some(&(x2, y2))) = (
297            positions.get(edge.src.as_str()),
298            positions.get(edge.dst.as_str()),
299        ) {
300            let color = edge_colors
301                .get(edge.kind.as_str())
302                .copied()
303                .unwrap_or("#ffffff11");
304            svg.push_str(&format!(
305                r##"  <line x1="{:.1}" y1="{:.1}" x2="{:.1}" y2="{:.1}" stroke="{}" stroke-width="{:.1}" opacity="0.6"/>
306"##,
307                x1, y1, x2, y2, color, (edge.weight * 1.0).clamp(0.3, 3.0)
308            ));
309        }
310    }
311
312    for node in display_nodes.iter() {
313        if let Some(&(x, y)) = positions.get(node.id.as_str()) {
314            let color = kind_colors
315                .get(node.kind.as_str())
316                .copied()
317                .unwrap_or("#888888");
318            let r = 4.0 + (node.churn * 8.0).min(12.0);
319            let label = node.name.chars().take(20).collect::<String>();
320            let escaped_label = label
321                .replace('&', "&amp;")
322                .replace('<', "&lt;")
323                .replace('>', "&gt;");
324
325            svg.push_str(&format!(
326                r##"  <circle cx="{:.1}" cy="{:.1}" r="{:.1}" fill="{}" opacity="0.8"/>
327"##,
328                x, y, r, color
329            ));
330            svg.push_str(&format!(
331                r##"  <text x="{:.1}" y="{:.1}" fill="#ccc" font-family="JetBrains Mono, monospace" font-size="8" text-anchor="middle">{}</text>
332"##,
333                x,
334                y - r - 3.0,
335                escaped_label
336            ));
337        }
338    }
339
340    svg.push_str("</svg>\n");
341    Ok(svg)
342}
343
344pub fn export_graphml(db: &GraphDb) -> anyhow::Result<String> {
345    let nodes = db.get_all_nodes()?;
346    let edges = db.get_all_edges()?;
347
348    let mut xml = String::from(
349        r#"<?xml version="1.0" encoding="UTF-8"?>
350<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
351         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
352         xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
353         http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
354  <key id="name" for="node" attr.name="name" attr.type="string"/>
355  <key id="kind" for="node" attr.name="kind" attr.type="string"/>
356  <key id="path" for="node" attr.name="path" attr.type="string"/>
357  <key id="churn" for="node" attr.name="churn" attr.type="double"/>
358  <key id="coupling" for="node" attr.name="coupling" attr.type="double"/>
359  <key id="community" for="node" attr.name="community" attr.type="long"/>
360  <key id="language" for="node" attr.name="language" attr.type="string"/>
361  <key id="kind" for="edge" attr.name="kind" attr.type="string"/>
362  <key id="weight" for="edge" attr.name="weight" attr.type="double"/>
363  <key id="confidence" for="edge" attr.name="confidence" attr.type="double"/>
364  <graph id="G" edgedefault="directed">
365"#,
366    );
367
368    for node in &nodes {
369        let safe_id = xml_escape(&node.id);
370        let safe_name = xml_escape(&node.name);
371        let safe_path = xml_escape(&node.path);
372        let safe_kind = xml_escape(&node.kind);
373        let safe_lang = xml_escape(&node.language);
374
375        xml.push_str(&format!("    <node id=\"{}\">\n", safe_id));
376        xml.push_str(&format!("      <data key=\"name\">{}</data>\n", safe_name));
377        xml.push_str(&format!("      <data key=\"kind\">{}</data>\n", safe_kind));
378        xml.push_str(&format!("      <data key=\"path\">{}</data>\n", safe_path));
379        xml.push_str(&format!(
380            "      <data key=\"churn\">{}</data>\n",
381            node.churn
382        ));
383        xml.push_str(&format!(
384            "      <data key=\"coupling\">{}</data>\n",
385            node.coupling
386        ));
387        xml.push_str(&format!(
388            "      <data key=\"community\">{}</data>\n",
389            node.community
390        ));
391        xml.push_str(&format!(
392            "      <data key=\"language\">{}</data>\n",
393            safe_lang
394        ));
395        xml.push_str("    </node>\n");
396    }
397
398    for edge in &edges {
399        let safe_src = xml_escape(&edge.src);
400        let safe_dst = xml_escape(&edge.dst);
401        let safe_kind = xml_escape(&edge.kind);
402
403        xml.push_str(&format!(
404            "    <edge source=\"{}\" target=\"{}\">\n",
405            safe_src, safe_dst
406        ));
407        xml.push_str(&format!("      <data key=\"kind\">{}</data>\n", safe_kind));
408        xml.push_str(&format!(
409            "      <data key=\"weight\">{}</data>\n",
410            edge.weight
411        ));
412        xml.push_str(&format!(
413            "      <data key=\"confidence\">{}</data>\n",
414            edge.confidence
415        ));
416        xml.push_str("    </edge>\n");
417    }
418
419    xml.push_str("  </graph>\n</graphml>\n");
420    Ok(xml)
421}
422
423fn sanitize_mermaid_id(id: &str) -> String {
424    id.replace(
425        [':', '.', '/', '-', '(', ')', '[', ']', ' ', '<', '>', '|'],
426        "_",
427    )
428}
429
430fn sanitize_mermaid_label(name: &str) -> String {
431    name.replace('"', "'")
432        .replace('[', "(")
433        .replace(']', ")")
434        .chars()
435        .take(40)
436        .collect()
437}
438
439fn sanitize_dot_id(id: &str) -> String {
440    id.replace('"', "\\\"").replace(['\n', '\r'], " ")
441}
442
443fn xml_escape(s: &str) -> String {
444    s.replace('&', "&amp;")
445        .replace('<', "&lt;")
446        .replace('>', "&gt;")
447        .replace('"', "&quot;")
448        .replace('\'', "&apos;")
449}