astrs_cli/command/
graph.rs1use std::io::Write;
5use std::path::{Path, PathBuf};
6
7use astrs_graph::DataflowGraph;
8use astrs_manifest::Manifest;
9use astrs_manifest::expand::FsModuleLoader;
10
11use crate::error::CliError;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum GraphFormat {
16 Mermaid,
19 Dot,
21 Html,
25}
26
27#[derive(Debug, Clone)]
29pub struct GraphArgs {
30 pub manifest_path: PathBuf,
32 pub format: GraphFormat,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct GraphReport {
39 pub rendered: String,
43 pub node_count: usize,
45 pub edge_count: usize,
47}
48
49pub fn run(out: &mut dyn Write, args: &GraphArgs) -> Result<GraphReport, CliError> {
60 let content = std::fs::read_to_string(&args.manifest_path)
61 .map_err(|err| CliError::io(&args.manifest_path, err))?;
62 let manifest = Manifest::from_yaml_str(&content)?;
63 manifest.validate()?;
64
65 let base_dir = base_dir_of(&args.manifest_path);
66 let loader = FsModuleLoader;
67 let expanded = manifest.expand(&base_dir, &loader)?;
68 expanded.validate()?;
69
70 let (graph, _construction_diagnostics) = DataflowGraph::from_manifest(&expanded)?;
71
72 let rendered = match args.format {
73 GraphFormat::Mermaid => astrs_graph::to_mermaid(&graph),
74 GraphFormat::Dot => astrs_graph::to_dot(&graph),
75 GraphFormat::Html => render_html(&astrs_graph::to_mermaid(&graph), &args.manifest_path),
76 };
77
78 writeln!(out, "{rendered}").map_err(|e| CliError::io("<output>", e))?;
79
80 Ok(GraphReport {
81 rendered,
82 node_count: graph.node_count(),
83 edge_count: graph.edge_count(),
84 })
85}
86
87fn escape_html(text: &str) -> String {
93 text.replace('&', "&")
94 .replace('<', "<")
95 .replace('>', ">")
96}
97
98fn render_html(mermaid_source: &str, manifest_path: &Path) -> String {
108 let title = escape_html(&manifest_path.display().to_string());
109 format!(
110 "<!doctype html>\n\
111<html lang=\"en\">\n\
112<head>\n\
113<meta charset=\"utf-8\">\n\
114<title>AstRS graph: {title}</title>\n\
115<style>\n\
116body {{ font-family: system-ui, sans-serif; margin: 2rem; background: #0b0f14; color: #e6edf3; }}\n\
117h1 {{ font-size: 1.1rem; font-weight: 600; }}\n\
118p.note {{ color: #9aa7b1; font-size: 0.9rem; }}\n\
119pre {{ background: #11161c; border: 1px solid #232a32; border-radius: 8px; padding: 1rem; overflow-x: auto; white-space: pre; }}\n\
120code {{ font-family: ui-monospace, Menlo, Consolas, monospace; }}\n\
121</style>\n\
122</head>\n\
123<body>\n\
124<h1>AstRS dataflow graph — {title}</h1>\n\
125<p class=\"note\">Generated by <code>astrs graph --html</code> (blueprint §17). This page embeds the raw mermaid\n\
126source below and does not fetch a renderer from a CDN — paste it into any mermaid-capable viewer\n\
127(GitHub/GitLab markdown, the mermaid Live Editor, or a Claude/ChatGPT artifact) to see the diagram.</p>\n\
128<pre><code>{}</code></pre>\n\
129</body>\n\
130</html>\n",
131 escape_html(mermaid_source)
132 )
133}
134
135fn base_dir_of(manifest_path: &Path) -> PathBuf {
137 match manifest_path.parent() {
138 Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
139 _ => PathBuf::from("."),
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
146 use super::*;
147
148 fn write_temp(name: &str, content: &str) -> PathBuf {
149 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
157 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
158 let dir = std::env::temp_dir().join(format!(
159 "astrs-cli-graph-test-{}-{name}-{n}",
160 std::process::id()
161 ));
162 std::fs::create_dir_all(&dir).unwrap();
163 let path = dir.join("root.yaml");
164 std::fs::write(&path, content).unwrap();
165 path
166 }
167
168 fn two_node_manifest() -> PathBuf {
169 write_temp(
170 "two-node",
171 "nodes:\n - id: camera\n path: ./camera\n outputs: [frames]\n - id: detector\n path: ./detector\n inputs:\n frames: camera/frames\n",
172 )
173 }
174
175 #[test]
176 fn mermaid_format_contains_both_node_ids() {
177 let mut out = Vec::new();
178 let report = run(
179 &mut out,
180 &GraphArgs {
181 manifest_path: two_node_manifest(),
182 format: GraphFormat::Mermaid,
183 },
184 )
185 .unwrap();
186 assert_eq!(report.node_count, 2);
187 assert_eq!(report.edge_count, 1);
188 assert!(report.rendered.contains("camera"));
189 assert!(report.rendered.contains("detector"));
190 assert!(report.rendered.contains("flowchart"));
191 }
192
193 #[test]
194 fn dot_format_starts_with_digraph_and_has_exactly_one_edge() {
195 let mut out = Vec::new();
196 let report = run(
197 &mut out,
198 &GraphArgs {
199 manifest_path: two_node_manifest(),
200 format: GraphFormat::Dot,
201 },
202 )
203 .unwrap();
204 assert!(
209 report.rendered.starts_with("digraph astrs {"),
210 "rendered was:\n{}",
211 report.rendered
212 );
213 assert!(report.rendered.contains("camera"));
214 assert!(report.rendered.contains("detector"));
215 assert_eq!(report.rendered.matches(" -> ").count(), 1);
220 }
221
222 #[test]
223 fn html_format_embeds_the_mermaid_source_and_escapes_it() {
224 let mut out = Vec::new();
225 let report = run(
226 &mut out,
227 &GraphArgs {
228 manifest_path: two_node_manifest(),
229 format: GraphFormat::Html,
230 },
231 )
232 .unwrap();
233 assert!(report.rendered.starts_with("<!doctype html>"));
234 assert!(report.rendered.contains("<pre><code>"));
235 assert!(report.rendered.contains("camera"));
236 assert!(!report.rendered.contains("cdn"));
238 assert!(!report.rendered.to_lowercase().contains("<script"));
239 }
240
241 #[test]
242 fn escape_html_handles_ampersand_before_angle_brackets() {
243 assert_eq!(escape_html("a & b < c > d"), "a & b < c > d");
244 assert_eq!(escape_html("<"), "<");
246 }
247
248 #[test]
249 fn missing_file_is_an_io_error() {
250 let mut out = Vec::new();
251 let err = run(
252 &mut out,
253 &GraphArgs {
254 manifest_path: std::env::temp_dir().join("astrs-cli-graph-does-not-exist.yaml"),
255 format: GraphFormat::Mermaid,
256 },
257 )
258 .unwrap_err();
259 assert!(matches!(err, CliError::Io { .. }));
260 }
261
262 #[test]
263 fn output_is_deterministic_across_repeated_runs() {
264 let path = two_node_manifest();
265 let mut first = Vec::new();
266 let mut second = Vec::new();
267 run(
268 &mut first,
269 &GraphArgs {
270 manifest_path: path.clone(),
271 format: GraphFormat::Mermaid,
272 },
273 )
274 .unwrap();
275 run(
276 &mut second,
277 &GraphArgs {
278 manifest_path: path,
279 format: GraphFormat::Mermaid,
280 },
281 )
282 .unwrap();
283 assert_eq!(first, second);
284 }
285}