From e452385fde4d60970af5c16c99a0eb6af886439e Mon Sep 17 00:00:00 2001 From: Sebastian Holmin Date: Mon, 13 May 2024 12:16:06 +0200 Subject: [PATCH] Add check `git` binary and `.git` folder --- mullvad-version/build.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/mullvad-version/build.rs b/mullvad-version/build.rs index 3747a675b945..3485f175ecc6 100644 --- a/mullvad-version/build.rs +++ b/mullvad-version/build.rs @@ -66,8 +66,11 @@ fn compute_product_version(target: Target) -> String { // Rerun this build script on changes to the git ref that affects the build version. // NOTE: This must be kept up to date with the behavior of `git_rev_parse_commit_hash`. - rerun_if_git_ref_changed(&release_tag) - .expect("Failed to set 'cargo:rerun-if-changed' on git ref changes"); + // If an error is returned, we are not in a repository and a proper release version cannot be + // built. + if let Err(()) = rerun_if_git_ref_changed(&release_tag) { + return format!("{release_tag}-dev-local"); + }; // Get the git commit hashes for the latest release and current HEAD let head_commit_hash = git_rev_parse_commit_hash("HEAD"); @@ -87,9 +90,21 @@ fn compute_product_version(target: Target) -> String { /// Trigger rebuild of `mullvad-version` on changing branch (`.git/HEAD`), on changes to the ref of /// the current branch (`.git/refs/heads/$current_branch`) and on changes to the ref of the current /// release tag (`.git/refs/tags/$current_release_tag`). -fn rerun_if_git_ref_changed(release_tag: &str) -> std::io::Result<()> { +/// +/// Returns an error if not in a git repository, or the git binary is not in `PATH`. +fn rerun_if_git_ref_changed(release_tag: &str) -> Result<(), ()> { let git_dir = Path::new("..").join(".git"); + if !git_dir.exists() { + return Err(()); + } + + // Check that `git` can be executed + match Command::new("git").arg("--version").status() { + Ok(status) if status.success() => {} + _ => return Err(()), + }; + // The `.git/HEAD` file contains the position of the current head. If in 'detached HEAD' state, // this will be the ref of the current commit. If on a branch it will just point to it, e.g. // `ref: refs/heads/main`. Tracking changes to this file will tell us if we change branch, or @@ -104,7 +119,8 @@ fn rerun_if_git_ref_changed(release_tag: &str) -> std::io::Result<()> { let output = Command::new("git") .arg("branch") .arg("--show-current") - .output()?; + .output() + .expect("Failed to execute `git branch --show-current`"); let current_branch = String::from_utf8(output.stdout).unwrap(); let current_branch = current_branch.trim();