AnyBot/build.rs

59 lines
2.6 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Which build this is, for 設定 › 更新, the phone and `anybot --version`: v<version>-<commit>.
//
// v0.0.1-36bc2be built from commit 36bc2be as it is
// v0.0.1-36bc2be-dirty built from 36bc2be with changes to what goes into the program
// v0.0.1 no git here (a source tarball)
//
// <version> is the one in Cargo.toml, the only place the number is kept. The commit comes from
// ANYBOT_GIT_COMMIT when it is set (make sets it, so the program and the dist file names agree),
// otherwise from git. The build time is not baked in: it is the program file's own time (src/version.rs).
use std::process::Command;
/// What goes into the program: a change anywhere else (docs, deploy scripts) doesn't make it "dirty".
const INPUTS: &[&str] = &["src", "box", "fonts", "icons", "mobile", "Cargo.toml", "Cargo.lock", "build.rs"];
fn git(args: &[&str]) -> Option<String> {
let out = Command::new("git").args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
(!s.is_empty()).then_some(s)
}
fn main() {
let number = std::env::var("CARGO_PKG_VERSION").unwrap_or_default();
let commit = match std::env::var("ANYBOT_GIT_COMMIT").ok().filter(|s| !s.trim().is_empty()) {
Some(c) => Some(c.trim().to_string()),
None => git(&["rev-parse", "--short=7", "HEAD"]).map(|c| {
let mut args = vec!["status", "--porcelain", "--untracked-files=no", "--"];
args.extend_from_slice(INPUTS);
let dirty = git(&args).is_some();
if dirty { format!("{c}-dirty") } else { c }
}),
};
let label = match commit {
Some(c) => format!("v{number}-{c}"),
None => format!("v{number}"),
};
println!("cargo:rustc-env=ANYBOT_VERSION={label}");
// Run again when the commit changes (commit, checkout, pull) or what goes into the program
// does (then it's compiled again anyway). Not on the index: `git status` rewrites it, and every
// rerun recompiles the whole program.
println!("cargo:rerun-if-env-changed=ANYBOT_GIT_COMMIT");
for p in INPUTS {
println!("cargo:rerun-if-changed={p}");
}
if let Some(dir) = git(&["rev-parse", "--absolute-git-dir"]) {
println!("cargo:rerun-if-changed={dir}/HEAD");
}
if let Some(common) = git(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
for p in ["refs/heads", "packed-refs"] {
if std::path::Path::new(&common).join(p).exists() {
println!("cargo:rerun-if-changed={common}/{p}");
}
}
}
}