Adding help text will remind us of how the tool is intended to be used. Doing this in Clap is well-supported, which makes it easy to do.
Add a series of comments with 3 forward slashes (/
).
use clap::Parser;
/// Scaffold a new post for your blog
#[derive(Parser, Debug)]
struct Args {
/// The layout the post should use
#[clap(short, long, default_value = "post")]
layout: String,
/// Tags to include
#[clap(short, long = "tag")]
tags: Vec<String>,
/// The title of the post.
///
/// If not provided, the filename will be generated
#[clap(short = 'T', long, default_value = "A Post")]
title: String,
/// Should this post be published?
#[clap(short, long, default_value = "draft")]
status: String,
/// Where to put the file
#[clap(short, long, default_value = "content")]
output_dir: String,
}
fn main() {
let args = Args::parse();
dbg!(args);
}
The comments on each field are associated with each flag, while the comment on the struct itself is the primary documentation location for the CLI.
Clap allows us to run using short help (-h
) or long help (—help
) flags and will derive the output of these commands from our comments.
The short version is compressed, and only uses the first line of each comment for each field.
❯ cargo run -- -h
Compiling scaffold v0.1.0 (/Users/chris/github/rust-adventure/_in-progress/first-rust-cli-clap)
Finished dev [unoptimized + debuginfo] target(s) in 0.78s
Running `target/debug/scaffold -h`
Scaffold a new post for your blog
Usage: scaffold [OPTIONS]
Options:
-l, --layout <LAYOUT> The layout the post should use [default: post]
-t, --tag <TAGS> Tags to include
-T, --title <TITLE> The title of the post [default: "A Post"]
-s, --status <STATUS> Should this post be published? [default: draft]
-o, --output-dir <OUTPUT_DIR> Where to put the file [default: content]
-h, --help Print help (see more with '--help')
While the long help includes the full output of our comments in a more spaced out display.
❯ cargo run -- --help
Finished dev [unoptimized + debuginfo] target(s) in 0.05s
Running `target/debug/scaffold --help`
Scaffold a new post for your blog
Usage: scaffold [OPTIONS]
Options:
-l, --layout <LAYOUT>
The layout the post should use
[default: post]
-t, --tag <TAGS>
Tags to include
-T, --title <TITLE>
The title of the post.
If not provided, the filename will be generated
[default: "A Post"]
-s, --status <STATUS>
Should this post be published?
[default: draft]
-o, --output-dir <OUTPUT_DIR>
Where to put the file
[default: content]
-h, --help
Print help (see a summary with '-h')
-V, --version
Print version
Its well possible to do all sorts of grouping for the documentation, but we’ll leave the comment output as is for now.
Notice also that the default values are also printed out!