diff --git a/cli/build.rs b/cli/build.rs index 87edcb75..87092c40 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -60,6 +60,8 @@ fn web_playground_files_present() -> bool { paths.iter().all(|p| Path::new(p).exists()) } +// When updating this function, don't forget to also update generate/build.rs which has a +// near-identical function. fn read_git_sha() -> Option { let crate_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); diff --git a/cli/generate/build.rs b/cli/generate/build.rs new file mode 100644 index 00000000..dcfd67b4 --- /dev/null +++ b/cli/generate/build.rs @@ -0,0 +1,32 @@ +use std::{env, path::PathBuf, process::Command}; + +fn main() { + if let Some(git_sha) = read_git_sha() { + println!("cargo:rustc-env=BUILD_SHA={git_sha}"); + } +} + +// This is copied from the build.rs in parent directory. This should be updated if the +// parent build.rs gets fixes. +fn read_git_sha() -> Option { + let crate_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + + if !crate_path + .parent()? + .parent() + .map_or(false, |p| p.join(".git").is_dir()) + { + return None; + } + + Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(crate_path) + .output() + .map_or(None, |output| { + if !output.status.success() { + return None; + } + Some(String::from_utf8_lossy(&output.stdout).to_string()) + }) +} diff --git a/cli/generate/src/render.rs b/cli/generate/src/render.rs index f4fb140f..62993d55 100644 --- a/cli/generate/src/render.rs +++ b/cli/generate/src/render.rs @@ -19,8 +19,9 @@ use super::{ const SMALL_STATE_THRESHOLD: usize = 64; const ABI_VERSION_MIN: usize = 14; const ABI_VERSION_MAX: usize = tree_sitter::LANGUAGE_VERSION; -const BUILD_VERSION: &str = env!("CARGO_PKG_VERSION"); const ABI_VERSION_WITH_METADATA: usize = 15; +const BUILD_VERSION: &str = env!("CARGO_PKG_VERSION"); +const BUILD_SHA: Option<&'static str> = option_env!("BUILD_SHA"); macro_rules! add { ($this: tt, $($arg: tt)*) => {{ @@ -280,9 +281,13 @@ impl Generator { } fn add_header(&mut self) { + let version = BUILD_SHA.map_or_else( + || BUILD_VERSION.to_string(), + |build_sha| format!("{BUILD_VERSION} ({build_sha})"), + ); add_line!( self, - "// Automatically generated by tree-sitter v{BUILD_VERSION}" + "/* Automatically generated by tree-sitter v{version} */", ); add_line!(self, ""); }