Documenting and writing helptext for Structopt CLI commands and flags

InstructorChris Biscardi

Share this video with your friends

Send Tweet

if we run cargo run -- --help, we can see that structopt thinks the name of our binary is still the package name. We can change that with another attribute macro on our struct.

digital-garden 0.1.0

USAGE:
    garden <SUBCOMMAND>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

SUBCOMMANDS:
    help     Prints this message or the help of the given subcommand(s)
    write

Also notice that in the help text the help subcommand has some helpful output while write has none:

garden 0.1.0

USAGE:
    garden <SUBCOMMAND>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

SUBCOMMANDS:
    help     Prints this message or the help of the given subcommand(s)
    write

There are a number of places we can put doc comments. We can write on the Opt struct for global information about the CLI.

We can also write on each subcommand or even the options for each subcommand.

/// A CLI for the growing and curation of a digital garden
///
/// Visit https://www.rustadventure.rs/garden for more!
struct Opt {
    #[structopt(subcommand)]
    cmd: Command,
}
enum Command {
    /// write something in your garden
    ///
    /// This command will open your $EDITOR, wait for you
    /// to write something, and then save the file to your
    /// garden
    Write {
        /// Optionally set a title for what you are going to write about
        #[structopt(short, long)]
        title: Option<String>,
    },
}

Each of these results in documentation going to the relevant place in the CLI help text. Note especially that the first line of doc comment for subcommands is shown as "short" help text, while the full text is reserved for running --help directly on the subcommand.

❯ cargo run
garden 0.1.0
A CLI for the growing and curation of a digital garden

Visit https://www.rustadventure.rs/garden for more!

USAGE:
    garden <SUBCOMMAND>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

SUBCOMMANDS:
    help     Prints this message or the help of the given subcommand(s)
    write    write something in your garden
❯ cargo run -- write --help
garden-write 0.1.0
write something in your garden

This command will open your $EDITOR, wait for you to write something, and then save the file to your garden

USAGE:
    garden write [OPTIONS]

FLAGS:
    -h, --help
            Prints help information

    -V, --version
            Prints version information

OPTIONS:
    -t, --title <title>
            Optionally set a title for what you are going to write about

Also note that -h and --help are not the same thing when it comes to structopt.