From b148d64b2b3de909a2577cecab1e654430b622ff Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 30 Apr 2026 15:43:55 -0500 Subject: [PATCH] Make `git rev-parse` in `build.rs` optional with graceful fallback (#701) * Initial plan * Make git rev-parse optional in build.rs, fall back to empty string Agent-Logs-Url: https://github.com/microsoft/regorus/sessions/070084fe-288a-4029-b4a0-006ff18f8c94 Co-authored-by: anakrish <35780660+anakrish@users.noreply.github.com> * Use \"unknown\" as fallback for GIT_HASH; also honour GIT_HASH env var override Agent-Logs-Url: https://github.com/microsoft/regorus/sessions/50f82bf4-0ccc-4dbf-8455-6182849f02d4 Co-authored-by: anakrish <35780660+anakrish@users.noreply.github.com> * Fix cargo fmt formatting in build.rs Agent-Logs-Url: https://github.com/microsoft/regorus/sessions/0f7a9eec-20c7-4b8c-873d-4f5bae8b13c1 Co-authored-by: anakrish <35780660+anakrish@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: anakrish <35780660+anakrish@users.noreply.github.com> --- build.rs | 25 ++++++++++++++++++++----- src/builtins/opa.rs | 2 +- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/build.rs b/build.rs index 6fa5c07..9db6e18 100644 --- a/build.rs +++ b/build.rs @@ -18,11 +18,26 @@ fn main() -> Result<()> { // Supply information as compile-time environment variables. #[cfg(feature = "opa-runtime")] { - let output = std::process::Command::new("git") - .args(["rev-parse", "HEAD"]) - .output() - .expect("`git rev-parse HEAD` failed."); - let git_hash = String::from_utf8(output.stdout).unwrap(); + // Allow build systems (e.g. vcpkg, CI) to inject the commit hash directly + // via a GIT_HASH environment variable. If not set, attempt to read it from + // git. Fall back to "unknown" when git is unavailable or there is no .git + // directory (e.g. builds from source tarballs). + let git_hash = std::env::var("GIT_HASH").ok().unwrap_or_else(|| { + std::process::Command::new("git") + .args(["rev-parse", "HEAD"]) + .output() + .ok() + .and_then(|o| { + if o.status.success() { + Some(o.stdout) + } else { + None + } + }) + .and_then(|bytes| String::from_utf8(bytes).ok()) + .map(|s| s.trim().to_string()) + .unwrap_or_else(|| "unknown".to_string()) + }); println!("cargo:rustc-env=GIT_HASH={git_hash}"); } diff --git a/src/builtins/opa.rs b/src/builtins/opa.rs index 82811ee..c6bebeb 100644 --- a/src/builtins/opa.rs +++ b/src/builtins/opa.rs @@ -24,7 +24,7 @@ fn opa_runtime(span: &Span, params: &[Ref], args: &[Value], _strict: bool) obj.insert( Value::String("commit".into()), - Value::String(env!("GIT_HASH").into()), + Value::String(option_env!("GIT_HASH").unwrap_or("").into()), ); obj.insert(