Clap get help text as string for subcommand

I want to snapshot-test my CLI interface help text, but I can't figure out how to get the help text for a subcommand as string from clap. I managed to find I can use CommandFactory::command() to get Command, on which I can then call Command::render_long_help(), as seen in the code below. But that help text is the equivalent of my_prog --help, and I also need the equivalent of my_prog a --help, that will include the subcommands C, and D.

Google is basically useless as all the results are about specifying custom help text, not programmatically getting the derived one. Docs.rs got me Command::render_long_help(), but I don't see how that could used with a subcommand. I thought about just using Parser::parse_from, but that will just print the help itself (to stdout), and I need it in a String.

TLDR: I need this code to print help text about the C and D subcommands

use clap::{CommandFactory, Parser, Subcommand};

#[derive(Parser, Debug)]
#[clap(author, about)]
struct Opts {
    #[clap(subcommand)]
    command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
    /// this has subcommands
    #[clap(subcommand)]
    A(SubCommand),
    B,
}
#[derive(Subcommand, Debug)]
enum SubCommand {
    /// this should also be printed
    C,
    D,
}

fn main() {
    let help_str = Opts::command().render_long_help().to_string();

    // I need to do snapshot testing, for now just print it
    println!("{}", help_str);
}

(Playground)

Output:

Usage: playground <COMMAND>

Commands:
  a
          this has subcommands
  b
          
  help
          Print this message or the help of the given subcommand(s)

Options:
  -h, --help
          Print help information


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.