git_describe_build_tool/
lib.rs

1//! Retrieve Git tag, store as environment variable at build time
2//!
3//! The command `git describe --tags`
4//!
5//! > ... finds the most recent tag that is reachable from a commit. If
6//! > the tag points to the commit, then only the tag is shown. Otherwise,
7//! > it suffixes the tag name with the number of additional commits on
8//! > top of the tagged object and the abbreviated object name of the most
9//! > recent commit. The result is a "human-readable" object name which
10//! > can also be used to identify the commit to other git commands ...
11//! >
12//! > -- Git Manual
13//!
14//! Example
15//! -------
16//!
17//! To use, simply add as a build dependency to your `cargo.toml`
18//!
19//! ```text
20//! [package]
21//! build = "build.rs"
22//!
23//! [build-dependencies]
24//! git_describe_build_tool = "~1.0.0"
25//! ```
26//!
27//! Then, add `build.rs`
28//!
29//! ```no_run
30//! # #[allow(clippy::needless_doctest_main)]
31//! use git_describe_build_tool::prelude::*;
32//!
33//! fn main() {
34//!     git_build_script();
35//! }
36//! ```
37//!
38//! Then, in your code, whenever you want to reference the current version
39//! use the `env!` macro
40//!
41//! ```no_run
42//! pub const GIT_COMMIT_DESCRIBE: &str = env!("GIT_COMMIT_DESCRIBE");
43//!
44//! assert_eq! {
45//!     "0.11.0-51-g4446464",
46//!     GIT_COMMIT_DESCRIBE
47//! }
48//! ```
49
50/// Name of the environment variable
51pub const ENV_VAR_NAME: &str = "GIT_COMMIT_DESCRIBE";
52
53pub mod prelude {
54    pub use super::git_build_script;
55}
56
57/// Retrieve the version from git, then store in environment variable
58pub fn git_build_script() {
59    let _ = retrieve_app_version_from_git_repository()
60        .or_else(|| Some("UNKNOWN".to_owned()))
61        .map(store_app_version_in_environment_variable);
62}
63
64/// Retrieve the version from git
65pub fn retrieve_app_version_from_git_repository() -> Option<String> {
66    { std::process::Command::new("git").args(&["describe", "--tags"]) }
67        .output()
68        .ok()
69        .filter(|o| o.status.success())
70        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
71}
72
73/// Store the version in environment variable
74pub fn store_app_version_in_environment_variable(app_version: String) {
75    println!("cargo:rustc-env={ENV_VAR_NAME}={app_version}");
76}