From 76e81df7150d9445699fcb66e678c319b4655d8f Mon Sep 17 00:00:00 2001 From: Clement Tsang <34804052+ClementTsang@users.noreply.github.com> Date: Tue, 20 Jun 2023 05:52:54 +0000 Subject: [PATCH] other: clean up some build script code (#1218) Some build script formatting fixes and cleanup of some code. In particular, I found some of the nightly version handling code to look pretty gross so I separated out the parts into functions to clean it up a bit. --- build.rs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/build.rs b/build.rs index 0a051b83..b858a57b 100644 --- a/build.rs +++ b/build.rs @@ -12,9 +12,7 @@ fn create_dir(dir: &Path) -> io::Result<()> { match &res { Ok(()) => {} Err(err) => { - eprintln!( - "Failed to create a directory at location {dir:?}, encountered error {err:?}. Aborting...", - ); + eprintln!("Failed to create a directory at location {dir:?}, encountered error {err:?}. Aborting...",); } } @@ -58,6 +56,14 @@ fn btm_generate() -> io::Result<()> { Ok(()) } +fn extract_sha(sha: Option<&str>) -> Option<&str> { + sha.and_then(|sha: &str| sha.get(0..8)) +} + +fn output_nightly_version(version: &str, git_hash: &str) { + println!("cargo:rustc-env=NIGHTLY_VERSION={version}-nightly-{git_hash}"); +} + fn nightly_version() { const ENV_KEY: &str = "BTM_BUILD_RELEASE_CALLER"; @@ -65,20 +71,20 @@ fn nightly_version() { Some(var) if !var.is_empty() && var == "nightly" => { let version = env!("CARGO_PKG_VERSION"); - if let Some(git_hash) = option_env!("CIRRUS_CHANGE_IN_REPO") - .and_then(|cirrus_sha: &str| cirrus_sha.get(0..8)) - { - println!("cargo:rustc-env=NIGHTLY_VERSION={version}-nightly-{git_hash}"); - } else if let Some(git_hash) = - option_env!("GITHUB_SHA").and_then(|gha_sha: &str| gha_sha.get(0..8)) - { - println!("cargo:rustc-env=NIGHTLY_VERSION={version}-nightly-{git_hash}"); + if let Some(hash) = extract_sha(option_env!("CIRRUS_CHANGE_IN_REPO")) { + // May be set if we're building with Cirrus CI. + output_nightly_version(version, hash); + } else if let Some(hash) = extract_sha(option_env!("GITHUB_SHA")) { + // May be set if we're building with GHA. + output_nightly_version(version, hash); } else if let Ok(output) = std::process::Command::new("git") .args(["rev-parse", "--short=8", "HEAD"]) .output() { - let git_hash = String::from_utf8(output.stdout).unwrap(); - println!("cargo:rustc-env=NIGHTLY_VERSION={version}-nightly-{git_hash}"); + // If we're not building in either, we do the lazy thing and fall back to + // manually grabbing info using git as a command. + let hash = String::from_utf8(output.stdout).unwrap(); + output_nightly_version(version, &hash); } } _ => {}