use std::io::Write as _;
use std::process::{Command, Stdio};
use crate::directives::{first_lines, html_escape};
use crate::error::CompilerError;
use crate::fences::Directive;
use crate::BuildContext;
pub(crate) fn diagram(d: &Directive, _ctx: &BuildContext) -> Result<String, CompilerError> {
let mut command = Command::new("d2");
command
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if let Some(layout) = d.attr("layout") {
command.arg("--layout").arg(layout);
}
let mut child = command.spawn().map_err(|source| CompilerError::Diagram {
detail: format!("cannot spawn `d2` (is it on PATH?): {source}"),
})?;
let stdin_result = match child.stdin.take() {
Some(mut stdin) => stdin
.write_all(d.body.as_bytes())
.map_err(|e| e.to_string()),
None => Err("d2 stdin was already taken".to_string()),
};
let output = child
.wait_with_output()
.map_err(|source| CompilerError::Diagram {
detail: format!("d2 did not run to completion: {source}"),
})?;
let stderr = String::from_utf8_lossy(&output.stderr);
if let Err(write_error) = stdin_result {
return Err(CompilerError::Diagram {
detail: format!("writing the diagram source failed: {write_error}"),
});
}
if !output.status.success() {
return Err(CompilerError::Diagram {
detail: format!("d2 exited with {}: {}", output.status, first_lines(&stderr)),
});
}
let svg = String::from_utf8(output.stdout).map_err(|_| CompilerError::Diagram {
detail: "d2 produced non-UTF-8 output".to_string(),
})?;
if svg.trim().is_empty() {
return Err(CompilerError::Diagram {
detail: "d2 produced no output".to_string(),
});
}
let caption = d
.attr("caption")
.map(|c| format!("<figcaption>{}</figcaption>", html_escape(c)))
.unwrap_or_default();
Ok(format!(
"<figure class=\"docs-diagram\" data-tool=\"d2\">{svg}{caption}</figure>"
))
}