Skip to main content

mdbook_embedify/
cli.rs

1use clap::{Arg, Command};
2use mdbook::preprocess::Preprocessor;
3use std::{
4    io::{self, IsTerminal},
5    process,
6};
7
8pub struct Cli {
9    pub cmd: Command,
10}
11
12impl Cli {
13    pub fn new() -> Self {
14        let cmd = Command::new("mdbook-embedify")
15            .version(env!("CARGO_PKG_VERSION"))
16            .about("A mdbook embed preprocessor that embeds app to your book")
17            .subcommand(
18                Command::new("supports")
19                    .arg(Arg::new("renderer").required(true))
20                    .about("Check whether a renderer is supported by this preprocessor"),
21            );
22
23        let matches = cmd.clone().get_matches();
24        if !matches.args_present() {
25            if io::stdin().is_terminal() {
26                cmd.clone().print_help().unwrap();
27                process::exit(1);
28            }
29        }
30
31        Self { cmd }
32    }
33
34    pub fn reply_supports(&self, pre: &dyn Preprocessor) {
35        let matches = self.cmd.clone().get_matches();
36        if let Some(sub_args) = matches.subcommand_matches("supports") {
37            // get the renderer
38            let renderer = sub_args.get_one::<String>("renderer").unwrap();
39
40            // signal whether the renderer is supported by exiting with 1 or 0.
41            if pre.supports_renderer(renderer) {
42                process::exit(0);
43            } else {
44                process::exit(1);
45            }
46        }
47    }
48}