use std::path::Path;
use std::process::Command;
const GIT_HEAD_PATH: &str = "../.git/HEAD";
const JJ_OP_HEADS_PATH: &str = "../.jj/repo/op_heads/heads";
fn main() {
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
println!("cargo:rerun-if-env-changed=NIX_JJ_GIT_HASH");
let git_hash = get_git_hash_from_nix().or_else(|| {
if Path::new(GIT_HEAD_PATH).exists() {
println!("cargo:rerun-if-changed={GIT_HEAD_PATH}");
} else if Path::new(JJ_OP_HEADS_PATH).exists() {
println!("cargo:rerun-if-changed={JJ_OP_HEADS_PATH}");
}
get_git_hash_from_jj().or_else(get_git_hash_from_git)
});
if let Some(git_hash) = git_hash {
println!("cargo:rustc-env=JJ_VERSION={version}-{git_hash}");
} else {
println!("cargo:rustc-env=JJ_VERSION={version}");
}
let docs_symlink_path = Path::new("docs");
println!("cargo:rerun-if-changed={}", docs_symlink_path.display());
if docs_symlink_path.join("index.md").exists() {
println!("cargo:rustc-env=JJ_DOCS_DIR=docs/");
} else {
println!("cargo:rustc-env=JJ_DOCS_DIR=../docs/");
}
}
fn get_git_hash_from_nix() -> Option<String> {
std::env::var("NIX_JJ_GIT_HASH")
.ok()
.filter(|s| !s.is_empty())
}
fn get_git_hash_from_jj() -> Option<String> {
Command::new("jj")
.args([
"--ignore-working-copy",
"--color=never",
"log",
"--no-graph",
"-r=@-",
"-T=commit_id ++ '-'",
])
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| {
let mut parent_commits = String::from_utf8(output.stdout).unwrap();
parent_commits.truncate(parent_commits.trim_end_matches('-').len());
parent_commits
})
}
fn get_git_hash_from_git() -> Option<String> {
Command::new("git")
.args(["rev-parse", "HEAD"])
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| {
str::from_utf8(&output.stdout)
.unwrap()
.trim_end()
.to_owned()
})
}