1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
/// Allows you to pull the version from your Cargo.toml at compile time as
/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE`
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::crate_version;
/// # use clap::Command;
/// let m = Command::new("cmd")
/// .version(crate_version!())
/// .get_matches();
/// ```
#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_version {
() => {
env!("CARGO_PKG_VERSION")
};
}
/// Allows you to pull the authors for the command from your Cargo.toml at
/// compile time in the form:
/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"`
///
/// You can replace the colons with a custom separator by supplying a
/// replacement string, so, for example,
/// `crate_authors!(",\n")` would become
/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"`
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::crate_authors;
/// # use clap::Command;
/// let m = Command::new("cmd")
/// .author(crate_authors!("\n"))
/// .get_matches();
/// ```
#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_authors {
($sep:expr) => {{
static AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
if AUTHORS.contains(':') {
static CACHED: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let s = CACHED.get_or_init(|| AUTHORS.replace(':', $sep));
let s: &'static str = &*s;
s
} else {
AUTHORS
}
}};
() => {
env!("CARGO_PKG_AUTHORS")
};
}
/// Allows you to pull the description from your Cargo.toml at compile time.
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::crate_description;
/// # use clap::Command;
/// let m = Command::new("cmd")
/// .about(crate_description!())
/// .get_matches();
/// ```
#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_description {
() => {
env!("CARGO_PKG_DESCRIPTION")
};
}
/// Allows you to pull the name from your Cargo.toml at compile time.
///
/// **NOTE:** This macro extracts the name from an environment variable `CARGO_PKG_NAME`.
/// When the crate name is set to something different from the package name,
/// use environment variables `CARGO_CRATE_NAME` or `CARGO_BIN_NAME`.
/// See [the Cargo Book](https://doc.rust-lang.org/cargo/reference/environment-variables.html)
/// for more information.
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::crate_name;
/// # use clap::Command;
/// let m = Command::new(crate_name!())
/// .get_matches();
/// ```
#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_name {
() => {
env!("CARGO_PKG_NAME")
};
}
/// Allows you to build the `Command` instance from your Cargo.toml at compile time.
///
/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically,
/// and therefore won't change the generated output until you recompile.
///
/// In some cases you can "trick" the compiler into triggering a rebuild when your
/// `Cargo.toml` is changed by including this in your `src/main.rs` file
/// `include_str!("../Cargo.toml");`
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::command;
/// let m = command!().get_matches();
/// ```
#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! command {
() => {{
$crate::command!($crate::crate_name!())
}};
($name:expr) => {{
let mut cmd = $crate::Command::new($name).version($crate::crate_version!());
let author = $crate::crate_authors!();
if !author.is_empty() {
cmd = cmd.author(author)
}
let about = $crate::crate_description!();
if !about.is_empty() {
cmd = cmd.about(about)
}
cmd
}};
}
/// Requires `cargo` feature flag to be enabled.
#[cfg(not(feature = "cargo"))]
#[macro_export]
macro_rules! command {
() => {{
compile_error!("`cargo` feature flag is required");
}};
($name:expr) => {{
compile_error!("`cargo` feature flag is required");
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! arg_impl {
( @string $val:ident ) => {
stringify!($val)
};
( @string $val:literal ) => {{
let ident_or_string_literal: &str = $val;
ident_or_string_literal
}};
( @string $val:tt ) => {
::std::compile_error!("Only identifiers or string literals supported");
};
( @string ) => {
None
};
( @char $val:ident ) => {{
let ident_or_char_literal = stringify!($val);
debug_assert_eq!(
ident_or_char_literal.len(),
1,
"Single-letter identifier expected, got {ident_or_char_literal}",
);
ident_or_char_literal.chars().next().unwrap()
}};
( @char $val:literal ) => {{
let ident_or_char_literal: char = $val;
ident_or_char_literal
}};
( @char ) => {{
None
}};
(
@arg
($arg:expr)
--$long:ident
$($tail:tt)*
) => {{
debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
let mut arg = $arg;
let long = $crate::arg_impl! { @string $long };
if arg.get_id() == "" {
arg = arg.id(long);
}
let action = $crate::ArgAction::SetTrue;
let arg = arg
.long(long)
.action(action);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
--$long:literal
$($tail:tt)*
) => {{
debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
let mut arg = $arg;
let long = $crate::arg_impl! { @string $long };
if arg.get_id() == "" {
arg = arg.id(long);
}
let action = $crate::ArgAction::SetTrue;
let arg = arg
.long(long)
.action(action);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
-$short:ident
$($tail:tt)*
) => {{
debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags");
debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
let action = $crate::ArgAction::SetTrue;
let arg = $arg
.short($crate::arg_impl! { @char $short })
.action(action);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
-$short:literal
$($tail:tt)*
) => {{
debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags");
debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
let action = $crate::ArgAction::SetTrue;
let arg = $arg
.short($crate::arg_impl! { @char $short })
.action(action);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
<$value_name:ident>
$($tail:tt)*
) => {{
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported");
let mut arg = $arg;
if arg.get_long().is_none() && arg.get_short().is_none() {
arg = arg.required(true);
}
let value_name = $crate::arg_impl! { @string $value_name };
if arg.get_id() == "" {
arg = arg.id(value_name);
}
let arg = arg
.value_name(value_name)
.action($crate::ArgAction::Set);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
<$value_name:literal>
$($tail:tt)*
) => {{
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported");
let mut arg = $arg;
if arg.get_long().is_none() && arg.get_short().is_none() {
arg = arg.required(true);
}
let value_name = $crate::arg_impl! { @string $value_name };
if arg.get_id() == "" {
arg = arg.id(value_name);
}
let arg = arg
.value_name(value_name)
.action($crate::ArgAction::Set);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
[$value_name:ident]
$($tail:tt)*
) => {{
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported");
let mut arg = $arg;
if arg.get_long().is_none() && arg.get_short().is_none() {
arg = arg.required(false);
} else {
arg = arg.num_args(0..=1);
}
let value_name = $crate::arg_impl! { @string $value_name };
if arg.get_id() == "" {
arg = arg.id(value_name);
}
let arg = arg
.value_name(value_name)
.action($crate::ArgAction::Set);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
[$value_name:literal]
$($tail:tt)*
) => {{
debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported");
let mut arg = $arg;
if arg.get_long().is_none() && arg.get_short().is_none() {
arg = arg.required(false);
} else {
arg = arg.num_args(0..=1);
}
let value_name = $crate::arg_impl! { @string $value_name };
if arg.get_id() == "" {
arg = arg.id(value_name);
}
let arg = arg
.value_name(value_name)
.action($crate::ArgAction::Set);
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
...
$($tail:tt)*
) => {{
let arg = match $arg.get_action() {
$crate::ArgAction::Set => {
if $arg.get_long().is_none() && $arg.get_short().is_none() {
$arg.num_args(1..)
// Allow collecting arguments interleaved with flags
.action($crate::ArgAction::Append)
} else {
$arg.action($crate::ArgAction::Append)
}
},
$crate::ArgAction::SetTrue | $crate::ArgAction::Help | $crate::ArgAction::Version => {
$arg.action($crate::ArgAction::Count)
}
action => {
panic!("Unexpected action {action:?}")
}
};
let arg = $crate::arg_impl! {
@arg (arg) $($tail)*
};
arg
}};
(
@arg
($arg:expr)
$help:literal
) => {{
$arg.help($help)
}};
(
@arg
($arg:expr)
) => {{
$arg
}};
}
/// Create an [`Arg`] from a usage string.
///
/// Allows creation of basic settings for the [`Arg`].
///
/// **NOTE**: Not all settings may be set using the usage string method. Some properties are
/// only available via the builder pattern.
///
/// # Syntax
///
/// Usage strings typically following the form:
///
/// ```notrust
/// [explicit name] [short] [long] [value names] [...] [help string]
/// ```
///
/// ### Explicit Name
///
/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or
/// `"name":`.
///
/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional
/// fields as the name using the following priority order:
///
/// 1. Explicit Name
/// 2. Long
/// 3. Value Name
///
/// See [`Arg::id`][crate::Arg::id].
///
/// ### Short
///
/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or
/// `-'f'`.
///
/// See [`Arg::short`][crate::Arg::short].
///
/// ### Long
///
/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or
/// `--"foo"`.
///
/// **NOTE:** Dashes in the long name (e.g. `--foo-bar`) is not supported and quoting is required
/// (e.g. `--"foo-bar"`).
///
/// See [`Arg::long`][crate::Arg::long].
///
/// ### Values (Value Notation)
///
/// This is set by placing bare-word between:
/// - `[]` like `[FOO]`
/// - Positional argument: optional
/// - Named argument: optional value
/// - `<>` like `<FOO>`: required
///
/// See [`Arg::value_name`][crate::Arg::value_name].
///
/// ### `...`
///
/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple
/// times (not to be confused with multiple values per occurrence).
///
/// See [`ArgAction::Count`][crate::ArgAction::Count] and [`ArgAction::Append`][crate::ArgAction::Append].
///
/// ### Help String
///
/// The help string is denoted between a pair of double quotes `""` and may contain any
/// characters.
///
/// # Examples
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, arg};
/// let cmd = Command::new("prog")
/// .args(&[
/// arg!(--config <FILE> "a required file for the configuration and no short"),
/// arg!(-d --debug ... "turns on debugging information and allows multiples"),
/// arg!([input] "an optional input file to use")
/// ]);
///
/// let m = cmd.try_get_matches_from(["prog", "--config", "file.toml"]).unwrap();
/// assert_eq!(m.get_one::<String>("config").unwrap(), "file.toml");
/// assert_eq!(*m.get_one::<u8>("debug").unwrap(), 0);
/// assert_eq!(m.get_one::<String>("input"), None);
/// ```
/// [`Arg`]: crate::Arg
#[macro_export]
macro_rules! arg {
( $name:ident: $($tail:tt)+ ) => {{
let arg = $crate::Arg::new($crate::arg_impl! { @string $name });
let arg = $crate::arg_impl! {
@arg (arg) $($tail)+
};
arg
}};
( $($tail:tt)+ ) => {{
let arg = $crate::Arg::default();
let arg = $crate::arg_impl! {
@arg (arg) $($tail)+
};
debug_assert_ne!(arg.get_id(), "", "Without a value or long flag, the `name:` prefix is required");
arg
}};
}
#[cfg(feature = "debug")]
macro_rules! debug {
($($arg:tt)*) => ({
use std::fmt::Write as _;
let hint = anstyle::Style::new().dimmed();
let module_path = module_path!();
let body = format!($($arg)*);
let mut styled = $crate::builder::StyledStr::new();
let _ = write!(styled, "{}[{module_path:>28}]{body}{}\n", hint.render(), hint.render_reset());
let color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto).with_content(styled);
let _ = color.print();
})
}
#[cfg(not(feature = "debug"))]
macro_rules! debug {
($($arg:tt)*) => {};
}
macro_rules! ok {
($expr:expr) => {
match $expr {
Ok(val) => val,
Err(err) => {
return Err(err);
}
}
};
}
macro_rules! some {
($expr:expr) => {
match $expr {
Some(val) => val,
None => {
return None;
}
}
};
}