diff --git a/src/macros.rs b/src/macros.rs index 49467a616e24..f3a7e0332d28 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -283,15 +283,10 @@ macro_rules! crate_name { /// Allows you to build the `Command` instance from your Cargo.toml at compile time. /// -/// Equivalent to using the `crate_*!` macros with their respective fields. -/// -/// Provided separator is for the [`crate_authors!`] macro, -/// refer to the documentation therefor. -/// /// **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. /// -/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your +/// 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");` /// @@ -301,11 +296,35 @@ macro_rules! crate_name { /// # #[macro_use] /// # extern crate clap; /// # fn main() { -/// let m = app_from_crate!().get_matches(); +/// 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 + }}; +} + +/// Deprecated, replaced with [`clap::command!`] +#[cfg(feature = "cargo")] +#[macro_export] macro_rules! app_from_crate { () => {{ let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); diff --git a/tests/builder/command.rs b/tests/builder/command.rs new file mode 100644 index 000000000000..9f31d7a9d6a1 --- /dev/null +++ b/tests/builder/command.rs @@ -0,0 +1,27 @@ +#![cfg(feature = "cargo")] + +use clap::{command, error::ErrorKind}; + +static EVERYTHING: &str = "clap {{version}} +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + clap + +OPTIONS: + -h, --help Print help information + -V, --version Print version information +"; + +#[test] +fn command() { + let res = command!().try_get_matches_from(vec!["clap", "--help"]); + + assert!(res.is_err()); + let err = res.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::DisplayHelp); + assert_eq!( + err.to_string(), + EVERYTHING.replace("{{version}}", env!("CARGO_PKG_VERSION")) + ); +} diff --git a/tests/builder/main.rs b/tests/builder/main.rs index ab181047f2f2..124111f10117 100644 --- a/tests/builder/main.rs +++ b/tests/builder/main.rs @@ -6,6 +6,7 @@ mod arg_matcher_assertions; mod arg_settings; mod borrowed; mod cargo; +mod command; mod conflicts; mod default_missing_vals; mod default_vals;