quillmark-cli 0.145.1

Command-line interface for Quillmark, a schema-driven document framework
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 {
    /// Path to quill directory or .quill bundle
    #[arg(value_name = "QUILL_PATH")]
    quill: PathBuf,

    /// Path to a Markdown document (default: the quill's example, else its
    /// blank form)
    #[arg(value_name = "MARKDOWN_FILE")]
    markdown_file: Option<PathBuf>,

    /// Output file; its extension picks the format, and `-` writes to stdout
    /// (default: beside the document, else `<quill>.<format>`)
    #[arg(short, long, value_name = "FILE")]
    output: Option<PathBuf>,

    /// Output format: pdf, svg, png, docx (default: the -o extension when it
    /// names one, else pdf)
    #[arg(short, long, value_name = "FORMAT")]
    format: Option<String>,

    /// Render the blank form rather than the example
    #[arg(long)]
    blank: bool,

    /// A font file (.ttf, .otf, .ttc, .otc) for the host font library; repeat
    /// for more
    #[arg(long = "font", value_name = "FONT_FILE")]
    fonts: Vec<PathBuf>,

    /// The render date a `today` date renders as (default: the local date)
    #[arg(long, value_name = "YYYY-MM-DD")]
    today: Option<CalendarDate>,

    /// Pixels per inch for png output (default: 144); pdf, svg and docx ignore it
    #[arg(long, value_name = "PPI")]
    ppi: Option<f32>,

    /// The pdf and docx document title (default: the plate's own, else the
    /// quill's description); png and svg ignore it
    #[arg(long, value_name = "TITLE")]
    title: Option<String>,

    /// Print one JSON report on stdout and nothing else
    #[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) => {
            // Only a result carries `validate`'s warnings, and a failed render
            // may be failing on the input they name.
            let unclaimed = quill
                .validate(&document)
                .into_iter()
                .filter(|d| d.severity == Severity::Warning);
            said.extend(unclaimed);
            // A failed render carries the warnings raised before it, which
            // print with the others, ahead of its errors.
            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 {
        // Every page numbered, page one included: an unnumbered file beside
        // numbered ones reads as the whole document.
        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(())
}

/// `path` parsed against `quill`, beside its parse warnings.
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))
}

/// An `-o` extension that names a format is a second statement of it: it
/// supplies an omitted `-f` and must agree with a given one. Any other
/// extension needs `-f`, and the file is then written as given.
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)),
    }
}