use std::io::Write;
use std::path::{Path, PathBuf};
use astrs_graph::DataflowGraph;
use astrs_manifest::Manifest;
use astrs_manifest::expand::FsModuleLoader;
use crate::error::CliError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphFormat {
Mermaid,
Dot,
Html,
}
#[derive(Debug, Clone)]
pub struct GraphArgs {
pub manifest_path: PathBuf,
pub format: GraphFormat,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphReport {
pub rendered: String,
pub node_count: usize,
pub edge_count: usize,
}
pub fn run(out: &mut dyn Write, args: &GraphArgs) -> Result<GraphReport, CliError> {
let content = std::fs::read_to_string(&args.manifest_path)
.map_err(|err| CliError::io(&args.manifest_path, err))?;
let manifest = Manifest::from_yaml_str(&content)?;
manifest.validate()?;
let base_dir = base_dir_of(&args.manifest_path);
let loader = FsModuleLoader;
let expanded = manifest.expand(&base_dir, &loader)?;
expanded.validate()?;
let (graph, _construction_diagnostics) = DataflowGraph::from_manifest(&expanded)?;
let rendered = match args.format {
GraphFormat::Mermaid => astrs_graph::to_mermaid(&graph),
GraphFormat::Dot => astrs_graph::to_dot(&graph),
GraphFormat::Html => render_html(&astrs_graph::to_mermaid(&graph), &args.manifest_path),
};
writeln!(out, "{rendered}").map_err(|e| CliError::io("<output>", e))?;
Ok(GraphReport {
rendered,
node_count: graph.node_count(),
edge_count: graph.edge_count(),
})
}
fn escape_html(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
fn render_html(mermaid_source: &str, manifest_path: &Path) -> String {
let title = escape_html(&manifest_path.display().to_string());
format!(
"<!doctype html>\n\
<html lang=\"en\">\n\
<head>\n\
<meta charset=\"utf-8\">\n\
<title>AstRS graph: {title}</title>\n\
<style>\n\
body {{ font-family: system-ui, sans-serif; margin: 2rem; background: #0b0f14; color: #e6edf3; }}\n\
h1 {{ font-size: 1.1rem; font-weight: 600; }}\n\
p.note {{ color: #9aa7b1; font-size: 0.9rem; }}\n\
pre {{ background: #11161c; border: 1px solid #232a32; border-radius: 8px; padding: 1rem; overflow-x: auto; white-space: pre; }}\n\
code {{ font-family: ui-monospace, Menlo, Consolas, monospace; }}\n\
</style>\n\
</head>\n\
<body>\n\
<h1>AstRS dataflow graph — {title}</h1>\n\
<p class=\"note\">Generated by <code>astrs graph --html</code> (blueprint §17). This page embeds the raw mermaid\n\
source below and does not fetch a renderer from a CDN — paste it into any mermaid-capable viewer\n\
(GitHub/GitLab markdown, the mermaid Live Editor, or a Claude/ChatGPT artifact) to see the diagram.</p>\n\
<pre><code>{}</code></pre>\n\
</body>\n\
</html>\n",
escape_html(mermaid_source)
)
}
fn base_dir_of(manifest_path: &Path) -> PathBuf {
match manifest_path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
_ => PathBuf::from("."),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn write_temp(name: &str, content: &str) -> PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"astrs-cli-graph-test-{}-{name}-{n}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("root.yaml");
std::fs::write(&path, content).unwrap();
path
}
fn two_node_manifest() -> PathBuf {
write_temp(
"two-node",
"nodes:\n - id: camera\n path: ./camera\n outputs: [frames]\n - id: detector\n path: ./detector\n inputs:\n frames: camera/frames\n",
)
}
#[test]
fn mermaid_format_contains_both_node_ids() {
let mut out = Vec::new();
let report = run(
&mut out,
&GraphArgs {
manifest_path: two_node_manifest(),
format: GraphFormat::Mermaid,
},
)
.unwrap();
assert_eq!(report.node_count, 2);
assert_eq!(report.edge_count, 1);
assert!(report.rendered.contains("camera"));
assert!(report.rendered.contains("detector"));
assert!(report.rendered.contains("flowchart"));
}
#[test]
fn dot_format_starts_with_digraph_and_has_exactly_one_edge() {
let mut out = Vec::new();
let report = run(
&mut out,
&GraphArgs {
manifest_path: two_node_manifest(),
format: GraphFormat::Dot,
},
)
.unwrap();
assert!(
report.rendered.starts_with("digraph astrs {"),
"rendered was:\n{}",
report.rendered
);
assert!(report.rendered.contains("camera"));
assert!(report.rendered.contains("detector"));
assert_eq!(report.rendered.matches(" -> ").count(), 1);
}
#[test]
fn html_format_embeds_the_mermaid_source_and_escapes_it() {
let mut out = Vec::new();
let report = run(
&mut out,
&GraphArgs {
manifest_path: two_node_manifest(),
format: GraphFormat::Html,
},
)
.unwrap();
assert!(report.rendered.starts_with("<!doctype html>"));
assert!(report.rendered.contains("<pre><code>"));
assert!(report.rendered.contains("camera"));
assert!(!report.rendered.contains("cdn"));
assert!(!report.rendered.to_lowercase().contains("<script"));
}
#[test]
fn escape_html_handles_ampersand_before_angle_brackets() {
assert_eq!(escape_html("a & b < c > d"), "a & b < c > d");
assert_eq!(escape_html("<"), "<");
}
#[test]
fn missing_file_is_an_io_error() {
let mut out = Vec::new();
let err = run(
&mut out,
&GraphArgs {
manifest_path: std::env::temp_dir().join("astrs-cli-graph-does-not-exist.yaml"),
format: GraphFormat::Mermaid,
},
)
.unwrap_err();
assert!(matches!(err, CliError::Io { .. }));
}
#[test]
fn output_is_deterministic_across_repeated_runs() {
let path = two_node_manifest();
let mut first = Vec::new();
let mut second = Vec::new();
run(
&mut first,
&GraphArgs {
manifest_path: path.clone(),
format: GraphFormat::Mermaid,
},
)
.unwrap();
run(
&mut second,
&GraphArgs {
manifest_path: path,
format: GraphFormat::Mermaid,
},
)
.unwrap();
assert_eq!(first, second);
}
}