feat(macros.rs): add macro to get version from Cargo.toml

This commit is contained in:
Kevin K 2015-04-19 14:06:08 -04:00
parent d7bf519acf
commit c630969aa3
2 changed files with 41 additions and 8 deletions

View file

@ -1,19 +1,28 @@
#[macro_use]
extern crate clap;
use clap::App;
fn main() {
// You can have clap pull the application version directly from your Cargo.toml starting with
// clap v0.4.14 on crates.io (or master#a81f915 on github)
// clap v0.4.14 on crates.io (or master#a81f915 on github). Using Rust's env! macro like this:
//
// let version = format!("{}.{}.{}{}",
// env!("CARGO_PKG_VERSION_MAJOR"),
// env!("CARGO_PKG_VERSION_MINOR"),
// env!("CARGO_PKG_VERSION_PATCH"),
// option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
//
// Starting from v0.6.6 on crates.io you can also use the crate_version!() macro instead of
// manually using the env!() macros. Under the hood, the macro uses this exact method to get
// the version.
//
// Thanks to https://github.com/jhelwig for pointing this out
let version = format!("{}.{}.{}{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH"),
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
let matches = App::new("myapp").about("does awesome things").version(&version[..]).get_matches();
let matches = App::new("myapp")
.about("does awesome things")
// use crate_version! to pull the version number
.version(&crate_version!()[..])
.get_matches();
// running the this app with the -v or --version will display whatever version is in your
// Cargo.toml, the default being: myapp 0.0.1

View file

@ -382,3 +382,27 @@ macro_rules! arg_enum {
}
};
}
/// Allows you pull the version for an from your Cargo.toml as MAJOR.MINOR.PATCH_PKGVERSION_PRE
///
/// # Example
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # fn main() {
/// let m = App::new("app")
/// .version(crate_version!())
/// .get_matches();
/// # }
/// ```
#[macro_export]
macro_rules! crate_version {
() => {
format!("{}.{}.{}{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH"),
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""))
}
}