use std::{
io::Write,
path::{Path, PathBuf},
};
use toml_edit::{Item, TableLike, Value};
use crate::{
layout::LayoutReport,
operation::{self, OperationOptions},
output::{save_inner, Format},
Output, Result,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{
codec::{choice, invalid, Codec},
source, Bindings, Recipe,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RunAction {
Image,
Layout,
}
choice!(RunAction {Image=>"image",Layout=>"layout"});
impl std::str::FromStr for RunAction {
type Err = crate::Error;
fn from_str(value: &str) -> Result<Self> {
Self::decode(&Item::Value(value.into()), None)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum RunResult {
Image(Output),
Layout(LayoutReport),
}
#[derive(Default)]
#[must_use]
pub struct RunOptions<'a> {
bindings: Option<&'a Bindings<'a>>,
action: Option<RunAction>,
output: Option<PathBuf>,
layout_writer: Option<&'a mut dyn Write>,
}
impl<'a> RunOptions<'a> {
pub fn bindings(mut self, bindings: &'a Bindings<'a>) -> Self {
self.bindings = Some(bindings);
self
}
pub const fn action(mut self, action: RunAction) -> Self {
self.action = Some(action);
self
}
pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
self.output = Some(path.into());
self
}
pub fn layout_writer(mut self, writer: &'a mut dyn Write) -> Self {
self.layout_writer = Some(writer);
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
#[expect(
clippy::large_enum_variant,
reason = "a single call-local publication declaration needs no heap indirection"
)]
pub enum OutputDeclaration {
Image {
path: PathBuf,
format: Format,
},
Layout {
path: Option<PathBuf>,
},
}
impl OutputDeclaration {
pub fn image(path: impl Into<PathBuf>, format: impl Into<Format>) -> Self {
Self::Image {
path: path.into(),
format: format.into(),
}
}
pub fn layout(path: Option<PathBuf>) -> Self {
Self::Layout { path }
}
}
#[derive(Default)]
struct Settings<'a> {
action: Option<RunAction>,
image: Option<PathBuf>,
layout: Option<PathBuf>,
image_options: Option<&'a Item>,
}
fn path_field(fields: &dyn TableLike, name: &str) -> Result<Option<PathBuf>> {
fields
.get(name)
.map(|item| {
let path = item
.as_str()
.filter(|path| !path.is_empty())
.ok_or_else(|| invalid(format!("{name} requires a nonempty local path")))?;
Ok(PathBuf::from(path))
})
.transpose()
}
const OUTPUT_FIELDS: &[grammar::Field] = &[
grammar::optional::<RunAction>("action"),
grammar::custom(
"image",
false,
|_| serde_json::json!({"type":"string","minLength":1}),
),
grammar::custom(
"layout",
false,
|_| serde_json::json!({"type":"string","minLength":1}),
),
grammar::optional::<Format>("image_options"),
];
pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, OUTPUT_FIELDS)
}
impl<'a> Settings<'a> {
fn read(item: Option<&'a Item>) -> Result<Self> {
let Some(item) = item else {
return Ok(Self::default());
};
let fields = grammar::record_fields(item, OUTPUT_FIELDS)?;
let settings = Self {
action: fields
.get("action")
.map(|item| RunAction::decode(item, None))
.transpose()?,
image: path_field(fields, "image")?,
layout: path_field(fields, "layout")?,
image_options: fields.get("image_options"),
};
if let Some(options) = settings.image_options {
let inferred = settings
.image
.as_ref()
.and_then(|path| Format::from_path(path).ok());
let _ = Format::decode(options, inferred)
.map_err(|error| error.with_prefix("image_options"))?;
}
Ok(settings)
}
fn destination(
&self,
action: RunAction,
override_path: Option<PathBuf>,
base: &Path,
) -> Result<Option<PathBuf>> {
if override_path.is_some() {
return Ok(override_path);
}
let path = match action {
RunAction::Image => &self.image,
RunAction::Layout => &self.layout,
};
path.as_ref()
.map(|path| source::expand_path(path, base))
.transpose()
}
fn format(&self, destination: &Path) -> Result<Format> {
let inferred = self
.image
.as_ref()
.and_then(|path| Format::from_path(path).ok())
.or_else(|| Format::from_path(destination).ok());
if let Some(options) = self.image_options {
if options.get("device").is_none() && inferred.is_none() {
return Err(invalid(
"image output requires an explicit device or an SVG/PNG filename",
));
}
return Format::decode(options, inferred)
.map_err(|error| error.with_prefix("image_options"));
}
inferred.ok_or_else(|| {
invalid("image output requires an explicit device or an SVG/PNG filename")
})
}
}
pub(super) fn validate_output(item: Option<&Item>) -> Result<()> {
Settings::read(item)
.map(drop)
.map_err(|error| error.with_prefix("output"))
}
pub(super) fn rebase_output(item: &mut Item, base: &Path) -> Result<()> {
let fields = item
.as_table_like_mut()
.ok_or_else(|| invalid("output must be a table"))?;
for name in ["image", "layout"] {
if let Some(path) = fields.get_mut(name) {
let rebased = source::rebase(
Path::new(path.as_str().expect("validated destination")),
base,
);
*path = path_item(&rebased)?;
}
}
Ok(())
}
fn path_item(path: &Path) -> Result<Item> {
let path = path
.to_str()
.filter(|path| !path.is_empty())
.ok_or_else(|| invalid("output path requires nonempty Unicode"))?;
Ok(toml_edit::value(path))
}
fn declared_path(path: &Path, base: &Path) -> Result<Item> {
if path.as_os_str().is_empty() {
return Err(invalid("output path must not be empty"));
}
path_item(&source::rebase(path, base))
}
impl Recipe {
pub fn set_output(&mut self, declaration: OutputDeclaration) -> Result<()> {
let directory = std::env::current_dir()?;
let mut document = self.document.clone();
if document.get("output").is_none() {
document["output"] = Item::Table(toml_edit::Table::new());
}
let fields = document["output"]
.as_table_like_mut()
.expect("validated output table");
let action = match declaration {
OutputDeclaration::Image { path, format } => {
format.validate()?;
fields.insert("image", declared_path(&path, &directory)?);
fields.insert("image_options", Item::Value(format.encode()));
RunAction::Image
}
OutputDeclaration::Layout { path } => {
if let Some(path) = path {
fields.insert("layout", declared_path(&path, &directory)?);
} else {
fields.remove("layout");
}
RunAction::Layout
}
};
fields.insert("action", Item::Value(action.encode()));
self.install(document)
}
pub fn run(&self) -> Result<RunResult> {
self.run_with(RunOptions::default())
}
pub fn run_with(&self, options: RunOptions<'_>) -> Result<RunResult> {
self.run_with_operation(options, &OperationOptions::default())
}
pub fn run_with_operation(
&self,
options: RunOptions<'_>,
operation: &OperationOptions,
) -> Result<RunResult> {
operation::run(operation, || self.run_inner(options))
}
fn run_inner(&self, options: RunOptions<'_>) -> Result<RunResult> {
let settings = Settings::read(self.document.get("output"))?;
let action = options.action.or(settings.action).ok_or_else(|| {
invalid("recipe execution requires an explicit action (image or layout)")
})?;
let destination = settings.destination(action, options.output, &self.base)?;
let default = Bindings::new();
let bindings = options.bindings.unwrap_or(&default);
match action {
RunAction::Layout => {
let report = self.layout_source(bindings)?.recipe_layout_report()?;
if destination.is_some() || options.layout_writer.is_some() {
operation::phase(crate::errors::OperationPhase::Write)?;
let mut json = report.to_json()?;
json.push('\n');
if let Some(path) = destination {
crate::orchestrator::write_atomic(&path, json.as_bytes())?;
} else if let Some(writer) = options.layout_writer {
crate::output::write_stream(writer, json.as_bytes())?;
}
}
Ok(RunResult::Layout(report))
}
RunAction::Image => {
let destination = destination
.ok_or_else(|| invalid("image action requires an output destination"))?;
let format = settings.format(&destination)?;
let output = if self.document.get("base").is_some() {
let composite = self.composition_inner(bindings)?.compose_inner()?;
save_inner(&composite, &destination, &format)?
} else {
if self.document.get("placements").is_some() {
return Err(invalid(
"image action for placement declarations requires an explicit base",
));
}
let figure = self.build_inner(bindings)?;
save_inner(&figure, &destination, &format)?
};
Ok(RunResult::Image(output))
}
}
}
}