Sub topic 6
Help and version output
This chapter assumes you can define a CLI with #[derive(Parser)], including doc comments on fields and the #[arg(...)] attribute. It also assumes you know that --help exits with status 0. Here you will see where clap gets each line of its help text, how short and long help differ, and how to control the layout and the version string.
Where help text comes from
clap builds help from the CLI definition. You never write a --help handler. For every derived parser, clap adds:
-hand--help, which print help to stdout and exit with status 0.-Vand--version, but only if you setversionon the command.
Each piece of the help screen has one source:
| Help section | Source in the derive definition |
|---|---|
| Description at the top | Doc comment on the struct, or `about = "..."` |
| Program name in `Usage:` | Package name, or `name = "..."` |
| Argument descriptions | Doc comment on each field, or `help = "..."` |
| Placeholders such as `<FILE>` | Field name in upper case, or `value_name = "..."` |
| Version string | `version` (from `Cargo.toml`) or `version = "..."` |
| `[default: ...]` suffix | `default_value_t` or `default_value` |
A first look at the output
This program uses doc comments for everything, plus two customizations: value_name and after_help.
use clap::{ArgAction, Parser};
use std::path::PathBuf;
/// Print lines of a file that contain a pattern.
///
/// Lines are matched as plain text, not as regular expressions.
/// The file is read once, from start to end.
#[derive(Parser, Debug)]
#[command(version, after_help = "Exit status: 0 on success, 2 on usage errors.")]
struct Cli {
/// File to search
#[arg(value_name = "FILE")]
path: PathBuf,
/// Only print lines containing this text
///
/// Matching is case-sensitive.
#[arg(short, long, value_name = "TEXT")]
filter: Option<String>,
/// Increase output detail (-v, -vv)
#[arg(short, long, action = ArgAction::Count)]
verbose: u8,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Assume the package is named lookup. Running cargo run -- -h prints output like this:
Print lines of a file that contain a pattern
Usage: lookup [OPTIONS] <FILE>
Arguments:
<FILE> File to search
Options:
-f, --filter <TEXT> Only print lines containing this text
-v, --verbose... Increase output detail (-v, -vv)
-h, --help Print help (see more with '--help')
-V, --version Print version
Exit status: 0 on success, 2 on usage errors.Four details are worth noting:
- The trailing period of the one-line description is removed.
- The counted flag shows as
--verbose..., which tells the reader it can repeat. <FILE>and<TEXT>come fromvalue_name. Without it you would see<PATH>and<FILTER>.- The
-hline says "see more with '--help'" because some text has a longer form.
cargo run -- --version prints lookup 0.1.0. The number comes from the version field in Cargo.toml, read at compile time through the CARGO_PKG_VERSION environment variable.
Short help and long help
clap keeps two versions of each description. -h prints the short one and --help prints the long one. Doc comments feed both:
- The first paragraph becomes the short text.
- The whole comment, with all paragraphs, becomes the long text.
In the example above, -h shows only "Print lines of a file that contain a pattern" at the top, and --filter shows only its first line. --help shows the extra paragraphs, such as "Matching is case-sensitive." It lays out each option's description on its own lines below the option name, which leaves room for the longer text.
If you want different text instead of the doc comment, set it explicitly with help for the short form and long_help for the long form. On the command itself, the equivalents are about and long_about.
use clap::Parser;
#[derive(Parser)]
#[command(about = "Resize images", long_about = "Resize images.\n\nSupports PNG and JPEG.")]
struct Cli {
#[arg(long, help = "Width in pixels", long_help = "Width in pixels. Height is scaled to match.")]
width: Option<u32>,
}
fn main() {
let _ = Cli::parse();
}An explicit about replaces the doc comment. A bare about with no value is a special case: it reads the description field from Cargo.toml. That is the form you saw in the earlier chapters.
Doc comment formatting
clap re-wraps doc comment text to the terminal width and joins consecutive lines into one paragraph. A list or an ASCII table inside a doc comment will therefore be flattened. Add #[command(verbatim_doc_comment)] on the struct, or #[arg(verbatim_doc_comment)] on a field, to keep your line breaks exactly as written.
Customizing the layout
This example combines the most common customizations.
use clap::Parser;
use std::path::PathBuf;
/// Resize every image in a directory.
#[derive(Parser, Debug)]
#[command(
name = "imgfit",
version = "2.1.0",
long_version = "2.1.0 (format support: png, jpeg)",
arg_required_else_help = true,
after_long_help = "Examples:\n imgfit photos --width 800\n imgfit photos --width 800 --out resized"
)]
struct Cli {
/// Directory that holds the images
#[arg(value_name = "DIR")]
dir: PathBuf,
/// Target width in pixels
#[arg(long, value_name = "PX", default_value_t = 1024)]
width: u32,
/// Directory for resized copies
#[arg(long, value_name = "DIR", help_heading = "Output")]
out: Option<PathBuf>,
/// Reserved for a future release
#[arg(long, hide = true)]
keep_times: bool,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}What each attribute does:
namereplaces the package name inUsage:and in the version line.version = "2.1.0"sets the version explicitly. This is useful when the version does not come fromCargo.toml.long_versionis printed by--version, while-Vprints the short one.imgfit -Vgivesimgfit 2.1.0, andimgfit --versiongivesimgfit 2.1.0 (format support: png, jpeg). Build scripts often use this slot for a commit hash.arg_required_else_help = trueprints help and exits when the program is run with no arguments. Without it, a missingDIRproduces a usage error.after_long_helpadds text at the bottom of--helponly.after_helpadds it to both forms, andbefore_helpandbefore_long_helpadd text above the options.help_heading = "Output"moves--outinto its ownOutput:section.hide = trueremoves--keep-timesfrom both help forms. The flag still works when typed.default_value_t = 1024adds[default: 1024]to the help line for--width.
The \n escapes in after_long_help make the text span several lines. clap prints that text as written.
Help in code
Sometimes you need to print help yourself, for example when a program is run with no input on a pipe. CommandFactory gives you the underlying Command:
use clap::{CommandFactory, Parser};
#[derive(Parser)]
#[command(version)]
struct Cli {
/// Name to greet
name: Option<String>,
}
fn main() {
let cli = Cli::parse();
match cli.name {
Some(name) => println!("Hello, {name}!"),
None => {
Cli::command().print_help().expect("failed to write help");
println!();
}
}
}print_help writes the long form to stdout. If you want the short form, call print_help on a command value that has been prepared with render_help or render_long_help, which return a value you can format yourself.
Common problems
- The
-hand-Vletters are taken. Adding#[arg(short)]to a field namedhostorverboseis fine, but a field namedhelpor a short letterhcollides with the built-in help flag. In a debug build clap panics with a message about a duplicate short option. Useshort = 'H'instead, or turn off the built-in flag with#[command(disable_help_flag = true)]. - Without
version,--versiondoes not exist. Running it gives an "unexpected argument" usage error with exit status 2, not a version line. - Lowercase
-vand uppercase-Vare different flags. Many tools use-vfor verbose and-Vfor version, and clap follows that convention by default. - Subcommands do not inherit the version flag.
tool --versionworks, buttool add --versiondoes not, unless you also setpropagate_version = true. The next chapters cover subcommands in full. - Help and errors go to different streams.
--helpand--versionwrite to stdout and exit with status 0. Parse errors write to stderr and exit with status 2. Scripts that capture help output must read stdout. - Version changes need a rebuild. The version is baked in at compile time. Cargo detects a changed
versioninCargo.tomland rebuilds, but a version string you pass inversion = "..."changes only when the source changes.
Exercise
A field has a doc comment with two paragraphs. Which flag shows both paragraphs, what does -h show, and how do you hide the field from both outputs?
Show answer
--help shows both paragraphs. -h shows only the first paragraph. Adding #[arg(hide = true)] removes the field from both help forms, and the flag still works when typed.
Exercise
You add #[arg(short, long)] help: bool to your struct, and the program panics at startup in a debug build. Why, and how do you fix it?
Show answer
The field's short flag is -h, which clap already uses for the built-in help flag, so clap detects a duplicate. Either give the field a different letter, such as short = 'H', or set #[command(disable_help_flag = true)] and define your own help behavior.
Exercise
What do -V and --version print when you set both version = "2.1.0" and long_version = "2.1.0 (build 4821)" on a command named imgfit?
Show answer
imgfit -V prints imgfit 2.1.0. imgfit --version prints imgfit 2.1.0 (build 4821).