I have cloned a remote git repo and created a new branch out of the main
branch. Now I want to get latest repo tag (if exists) at compile time. I was able to get latest commit hash at compile time. Below is my code
// build.rs
use std::process::Command;
fn main() {
let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}
// main.rs
fn main() {
println!("{}", env!("GIT_HASH"));
}
I would use the following command for getting the latest (in whichever way you'd like to define this) tag: git describe --tags --abbrev=0
(using git describe
).
Therefore this would be my solution:
build.rs
use std::{path::Path, process::Command};
fn main() {
// Check if the tags changed.
if Path::new(".git/refs/tags").exists() {
println!("cargo:rerun-if-changed=.git/refs/tags");
}
if Path::new(".git/packed-refs").exists() {
println!("cargo:rerun-if-changed=.git/packed-refs");
}
// Get the "latest" tag and store its name in the GIT_TAG environment variable.
let output = Command::new("git").args(&["describe", "--tags", "--abbrev=0"]).output().unwrap();
let git_tag = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_TAG={}", git_tag);
}
main.rs
fn main() {
println!("{}", env!("GIT_TAG"));
}
The idea is to run the build-script whenever a git tag related file on your system changes.
Note that this will result in problems if for example you have two tags pointing at the same commit.
Depending on your preferred shell there might be better options, but this seems to be the best cross platform command.