libreoffice-pure 0.3.3

Pure-Rust LibreOffice-compatible document generation CLI
Documentation
//! `libreoffice-pure` CLI: thin wrapper over the high-level helpers in
//! `libreoffice_pure` (the lib target of this crate).

use std::env;
use std::fs;
use std::process::ExitCode;

use libreoffice_pure::{
    accept_all_tracked_changes_docx_bytes, doc_to_docx_bytes, docx_to_pdf_bytes, pptx_to_pdf_bytes,
    xlsx_recalc_bytes,
};

fn main() -> ExitCode {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        print_usage();
        return ExitCode::FAILURE;
    }
    match run(&args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::FAILURE
        }
    }
}

fn run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let cmd = args[1].as_str();
    match cmd {
        "docx-to-pdf" => convert(args, docx_to_pdf_bytes),
        "doc-to-docx" => convert(args, doc_to_docx_bytes),
        "pptx-to-pdf" => convert(args, pptx_to_pdf_bytes),
        "xlsx-recalc" => convert(args, xlsx_recalc_bytes),
        "accept-changes" => convert(args, accept_all_tracked_changes_docx_bytes),
        "help" | "--help" | "-h" => {
            print_usage();
            Ok(())
        }
        other => {
            print_usage();
            Err(format!("unknown command: {other}").into())
        }
    }
}

fn convert<F>(args: &[String], handler: F) -> Result<(), Box<dyn std::error::Error>>
where
    F: Fn(&[u8]) -> lo_core::Result<Vec<u8>>,
{
    if args.len() < 4 {
        return Err("expected: <input> <output>".into());
    }
    let input = &args[2];
    let output = &args[3];
    let bytes = fs::read(input)?;
    let out = handler(&bytes)?;
    fs::write(output, out)?;
    Ok(())
}

fn print_usage() {
    eprintln!(
        "usage:
  libreoffice-pure docx-to-pdf <input.docx> <output.pdf>
  libreoffice-pure doc-to-docx <input.doc> <output.docx>
  libreoffice-pure pptx-to-pdf <input.pptx> <output.pdf>
  libreoffice-pure xlsx-recalc <input.xlsx> <output.xlsx>
  libreoffice-pure accept-changes <input.docx> <output.docx>"
    );
}