Skip to content

Commit

Permalink
feat(macros.rs): add macro to get version from Cargo.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
kbknapp committed Apr 19, 2015
1 parent d7bf519 commit c630969
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
25 changes: 17 additions & 8 deletions examples/09_AutoVersion.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down
24 changes: 24 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(""))
}
}

1 comment on commit c630969

@pickfire
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we show CARGO_PKG_VERSION instead of the long example above? It is implemented in cargo around 2015.

Please sign in to comment.