Generate metadata from clap?

Is there some clap feature or crate that can iterate over clap arguments/subcommands and save them to some machine-readable format?

XY: I have a cli administration tool that is well documented, but the client also wants that documentation in the form of a "Command Reference" pdf. The tool is way too big to do a manual conversion and also keep the tool and book in sync going forward, so I would like to be able to generate the documentation (or at least output the data to a format that can be easily transformed into typst code) from the cli tool.

You should be able to use Clap's Command::get_opts method as a starting point, at least. Something like:

use clap::Parser;

#[derive(Parser)]
struct Opt {
    #[clap(short = 'f', long = "some-flag")]
    flag: bool,
}

fn main() {
    use clap::CommandFactory;

    for arg in Opt::command().get_opts() {
        dbg!(arg);
    }
}
1 Like

Traditionally on Unix that kind of command reference is what a man page is, you should be able to use clap_mangen - Rust to generate the source for a man page from a clap Command, then you can use groff and man to convert the man page to a PDF.

So, assuming you implemented a --generate-man-page command that runs clap_mangen):

cargo run -- generate-man-page | man -Tpdf -l - > your_command.pdf

that requires groff to be fully installed (not just the groff-base package), so on Debian (and derivatives):

sudo apt install groff man-db
3 Likes

This is exactly what I was hoping existed -- thank you!

1 Like