| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- //! Build script: embeds the short git commit hash as `WH_GIT_HASH` and the commit count
- //! (build number) as `WH_BUILD_NUMBER`.
- use std::process::Command;
- /// Name of the compile-time environment variable holding the commit hash.
- const GIT_HASH_ENV: &str = "WH_GIT_HASH";
- /// Name of the compile-time environment variable holding the build number (commit count).
- const BUILD_NUMBER_ENV: &str = "WH_BUILD_NUMBER";
- /// Value used when the hash cannot be read (no git, not a repository).
- const UNKNOWN_HASH: &str = "unknown";
- /// Value used when the build number cannot be read (no git, not a repository).
- const UNKNOWN_BUILD_NUMBER: &str = "0";
- /// Purpose: export the short commit hash and the build number (commit count) to the crate
- /// and rebuild when the commit changes.
- /// Inputs: none (runs `git` in the package directory).
- /// Output: none.
- /// Side effects: prints cargo directives on stdout.
- fn main() {
- println!("cargo:rerun-if-changed=.git/HEAD");
- println!("cargo:rerun-if-changed=.git/refs");
- println!("cargo:rerun-if-changed=.git/packed-refs");
- let hash =
- git_output(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| UNKNOWN_HASH.to_owned());
- println!("cargo:rustc-env={GIT_HASH_ENV}={hash}");
- let build_number = git_output(&["rev-list", "--count", "HEAD"])
- .unwrap_or_else(|| UNKNOWN_BUILD_NUMBER.to_owned());
- println!("cargo:rustc-env={BUILD_NUMBER_ENV}={build_number}");
- }
- /// Purpose: run `git` with the given arguments and return its trimmed output.
- /// Inputs: `args` - the arguments passed to `git`.
- /// Output: the trimmed stdout, or `None` when git is missing, fails or prints nothing.
- /// Side effects: runs the `git` command.
- fn git_output(args: &[&str]) -> Option<String> {
- let output = Command::new("git").args(args).output().ok()?;
- if !output.status.success() {
- return None;
- }
- let text = String::from_utf8(output.stdout).ok()?.trim().to_owned();
- (!text.is_empty()).then_some(text)
- }
|