build.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. //! Build script: embeds the short git commit hash of the build as `WH_GIT_HASH`.
  2. use std::process::Command;
  3. /// Name of the compile-time environment variable holding the commit hash.
  4. const GIT_HASH_ENV: &str = "WH_GIT_HASH";
  5. /// Value used when the hash cannot be read (no git, not a repository).
  6. const UNKNOWN_HASH: &str = "unknown";
  7. /// Purpose: export the short commit hash to the crate and rebuild when the commit changes.
  8. /// Inputs: none (runs `git` in the package directory).
  9. /// Output: none.
  10. /// Side effects: prints cargo directives on stdout.
  11. fn main() {
  12. println!("cargo:rerun-if-changed=.git/HEAD");
  13. println!("cargo:rerun-if-changed=.git/refs");
  14. println!("cargo:rerun-if-changed=.git/packed-refs");
  15. let hash = git_short_hash().unwrap_or_else(|| UNKNOWN_HASH.to_owned());
  16. println!("cargo:rustc-env={GIT_HASH_ENV}={hash}");
  17. }
  18. /// Purpose: read the short hash of the checked-out commit.
  19. /// Inputs: none.
  20. /// Output: the hash, or `None` when git is missing, fails or prints nothing.
  21. /// Side effects: runs `git rev-parse --short HEAD`.
  22. fn git_short_hash() -> Option<String> {
  23. let output = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output().ok()?;
  24. if !output.status.success() {
  25. return None;
  26. }
  27. let hash = String::from_utf8(output.stdout).ok()?.trim().to_owned();
  28. (!hash.is_empty()).then_some(hash)
  29. }