astrs-cli 0.1.0

The astrs command line: run, build, monitor, migrate and bridge robotic dataflows.
Documentation
//! `astrs graph` (blueprint ยง17): mermaid, DOT, or a self-contained HTML
//! page embedding the mermaid source, for a manifest's dataflow graph.

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;

/// Which format `astrs graph` renders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphFormat {
    /// Mermaid `flowchart` source (renders natively on GitHub/GitLab and
    /// in Claude/ChatGPT-style artifacts).
    Mermaid,
    /// Graphviz DOT source.
    Dot,
    /// A self-contained HTML page embedding the mermaid source in a
    /// `<pre>` block plus a plain-text note โ€” no CDN, no network fetch
    /// (blueprint: "single-file template, no CDN").
    Html,
}

/// Arguments for `astrs graph`.
#[derive(Debug, Clone)]
pub struct GraphArgs {
    /// The manifest file to visualize.
    pub manifest_path: PathBuf,
    /// The output format.
    pub format: GraphFormat,
}

/// The result of rendering one manifest's graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphReport {
    /// The rendered text โ€” mermaid source, DOT source, or the full HTML
    /// page, depending on [`GraphArgs::format`]. Exactly what was written
    /// to the output sink.
    pub rendered: String,
    /// How many nodes the graph has.
    pub node_count: usize,
    /// How many edges the graph has.
    pub edge_count: usize,
}

/// Run `astrs graph`: parse, validate, expand, build the dataflow graph,
/// and print it in the requested format.
///
/// Aborts outright (like `expand`, unlike `validate`) on any pipeline
/// failure โ€” see `command::expand`'s own docs for why.
///
/// # Errors
///
/// See [`crate::command::expand::run`]'s error docs; the same pipeline
/// runs here before rendering.
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(),
    })
}

/// Escape `text` for safe embedding as the text content of an HTML
/// element (inside a `<pre>` block, never inside an attribute โ€” this
/// module never needs quote-escaping because it never places `text`
/// inside a quoted attribute value). Order matters: `&` must be escaped
/// first, or a later `&lt;` would itself get re-escaped into `&amp;lt;`.
fn escape_html(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Render a self-contained HTML page embedding `mermaid_source` in a
/// `<pre>` block.
///
/// Deliberately does **not** fetch the mermaid.js library from a CDN โ€”
/// blueprint ยง17 asks for "a single-file template, no CDN"; this renders
/// the mermaid *source* readably (for copy/paste into a renderer that has
/// it) rather than attempting a network fetch this tool must never
/// perform. A future revision may inline a vendored mermaid runtime; this
/// one is deliberately the honest, always-correct fallback.
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 &mdash; {title}</h1>\n\
<p class=\"note\">Generated by <code>astrs graph --html</code> (blueprint &sect;17). This page embeds the raw mermaid\n\
source below and does not fetch a renderer from a CDN &mdash; 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)
    )
}

/// See `command::validate::base_dir_of`.
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 {
        // A monotonic counter, not just `(pid, name)`, disambiguates the
        // directory: `name` alone collides whenever two *tests* share one
        // fixture-producing helper (e.g. `two_node_manifest` below, called
        // from four different `#[test]` functions) -- cargo's default
        // multi-threaded test runner executes those concurrently within
        // this one process, so a shared, non-unique path is a genuine
        // (observed) race, not just a naming nicety.
        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();
        // `"digraph" || "graph"` would be near-tautological (the first
        // literally contains the second) -- assert the real, doc-tested
        // `astrs_graph::to_dot` contract instead: it always starts with
        // this exact preamble.
        assert!(
            report.rendered.starts_with("digraph astrs {"),
            "rendered was:\n{}",
            report.rendered
        );
        assert!(report.rendered.contains("camera"));
        assert!(report.rendered.contains("detector"));
        // `two_node_manifest` wires exactly one edge (`camera/frames` into
        // `detector`'s `frames` input); `" -> "` is DOT's edge operator
        // and appears nowhere else in this emitter's output (node/cluster
        // declarations never contain it).
        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"));
        // Never fetches anything.
        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 &amp; b &lt; c &gt; d");
        // Order matters: a literal `<` must not become `&amp;lt;`.
        assert_eq!(escape_html("<"), "&lt;");
    }

    #[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);
    }
}