use std::env;
use std::process::Command;
fn git_output(args: &[&str]) -> Option<String> {
Command::new("git")
.args(args)
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn main() {
let sha =
git_output(&["rev-parse", "--short=10", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
println!("cargo:rustc-env=CARTOG_BUILD_SHA={sha}");
let describe = git_output(&["describe", "--tags", "--dirty", "--always"])
.unwrap_or_else(|| "unknown".to_string());
println!("cargo:rustc-env=CARTOG_BUILD_VERSION={describe}");
let mut features: Vec<String> = env::vars()
.filter_map(|(k, _)| {
k.strip_prefix("CARGO_FEATURE_")
.map(|rest| rest.to_ascii_lowercase().replace('_', "-"))
})
.collect();
features.sort();
let features_str = if features.is_empty() {
"none".to_string()
} else {
features.join(", ")
};
println!("cargo:rustc-env=CARTOG_BUILD_FEATURES={features_str}");
let install_source = if env::var_os("CARTOG_RELEASE_BUILD").is_some() {
"release-tarball"
} else {
"dev"
};
println!("cargo:rustc-env=CARTOG_INSTALL_SOURCE={install_source}");
println!("cargo:rerun-if-env-changed=CARTOG_RELEASE_BUILD");
let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_string());
println!("cargo:rustc-env=CARTOG_TARGET_TRIPLE={target}");
let mut watched = false;
for path in git_rerun_paths() {
println!("cargo:rerun-if-changed={path}");
watched = true;
}
if !watched {
println!("cargo:rerun-if-env-changed=CARTOG_BUILD_SHA");
}
}
fn git_rerun_paths() -> Vec<String> {
let mut paths = Vec::new();
if let Some(head) = git_output(&["rev-parse", "--git-path", "HEAD"]) {
paths.push(head);
}
if let Some(symref) = git_output(&["symbolic-ref", "--quiet", "HEAD"]) {
if let Some(ref_path) = git_output(&["rev-parse", "--git-path", &symref]) {
paths.push(ref_path);
}
}
if let Some(packed) = git_output(&["rev-parse", "--git-path", "packed-refs"]) {
paths.push(packed);
}
paths
}