use clap::{Arg, ArgMatches, Command};
use mdbook_preprocessor::{Preprocessor, errors::Result, parse_input};
use semver::{Version, VersionReq};
use std::{io, process};
pub fn run(preprocessor: impl Preprocessor, description: &'static str) -> Result<()> {
let name = preprocessor.name().to_string();
let args = Command::new(name)
.about(description)
.subcommand(
Command::new("supports")
.arg(Arg::new("renderer").required(true))
.about("Check whether a renderer is supported by this preprocessor"),
)
.get_matches();
if let Some(supports) = args.subcommand_matches("supports") {
handle_supports(preprocessor, supports);
} else {
handle_preprocessing(preprocessor)
}
}
fn handle_preprocessing(pre: impl Preprocessor) -> Result<()> {
let (ctx, book) = parse_input(io::stdin())?;
let book_version = Version::parse(&ctx.mdbook_version)?;
let version_req = VersionReq::parse(mdbook_preprocessor::MDBOOK_VERSION)?;
if !version_req.matches(&book_version) {
eprintln!(
"Warning: The {} plugin was built against version {} of mdbook, \
but we're being called from version {}",
pre.name(),
mdbook_preprocessor::MDBOOK_VERSION,
ctx.mdbook_version
);
}
let processed_book = pre.run(&ctx, book)?;
let out = serde_json::to_string(&processed_book)?;
println!("{}", out);
Ok(())
}
fn handle_supports(pre: impl Preprocessor, sub_args: &ArgMatches) -> ! {
let renderer = sub_args
.get_one::<String>("renderer")
.expect("Required argument");
let supported = pre.supports_renderer(renderer);
if matches!(supported, Ok(true)) {
process::exit(0);
} else {
process::exit(1);
}
}