From ae41cbe3dceb71269ab43e20217968d6622b33c7 Mon Sep 17 00:00:00 2001 From: Steveplays Date: Mon, 29 Jun 2026 09:04:33 +0200 Subject: [PATCH] Add Git information to cargo-gpu's `--version` CLI subcommand Added the commit hash and date to the `--version` CLI subcommand. --- crates/cargo-gpu/build.rs | 41 ++++++++++++++++++++++++++++++------- crates/cargo-gpu/src/lib.rs | 2 +- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/crates/cargo-gpu/build.rs b/crates/cargo-gpu/build.rs index 31a33575ce..e6d5cc186b 100644 --- a/crates/cargo-gpu/build.rs +++ b/crates/cargo-gpu/build.rs @@ -1,12 +1,39 @@ //! cargo-gpu build script. +use std::ffi::OsStr; + fn main() { - let git_hash = std::process::Command::new("git") - .args(["rev-parse", "HEAD"]) - .output() - .map_or_else( - |_| "unknown".to_owned(), - |output| String::from_utf8(output.stdout).unwrap_or_else(|_| "unknown".to_owned()), - ); + let git_directory = invoke_git(["rev-parse", "--git-dir"]); + println!("cargo:rerun-if-changed={git_directory}/HEAD"); + println!("cargo:rerun-if-changed={git_directory}/packed-refs"); + if let Ok(git_head) = std::fs::read_to_string(format!("{git_directory}/HEAD")) + && let Some(git_ref) = git_head.strip_prefix("ref: ") + { + println!("cargo:rerun-if-changed={git_directory}/{}", git_ref.trim()); + } + + let git_hash = invoke_git(["rev-parse", "HEAD"]); println!("cargo:rustc-env=GIT_HASH={git_hash}"); + + let git_date = invoke_git([ + "show", + "-s", + "--format=%cd", + "--date=format:%Y-%m-%d", + "HEAD", + ]); + println!("cargo:rustc-env=GIT_DATE={git_date}"); +} + +fn invoke_git(args: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + std::process::Command::new("git") + .args(args) + .output() + .ok() + .and_then(|output| String::from_utf8(output.stdout).ok()) + .unwrap_or_else(|| "unknown".to_owned()) } diff --git a/crates/cargo-gpu/src/lib.rs b/crates/cargo-gpu/src/lib.rs index eadde1c8d8..a8759c0415 100644 --- a/crates/cargo-gpu/src/lib.rs +++ b/crates/cargo-gpu/src/lib.rs @@ -153,7 +153,7 @@ impl Command { /// the Cli struct representing the main cli #[derive(clap::Parser)] -#[clap(author, version, about, subcommand_required = true)] +#[clap(author, version, long_version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("GIT_HASH"), "; ", env!("GIT_DATE"), ")"), about, subcommand_required = true)] #[non_exhaustive] pub struct Cli { /// The command to run.