diff --git a/build.rs b/build.rs index 97d2806..d9c4d25 100644 --- a/build.rs +++ b/build.rs @@ -1,4 +1,4 @@ -use std::{env, fs::File, io::Write, path::PathBuf}; +use std::{env, fs::File, io::Write, path::PathBuf, process::Command}; fn main() { // Put the linker script somewhere the linker can find it @@ -12,4 +12,34 @@ fn main() { // Only re-run the build script when memory.x is changed, // instead of when any part of the source code changes. println!("cargo:rerun-if-changed=memory.x"); + + let revision = env::var("BUILD_REVISION"); + match revision { + Ok(r) => { + // Skip if the environment variable is already set + println!("cargo:rustc-env=BUILD_REVISION={}", r); + } + Err(_) => { + let output = Command::new("git") + .args(&["rev-parse", "--short=7", "HEAD"]) + .output() + .expect("Failed to execute git command"); + + let dirty = !Command::new("git") + .args(&["status", "-s"]) + .output() + .expect("Failed to execute git command").stdout.is_empty(); + + let build_revision: String; + if dirty { + build_revision = String::from_utf8(output.stdout) + .expect("Invalid UTF-8 sequence") + "-dirty"; + } else { + build_revision = String::from_utf8(output.stdout) + .expect("Invalid UTF-8 sequence"); + } + + println!("cargo:rustc-env=BUILD_REVISION={}", build_revision.trim()); + } + }; } diff --git a/flake.nix b/flake.nix index a0afac6..62b2d6f 100644 --- a/flake.nix +++ b/flake.nix @@ -39,6 +39,7 @@ nativeBuildInputs = [ pkgs.llvm ]; buildPhase = '' + export BUILD_REVISION=${toString (self.shortRev or self.dirtyShortRev or "unknown")} cargo build --release --bin kirdy '';