use crate::commands::{Refused, load_quill, read_fonts, render_date};
use crate::errors::{CliError, Result};
use crate::output::{page_output_path, print_report, write_file, write_stdout};
use clap::Parser;
use quillmark::{
CalendarDate, Diagnostic, Document, Engine, OutputFormat, RenderError, RenderOptions, Report,
ReportDiagnostic, Severity,
};
use std::path::{Path, PathBuf};
#[derive(Parser)]
pub struct RenderArgs {
#[arg(value_name = "QUILL_PATH")]
quill: PathBuf,
#[arg(value_name = "MARKDOWN_FILE")]
markdown_file: Option<PathBuf>,
#[arg(short, long, value_name = "FILE")]
output: Option<PathBuf>,
#[arg(short, long, value_name = "FORMAT")]
format: Option<String>,
#[arg(long)]
blank: bool,
#[arg(long = "font", value_name = "FONT_FILE")]
fonts: Vec<PathBuf>,
#[arg(long, value_name = "YYYY-MM-DD")]
today: Option<CalendarDate>,
#[arg(long, value_name = "PPI")]
ppi: Option<f32>,
#[arg(long, value_name = "TITLE")]
title: Option<String>,
#[arg(long)]
json: bool,
#[command(flatten)]
gone: Refused,
}
pub fn execute(args: RenderArgs) -> Result<()> {
args.gone.refuse()?;
let json = args.json;
let stdout = args.output.as_deref() == Some(Path::new("-"));
if stdout && json {
return Err(CliError::InvalidArgument(
"--json and -o - both write to stdout: drop one".to_string(),
));
}
if args.blank && args.markdown_file.is_some() {
return Err(CliError::InvalidArgument(
"--blank renders the blank form, and a document was named".to_string(),
));
}
let output_format = resolve_format(
args.format.as_deref(),
args.output.as_deref().filter(|_| !stdout),
)?;
if let Some(out) = args.output.as_deref().filter(|_| !stdout)
&& out.is_dir()
{
return Err(CliError::InvalidArgument(format!(
"-o names a file, and {} is a directory: give -o {}",
out.display(),
out.join(format!("<name>.{output_format}")).display()
)));
}
let today = render_date(args.today);
let quill = load_quill(&args.quill)?;
let (document, mut said) = match args.markdown_file.as_deref() {
Some(path) => read_document(&quill, path)?,
None if !args.blank => match quill.example_document() {
Some(example) => (example, Vec::new()),
None => (quill.seed_document(), Vec::new()),
},
None => (quill.seed_document(), Vec::new()),
};
let mut options = RenderOptions::default().with_output_format(output_format);
options.ppi = args.ppi;
options.title = args.title;
let engine = Engine::with_fonts(read_fonts(&args.fonts)?)?;
let result = match engine.render(&quill, &document, today, &options) {
Ok(result) => result,
Err(e) => {
let unclaimed = quill
.validate(&document)
.into_iter()
.filter(|d| d.severity == Severity::Warning);
said.extend(unclaimed);
let (errors, warnings): (Vec<_>, Vec<_>) = e
.into_diagnostics()
.into_iter()
.partition(|d| d.severity == Severity::Error);
said.extend(warnings);
said.extend(errors);
if json {
print_report(&Report {
ok: false,
diagnostics: said.iter().map(ReportDiagnostic::from).collect(),
..Report::default()
});
return Err(CliError::Reported);
}
return Err(CliError::Render(RenderError::new(said)));
}
};
said.extend(result.warnings);
if result.artifacts.is_empty() {
return Err(CliError::Render(RenderError::coded(
"check::document_failed",
"the render produced nothing",
)));
}
let mut files = Vec::new();
if stdout {
if result.artifacts.len() > 1 {
return Err(CliError::InvalidArgument(format!(
"{} renders {} pages, one file each, and -o - carries one; give -o a file to write the pages",
output_format,
result.artifacts.len()
)));
}
crate::errors::print_warnings(&said);
write_stdout(&result.artifacts[0].bytes)?;
return Ok(());
}
let output_path = args.output.unwrap_or_else(|| match &args.markdown_file {
Some(path) => path.with_extension(output_format.as_str()),
None => PathBuf::from(format!("{}.{}", quill.name(), output_format)),
});
if let [artifact] = result.artifacts.as_slice() {
write_file(&output_path, &artifact.bytes)?;
files.push(output_path);
} else {
for (i, artifact) in result.artifacts.iter().enumerate() {
let path = page_output_path(&output_path, i + 1);
write_file(&path, &artifact.bytes)?;
files.push(path);
}
}
let files: Vec<String> = files.iter().map(|f| f.display().to_string()).collect();
if json {
print_report(&Report {
ok: true,
files,
diagnostics: said.iter().map(ReportDiagnostic::from).collect(),
next: None,
});
} else {
crate::errors::print_warnings(&said);
for file in files {
println!("{file}");
}
}
Ok(())
}
fn read_document(quill: &quillmark::Quill, path: &Path) -> Result<(Document, Vec<Diagnostic>)> {
if !path.exists() {
return Err(CliError::InvalidArgument(format!(
"{} does not exist",
path.display()
)));
}
let output = quill.parse(&std::fs::read_to_string(path)?)?;
Ok((output.document, output.warnings))
}
fn resolve_format(flag: Option<&str>, output: Option<&Path>) -> Result<OutputFormat> {
let flag = flag
.map(str::parse::<OutputFormat>)
.transpose()
.map_err(|e| CliError::InvalidArgument(e.to_string()))?;
let named = output.and_then(|path| {
let format = path.extension()?.to_str()?.parse::<OutputFormat>().ok()?;
Some((format, path))
});
match (flag, named) {
(Some(flag), Some((named, path))) if flag != named => {
Err(CliError::InvalidArgument(format!(
"-f {flag} disagrees with -o {}, which names {named}; \
drop -f to write {named}, or give -o a .{flag} extension",
path.display()
)))
}
(None, None) if let Some(path) = output => Err(CliError::InvalidArgument(format!(
"-o {} names no format: give it a .pdf, .docx, .png or .svg extension, or pass -f",
path.display()
))),
(flag, named) => Ok(flag
.or(named.map(|(format, _)| format))
.unwrap_or(OutputFormat::Pdf)),
}
}