|
| 1 | +use std::{env, process::Command}; |
| 2 | + |
| 3 | +fn main() { |
| 4 | + // Use the SDK_VERSION environment variable if it is set (e.g. by CI) or get it from Git |
| 5 | + let sdk_version = env::var("SDK_VERSION") |
| 6 | + .or_else(|_| version_from_git_info()) |
| 7 | + .unwrap_or("unknown".to_string()); |
| 8 | + |
| 9 | + println!("cargo:rustc-env=SDK_VERSION={sdk_version}"); |
| 10 | + println!("cargo:rustc-env=CARGO_PKG_VERSION={sdk_version}"); |
| 11 | +} |
| 12 | + |
| 13 | +fn run(args: &[&str]) -> Result<String, std::io::Error> { |
| 14 | + let out = Command::new(args[0]).args(&args[1..]).output()?; |
| 15 | + if !out.status.success() { |
| 16 | + use std::io::{Error, ErrorKind}; |
| 17 | + return Err(Error::new(ErrorKind::Other, "Command not successful")); |
| 18 | + } |
| 19 | + Ok(String::from_utf8(out.stdout).unwrap().trim().to_string()) |
| 20 | +} |
| 21 | + |
| 22 | +/// This method reads info from Git, namely tags, branch, and revision |
| 23 | +/// To access these values, use: |
| 24 | +/// - `env!("GIT_EXACT_TAG")` |
| 25 | +/// - `env!("GIT_BRANCH")` |
| 26 | +/// - `env!("GIT_REV")` |
| 27 | +fn version_from_git_info() -> Result<String, std::io::Error> { |
| 28 | + // The exact tag for the current commit, can be empty when |
| 29 | + // the current commit doesn't have an associated tag |
| 30 | + let exact_tag = run(&["git", "describe", "--abbrev=0", "--tags", "--exact-match"]).ok(); |
| 31 | + if let Some(ref exact) = exact_tag { |
| 32 | + println!("cargo:rustc-env=GIT_EXACT_TAG={exact}"); |
| 33 | + } |
| 34 | + |
| 35 | + // The current branch name |
| 36 | + let branch = run(&["git", "rev-parse", "--abbrev-ref", "HEAD"])?; |
| 37 | + println!("cargo:rustc-env=GIT_BRANCH={branch}"); |
| 38 | + |
| 39 | + // The current git commit hash |
| 40 | + let rev = run(&["git", "rev-parse", "HEAD"])?; |
| 41 | + let rev_short = rev.get(..8).unwrap_or_default(); |
| 42 | + println!("cargo:rustc-env=GIT_REV={rev_short}"); |
| 43 | + |
| 44 | + // Combined version |
| 45 | + if let Some(exact) = exact_tag { |
| 46 | + Ok(exact) |
| 47 | + } else if &branch != "main" && &branch != "master" && &branch != "HEAD" { |
| 48 | + Ok(format!("{rev_short} ({branch})")) |
| 49 | + } else { |
| 50 | + Ok(format!("{rev_short}")) |
| 51 | + } |
| 52 | +} |
0 commit comments