fix(notgraph): render dep graph edges, add dark mode

This commit is contained in:
Joseph O'Brien
2026-04-02 03:04:27 -04:00
parent 0cc1413a04
commit dcde5d1e82
3 changed files with 139 additions and 34 deletions

View File

@@ -1,17 +1,25 @@
use crate::types::{GraphStats, HotspotKind, SymbolKind, SymbolTable}; use crate::types::{CrateGraph, GraphStats, HotspotKind, SymbolKind, SymbolTable};
use anyhow::Result; use anyhow::Result;
use std::path::Path; use std::path::Path;
pub fn write_all(output_dir: &Path, stats: &GraphStats, symbol_tables: &[SymbolTable]) -> Result<()> { pub fn write_all(
output_dir: &Path,
crate_graph: &CrateGraph,
stats: &GraphStats,
symbol_tables: &[SymbolTable],
) -> Result<()> {
std::fs::create_dir_all(output_dir)?; std::fs::create_dir_all(output_dir)?;
write_json(output_dir, stats)?; write_json(output_dir, stats)?;
write_markdown(output_dir, stats, symbol_tables)?; write_markdown(output_dir, stats, symbol_tables)?;
write_html(output_dir, stats)?; write_html(output_dir, crate_graph, stats)?;
Ok(()) Ok(())
} }
fn write_json(dir: &Path, stats: &GraphStats) -> Result<()> { fn write_json(dir: &Path, stats: &GraphStats) -> Result<()> {
std::fs::write(dir.join("report.json"), serde_json::to_string_pretty(stats)?)?; std::fs::write(
dir.join("report.json"),
serde_json::to_string_pretty(stats)?,
)?;
Ok(()) Ok(())
} }
@@ -21,29 +29,47 @@ fn write_markdown(dir: &Path, stats: &GraphStats, symbol_tables: &[SymbolTable])
md.push_str("## Crate Dependency Graph\n\n"); md.push_str("## Crate Dependency Graph\n\n");
for fs in &stats.crate_graph { for fs in &stats.crate_graph {
md.push_str(&format!("- **{}** (fan-in: {}, fan-out: {})\n", fs.name, fs.fan_in, fs.fan_out)); md.push_str(&format!(
"- **{}** (fan-in: {}, fan-out: {})\n",
fs.name, fs.fan_in, fs.fan_out
));
} }
md.push('\n'); md.push('\n');
md.push_str("## Module Graphs\n\n"); md.push_str("## Module Graphs\n\n");
for ms in &stats.module_graphs { for ms in &stats.module_graphs {
let status = if ms.cycles.is_empty() { "OK" } else { "CYCLES DETECTED" }; let status = if ms.cycles.is_empty() {
"OK"
} else {
"CYCLES DETECTED"
};
md.push_str(&format!( md.push_str(&format!(
"### {} [{}]\n\n- Modules: {}\n- Cycles: {}\n\n", "### {} [{}]\n\n- Modules: {}\n- Cycles: {}\n\n",
ms.krate, status, ms.nodes.len(), ms.cycles.len() ms.krate,
status,
ms.nodes.len(),
ms.cycles.len()
)); ));
} }
md.push_str("## Hotspots\n\n### Fan-in (most depended-upon)\n\n"); md.push_str("## Hotspots\n\n### Fan-in (most depended-upon)\n\n");
md.push_str("| Name | Score |\n|------|-------|\n"); md.push_str("| Name | Score |\n|------|-------|\n");
for h in stats.hotspots.iter().filter(|h| h.kind == HotspotKind::FanIn) { for h in stats
.hotspots
.iter()
.filter(|h| h.kind == HotspotKind::FanIn)
{
md.push_str(&format!("| {} | {} |\n", h.name, h.score)); md.push_str(&format!("| {} | {} |\n", h.name, h.score));
} }
md.push('\n'); md.push('\n');
md.push_str("### Fan-out (highest coupling)\n\n"); md.push_str("### Fan-out (highest coupling)\n\n");
md.push_str("| Name | Score |\n|------|-------|\n"); md.push_str("| Name | Score |\n|------|-------|\n");
for h in stats.hotspots.iter().filter(|h| h.kind == HotspotKind::FanOut) { for h in stats
.hotspots
.iter()
.filter(|h| h.kind == HotspotKind::FanOut)
{
md.push_str(&format!("| {} | {} |\n", h.name, h.score)); md.push_str(&format!("| {} | {} |\n", h.name, h.score));
} }
md.push('\n'); md.push('\n');
@@ -51,8 +77,17 @@ fn write_markdown(dir: &Path, stats: &GraphStats, symbol_tables: &[SymbolTable])
md.push_str("## Public Symbol Inventory\n\n"); md.push_str("## Public Symbol Inventory\n\n");
for table in symbol_tables { for table in symbol_tables {
md.push_str(&format!("### {}\n\n", table.krate)); md.push_str(&format!("### {}\n\n", table.krate));
for kind in [SymbolKind::Struct, SymbolKind::Enum, SymbolKind::Trait, SymbolKind::Fn, SymbolKind::Type, SymbolKind::Const] { for kind in [
let syms: Vec<&str> = table.symbols.iter() SymbolKind::Struct,
SymbolKind::Enum,
SymbolKind::Trait,
SymbolKind::Fn,
SymbolKind::Type,
SymbolKind::Const,
] {
let syms: Vec<&str> = table
.symbols
.iter()
.filter(|s| s.kind == kind && s.is_pub) .filter(|s| s.kind == kind && s.is_pub)
.map(|s| s.name.as_str()) .map(|s| s.name.as_str())
.collect(); .collect();
@@ -75,29 +110,74 @@ fn write_markdown(dir: &Path, stats: &GraphStats, symbol_tables: &[SymbolTable])
Ok(()) Ok(())
} }
fn write_html(dir: &Path, stats: &GraphStats) -> Result<()> { fn write_html(dir: &Path, crate_graph: &CrateGraph, stats: &GraphStats) -> Result<()> {
let nodes_js: String = stats.crate_graph.iter().enumerate() // Build node id map from name -> index
.map(|(i, n)| format!("{{id:{},label:{:?},title:'fan-in:{} fan-out:{}'}}", i, n.name, n.fan_in, n.fan_out)) let name_to_id: std::collections::HashMap<&str, usize> = crate_graph
.nodes
.iter()
.enumerate()
.map(|(i, n)| (n.as_str(), i))
.collect();
let fan_map: std::collections::HashMap<&str, (usize, usize)> = stats
.crate_graph
.iter()
.map(|fs| (fs.name.as_str(), (fs.fan_in, fs.fan_out)))
.collect();
let nodes_js: String = crate_graph
.nodes
.iter()
.enumerate()
.map(|(i, n)| {
let (fi, fo) = fan_map.get(n.as_str()).copied().unwrap_or((0, 0));
format!(
"{{id:{},label:{:?},title:'fan-in:{} fan-out:{}'}}",
i, n, fi, fo
)
})
.collect::<Vec<_>>()
.join(",");
let edges_js: String = crate_graph
.edges
.iter()
.enumerate()
.filter_map(|(i, (from, to))| {
let from_id = name_to_id.get(from.as_str())?;
let to_id = name_to_id.get(to.as_str())?;
Some(format!("{{id:{},from:{},to:{}}}", i, from_id, to_id))
})
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(","); .join(",");
let cycle_html = if stats.cycles.is_empty() { let cycle_html = if stats.cycles.is_empty() {
"<p>No cycles detected.</p>".to_string() "<p>No cycles detected.</p>".to_string()
} else { } else {
stats.cycles.iter() stats
.cycles
.iter()
.map(|c| format!("<p>CYCLE: {}</p>", c.join(" -&gt; "))) .map(|c| format!("<p>CYCLE: {}</p>", c.join(" -&gt; ")))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n") .join("\n")
}; };
let hotspot_rows: String = stats.hotspots.iter() let hotspot_rows: String = stats
.map(|h| format!("<tr><td>{}</td><td>{}</td><td>{}</td></tr>", h.name, h.kind, h.score)) .hotspots
.iter()
.map(|h| {
format!(
"<tr><td>{}</td><td>{}</td><td>{}</td></tr>",
h.name, h.kind, h.score
)
})
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n"); .join("\n");
let html = format!( let html = format!(
include_str!("../templates/report.html.template"), include_str!("../templates/report.html.template"),
nodes_js = nodes_js, nodes_js = nodes_js,
edges_js = edges_js,
hotspot_rows = hotspot_rows, hotspot_rows = hotspot_rows,
cycle_html = cycle_html, cycle_html = cycle_html,
); );

View File

@@ -1,10 +1,13 @@
use notgraph_lib::{analysis, crate_graph, emit, module_graph, symbols};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use clap::Parser; use clap::Parser;
use notgraph_lib::{analysis, crate_graph, emit, module_graph, symbols};
use std::path::PathBuf; use std::path::PathBuf;
#[derive(Parser)] #[derive(Parser)]
#[command(name = "notgraph", about = "Workspace module graph and symbol analysis")] #[command(
name = "notgraph",
about = "Workspace module graph and symbol analysis"
)]
struct Cli { struct Cli {
#[arg(long, default_value = "docs/graph")] #[arg(long, default_value = "docs/graph")]
output: PathBuf, output: PathBuf,
@@ -21,8 +24,7 @@ fn main() -> Result<()> {
let manifest = find_workspace_manifest()?; let manifest = find_workspace_manifest()?;
let workspace_root = manifest.parent().unwrap().to_path_buf(); let workspace_root = manifest.parent().unwrap().to_path_buf();
let crate_g = crate_graph::build(&manifest) let crate_g = crate_graph::build(&manifest).context("failed to build crate graph")?;
.context("failed to build crate graph")?;
let meta = cargo_metadata::MetadataCommand::new() let meta = cargo_metadata::MetadataCommand::new()
.manifest_path(&manifest) .manifest_path(&manifest)
@@ -37,17 +39,19 @@ fn main() -> Result<()> {
continue; continue;
} }
let src_dir = PathBuf::from(pkg.manifest_path.as_str()) let src_dir = PathBuf::from(pkg.manifest_path.as_str())
.parent().unwrap().join("src"); .parent()
.unwrap()
.join("src");
if !src_dir.exists() { if !src_dir.exists() {
continue; continue;
} }
module_graphs.push( module_graphs.push(
module_graph::build(pkg.name.clone(), &src_dir) module_graph::build(pkg.name.clone(), &src_dir)
.with_context(|| format!("module_graph failed for {}", pkg.name))? .with_context(|| format!("module_graph failed for {}", pkg.name))?,
); );
symbol_tables.push( symbol_tables.push(
symbols::build(pkg.name.clone(), &src_dir) symbols::build(pkg.name.clone(), &src_dir)
.with_context(|| format!("symbols failed for {}", pkg.name))? .with_context(|| format!("symbols failed for {}", pkg.name))?,
); );
} }
@@ -59,7 +63,7 @@ fn main() -> Result<()> {
workspace_root.join(&cli.output) workspace_root.join(&cli.output)
}; };
emit::write_all(&output_dir, &stats, &symbol_tables) emit::write_all(&output_dir, &crate_g, &stats, &symbol_tables)
.context("failed to write reports")?; .context("failed to write reports")?;
println!("notgraph: reports written to {}", output_dir.display()); println!("notgraph: reports written to {}", output_dir.display());

View File

@@ -5,13 +5,33 @@
<title>notgraph Report</title> <title>notgraph Report</title>
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script> <script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<style> <style>
body {{ font-family: sans-serif; margin: 2rem; max-width: 1200px; }} :root {{
#graph {{ height: 400px; border: 1px solid #ccc; margin-bottom: 2rem; }} --bg: #1a1a1a;
--bg2: #242424;
--bg3: #2e2e2e;
--border: #3a3a3a;
--text: #e0e0e0;
--text-dim: #888;
--accent: #4a9eff;
--accent2: #2a5fa0;
--node-bg: #1e3a5f;
--node-border: #4a9eff;
--heading-border: #4a9eff;
}}
* {{ box-sizing: border-box; }}
body {{ font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); margin: 0; padding: 2rem; max-width: 1200px; }}
h1 {{ color: var(--accent); margin-bottom: 0.5rem; }}
h2 {{ border-bottom: 2px solid var(--heading-border); padding-bottom: 0.3rem; color: var(--text); margin-top: 2rem; }}
#graph {{ height: 480px; border: 1px solid var(--border); margin-bottom: 2rem; background: var(--bg2); border-radius: 4px; }}
table {{ border-collapse: collapse; width: 100%; margin-bottom: 2rem; }} table {{ border-collapse: collapse; width: 100%; margin-bottom: 2rem; }}
th, td {{ border: 1px solid #ccc; padding: 0.4rem 0.8rem; text-align: left; }} th, td {{ border: 1px solid var(--border); padding: 0.4rem 0.8rem; text-align: left; }}
th {{ background: #f5f5f5; cursor: pointer; user-select: none; }} th {{ background: var(--bg3); cursor: pointer; user-select: none; color: var(--accent); }}
th:hover {{ background: #e8e8e8; }} th:hover {{ background: var(--border); }}
h2 {{ border-bottom: 2px solid #333; padding-bottom: 0.3rem; }} td {{ background: var(--bg2); }}
tr:hover td {{ background: var(--bg3); }}
p {{ color: var(--text); }}
.ok {{ color: #4caf50; }}
.cycle {{ color: #f44336; }}
</style> </style>
</head> </head>
<body> <body>
@@ -20,11 +40,12 @@
<div id="graph"></div> <div id="graph"></div>
<script> <script>
const nodes = new vis.DataSet([{nodes_js}]); const nodes = new vis.DataSet([{nodes_js}]);
const edges = new vis.DataSet([]); const edges = new vis.DataSet([{edges_js}]);
new vis.Network(document.getElementById('graph'), {{nodes, edges}}, {{ new vis.Network(document.getElementById('graph'), {{nodes, edges}}, {{
layout: {{ hierarchical: {{ direction: 'LR', sortMethod: 'directed' }} }}, layout: {{ hierarchical: {{ direction: 'LR', sortMethod: 'directed', levelSeparation: 180 }} }},
physics: false, physics: false,
nodes: {{ shape: 'box', color: {{ background: '#d4e8ff', border: '#336699' }} }} edges: {{ arrows: {{ to: {{ enabled: true, scaleFactor: 0.8 }} }}, color: {{ color: '#4a9eff', opacity: 0.8 }}, smooth: {{ type: 'cubicBezier' }} }},
nodes: {{ shape: 'box', font: {{ color: '#e0e0e0', size: 14 }}, color: {{ background: '#1e3a5f', border: '#4a9eff', highlight: {{ background: '#2a5fa0', border: '#7bbfff' }} }}, margin: 8 }}
}}); }});
</script> </script>
<h2>Hotspots</h2> <h2>Hotspots</h2>