Skip to main content

pimalaya_cli/clap/commands/
manual.rs

1use std::{fs, path::PathBuf};
2
3use anyhow::Result;
4use clap::{Command, Parser};
5use clap_mangen::Man;
6use log::info;
7
8use crate::{clap::parsers::path_parser, printer::Printer};
9
10/// Generate manual pages to the given directory.
11///
12/// This command allows you to generate manual pages (following the
13/// man page format) to the given directory. If the directory does not
14/// exist, it will be created. Any existing man pages will be
15/// overriden.
16#[derive(Debug, Parser)]
17pub struct ManualCommand {
18    /// Directory where man files should be generated in.
19    #[arg(value_parser = path_parser)]
20    pub dir: PathBuf,
21}
22
23impl ManualCommand {
24    /// Generates the man pages and reports how many landed where.
25    pub fn execute(self, printer: &mut impl Printer, command: Command) -> Result<()> {
26        let dir = &self.dir;
27        let cmd_name = command.get_name().to_string();
28        let subcmds = command.get_subcommands().cloned().collect::<Vec<_>>();
29        let subcmds_len = subcmds.len() + 1;
30
31        let mut buffer = Vec::new();
32        Man::new(command).render(&mut buffer)?;
33
34        fs::create_dir_all(dir)?;
35        info!("generate man page for command {cmd_name}");
36        fs::write(dir.join(format!("{}.1", cmd_name)), buffer)?;
37
38        for subcmd in subcmds {
39            let subcmd_name = subcmd.get_name().to_string();
40
41            let mut buffer = Vec::new();
42            Man::new(subcmd).render(&mut buffer)?;
43
44            info!("generate man page for subcommand {subcmd_name}");
45            fs::write(dir.join(format!("{}-{}.1", cmd_name, subcmd_name)), buffer)?;
46        }
47
48        printer.out(format!(
49            "{subcmds_len} man page(s) successfully generated in {}",
50            dir.display()
51        ))
52    }
53}