Expand description
Command line argument parsing.
clap
is a powerful and feature-rich command-line argument parser
that provides a polished CLI experience out-of-the-box.
It supports two primary API approaches: the derive API for simplicity
and the builder API for maximum flexibility.
§Examples
Simple command-line tool using the derive API:
use clap::Parser;
#[derive(Parser)]
#[command(version, about = "A simple greeting tool")]
struct Args {
/// Name to greet
#[arg(short, long)]
name: String,
/// Number of times to greet
#[arg(short, long, default_value = "1")]
count: u8,
}
fn main() {
// Parse from custom args for testing
let args = Args::parse_from(&["prog", "--name", "World"]);
for _ in 0..args.count {
println!("Hello, {}!", args.name);
}
}
Application with subcommands:
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(version, about = "File management tool")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Create a new file
Create {
/// File name to create
name: String,
},
/// List files
List {
/// Show hidden files
#[arg(short, long)]
all: bool,
},
}
fn main() {
// Parse from custom args for testing
let cli = Cli::parse_from(&["prog", "create", "test.txt"]);
match cli.command {
Commands::Create { name } => {
println!("Creating file: {}", name);
}
Commands::List { all } => {
if all {
println!("Listing all files including hidden");
} else {
println!("Listing visible files");
}
}
}
}
Modules§
- builder
- Define
Command
line arguments - clap_
derive clap_derive
- error
- Error reporting
- parser
Command
line argument parser
Macros§
- arg
- Create an
Arg
from a usage string. - command
- Requires
cargo
feature flag to be enabled. - value_
parser - Select a
ValueParser
implementation from the intended type
Structs§
- Arg
- The abstract representation of a command line argument. Used to set all the options and relationships that define a valid argument for the program.
- ArgGroup
- Family of related arguments.
- ArgMatches
- Container for parse results.
- Command
- Build a command-line interface.
- Id
Arg
orArgGroup
identifier
Enums§
- ArgAction
- Behavior of arguments when they are encountered while parsing
- Color
Choice - Represents the color preferences for program output
- Value
Hint - Provide shell with hint on how to complete an argument.
Traits§
- Args
- Parse a set of arguments into a user-defined container.
- Command
Factory - Create a
Command
relevant for a user-defined container. - From
ArgMatches - Converts an instance of
ArgMatches
to a user-defined container. - Parser
- Parse command-line arguments into
Self
. - Subcommand
- Parse a sub-command into a user-defined enum.
- Value
Enum - Parse arguments into enums.
Type Aliases§
- Error
- Command Line Argument Parser Error
Derive Macros§
- Args
- Generates the
Args
impl. - Parser
- Generates the
Parser
implementation. - Subcommand
- Generates the
Subcommand
impl. - Value
Enum - Generates the
ValueEnum
impl.