Skip to main content

mdbook_embedify/
cli.rs

1use clap::{Arg, ArgMatches, Command};
2use mdbook_preprocessor::Preprocessor;
3use std::{
4    io::{self, IsTerminal},
5    process,
6};
7
8pub struct Cli {
9    pub matches: ArgMatches,
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        
25        // If no subcommand provided and stdin is a terminal, print help
26        if matches.subcommand().is_none() && io::stdin().is_terminal() {
27            cmd.clone().print_help().unwrap();
28            process::exit(1);
29        }
30
31        Self { matches }
32    }
33
34    pub fn reply_supports(&self, pre: &dyn Preprocessor) {
35        if let Some(sub_args) = self.matches.subcommand_matches("supports") {
36            // get the renderer
37            let renderer = sub_args.get_one::<String>("renderer").unwrap();
38
39            // signal whether the renderer is supported by exiting with 1 or 0.
40            match pre.supports_renderer(renderer) {
41                Ok(true) => process::exit(0),
42                Ok(false) => process::exit(1),
43                Err(_) => process::exit(1),
44            }
45        }
46    }
47}