Skip to main content

astrs_cli/command/
graph.rs

1//! `astrs graph` (blueprint §17): mermaid, DOT, or a self-contained HTML
2//! page embedding the mermaid source, for a manifest's dataflow graph.
3
4use 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/// Which format `astrs graph` renders.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum GraphFormat {
16    /// Mermaid `flowchart` source (renders natively on GitHub/GitLab and
17    /// in Claude/ChatGPT-style artifacts).
18    Mermaid,
19    /// Graphviz DOT source.
20    Dot,
21    /// A self-contained HTML page embedding the mermaid source in a
22    /// `<pre>` block plus a plain-text note — no CDN, no network fetch
23    /// (blueprint: "single-file template, no CDN").
24    Html,
25}
26
27/// Arguments for `astrs graph`.
28#[derive(Debug, Clone)]
29pub struct GraphArgs {
30    /// The manifest file to visualize.
31    pub manifest_path: PathBuf,
32    /// The output format.
33    pub format: GraphFormat,
34}
35
36/// The result of rendering one manifest's graph.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct GraphReport {
39    /// The rendered text — mermaid source, DOT source, or the full HTML
40    /// page, depending on [`GraphArgs::format`]. Exactly what was written
41    /// to the output sink.
42    pub rendered: String,
43    /// How many nodes the graph has.
44    pub node_count: usize,
45    /// How many edges the graph has.
46    pub edge_count: usize,
47}
48
49/// Run `astrs graph`: parse, validate, expand, build the dataflow graph,
50/// and print it in the requested format.
51///
52/// Aborts outright (like `expand`, unlike `validate`) on any pipeline
53/// failure — see `command::expand`'s own docs for why.
54///
55/// # Errors
56///
57/// See [`crate::command::expand::run`]'s error docs; the same pipeline
58/// runs here before rendering.
59pub 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
87/// Escape `text` for safe embedding as the text content of an HTML
88/// element (inside a `<pre>` block, never inside an attribute — this
89/// module never needs quote-escaping because it never places `text`
90/// inside a quoted attribute value). Order matters: `&` must be escaped
91/// first, or a later `&lt;` would itself get re-escaped into `&amp;lt;`.
92fn escape_html(text: &str) -> String {
93    text.replace('&', "&amp;")
94        .replace('<', "&lt;")
95        .replace('>', "&gt;")
96}
97
98/// Render a self-contained HTML page embedding `mermaid_source` in a
99/// `<pre>` block.
100///
101/// Deliberately does **not** fetch the mermaid.js library from a CDN —
102/// blueprint §17 asks for "a single-file template, no CDN"; this renders
103/// the mermaid *source* readably (for copy/paste into a renderer that has
104/// it) rather than attempting a network fetch this tool must never
105/// perform. A future revision may inline a vendored mermaid runtime; this
106/// one is deliberately the honest, always-correct fallback.
107fn 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 &mdash; {title}</h1>\n\
125<p class=\"note\">Generated by <code>astrs graph --html</code> (blueprint &sect;17). This page embeds the raw mermaid\n\
126source below and does not fetch a renderer from a CDN &mdash; 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
135/// See `command::validate::base_dir_of`.
136fn 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        // A monotonic counter, not just `(pid, name)`, disambiguates the
150        // directory: `name` alone collides whenever two *tests* share one
151        // fixture-producing helper (e.g. `two_node_manifest` below, called
152        // from four different `#[test]` functions) -- cargo's default
153        // multi-threaded test runner executes those concurrently within
154        // this one process, so a shared, non-unique path is a genuine
155        // (observed) race, not just a naming nicety.
156        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        // `"digraph" || "graph"` would be near-tautological (the first
205        // literally contains the second) -- assert the real, doc-tested
206        // `astrs_graph::to_dot` contract instead: it always starts with
207        // this exact preamble.
208        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        // `two_node_manifest` wires exactly one edge (`camera/frames` into
216        // `detector`'s `frames` input); `" -> "` is DOT's edge operator
217        // and appears nowhere else in this emitter's output (node/cluster
218        // declarations never contain it).
219        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        // Never fetches anything.
237        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 &amp; b &lt; c &gt; d");
244        // Order matters: a literal `<` must not become `&amp;lt;`.
245        assert_eq!(escape_html("<"), "&lt;");
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}