build.rs (2107B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::process::Command; 18 19 fn run_command(command: &str, args: &[&str]) -> Result<String, String> { 20 let output = Command::new(command) 21 .args(args) 22 .output() 23 .map_err(|e| format!("Failed to execute {}: {}", command, e))?; 24 25 if output.status.success() { 26 Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) 27 } else { 28 Err(format!( 29 "Command failed: {} {:?}\nStderr: {}", 30 command, 31 args, 32 String::from_utf8_lossy(&output.stderr) 33 )) 34 } 35 } 36 37 fn main() -> Result<(), String> { 38 // Get project git dir 39 let git_dir = run_command("git", &["rev-parse", "--git-dir"])?; 40 41 // Watch HEAD 42 let head_path = format!("{git_dir}/HEAD"); 43 println!("cargo:rerun-if-changed={head_path}"); 44 45 // Watch HEAD ref 46 let head_content = 47 std::fs::read_to_string(head_path).map_err(|e| format!("Failed to read git HEAD: {e}"))?; 48 if let Some(ref_path) = head_content.strip_prefix("ref: ") { 49 println!("cargo:rerun-if-changed={git_dir}/{ref_path}"); 50 } 51 52 // Get the short commit hash 53 let commit_hash = run_command("git", &["rev-parse", "--short", "HEAD"])?; 54 55 // Set the environment variable VERSION 56 println!("cargo:rustc-env=GIT_HASH={}", commit_hash); 57 58 // Watch the build script also 59 println!("cargo:rerun-if-changed=build.rs"); 60 61 Ok(()) 62 }